-2

I just try to check if an array contains a particular value or what is index of it not by showing respective values in brackets but typing them on textbox. How to go about that?

private void button3_Click(object sender, EventArgs e)
{
    int[] values = new int[6];
    values[0] = 2;
    values[1] = 9;
    values[2] = 5;
    values[3] = 15;
    values[4] = 8;
    values[5] = 25
    bool status = values.Contains(?);//I want to retrieve it from txtbox  
    label1.Text = $"{status}";
    int indexi = Array.IndexOf(values,?); //same is true for this method aswell.         
    label2.Text = $"{indexi}";


    foreach (int item in values)
    {               
        listBox1.Items.Add(item);
    }
}

2 Answers2

0

If you just want to retrieve an int value from a textbox and see if that number exists in the values array:

int position = Array.IndexOf(values, Convert.toInt32(Textbox.Text)); 
if (position > -1) //If it finds the index position it will be greater than -1
{
   bool status = true;
}

This simply retrieves the string value from the textbox, converts it to a integer and will look for it's index in the values array. If "position" variable is greater than -1 that means it found a valid position in the array.

Check this: Checking if a string array contains a value, and if so, getting its position

0

You can do it like this

int[] values = new int[6];
        values[0] = 2;
        values[1] = 9;
        values[2] = 5;
        values[3] = 15;
        values[4] = 8;
        values[5] = 25;
        bool status = values.Contains(Convert.ToInt16(txtValue.Text));//I want to retrieve it from txtbox  
        lblindex.Text = status.ToString();
        int indexi =Array.IndexOf(values,Convert.ToInt16(txtValue.Text)); //same is true for this method aswell.         
        lblindex.Text = indexi.ToString();
        foreach (int item in values)
        {
            listBox1.Items.Add(item);
        }
swapnil kamle
  • 115
  • 1
  • 8
  • Reply on Your Question:I was doing the same without using : if (array > -1) and I got -1 on the label all the time? what does "-1" refers to in the array? Ans: You are using Int Array, so before passing the textbox value you need to parse the value in to int and pass it to Indexof function. – swapnil kamle May 04 '18 at 09:37
  • bool status = values.Contains(Convert.ToInt16(txtValue.Text)); lblindex.Text = status.ToString(); - gives format exception error. – Cavid Hummatov May 04 '18 at 10:19
  • I've just figure out that using them both together throws FormatException error. What was the reason? how to keep both of methods without error? – Cavid Hummatov May 04 '18 at 10:50