C# 当使用Contains或IndexOf方法检查值的状态或索引时,如何从文本框中检索值?

C# 当使用Contains或IndexOf方法检查值的状态或索引时,如何从文本框中检索值?,c#,arrays,contains,indexof,C#,Arrays,Contains,Indexof,我只是试着检查数组是否包含一个特定的值,或者它的索引是什么,不是通过在括号中显示相应的值,而是在文本框中键入它们。怎么办 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; v

我只是试着检查数组是否包含一个特定的值,或者它的索引是什么,不是通过在括号中显示相应的值,而是在文本框中键入它们。怎么办

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);
    }
}

如果您只想从文本框中检索一个int值,并查看该值是否存在于值数组中:

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;
}
这只是从文本框中检索字符串值,将其转换为整数,并在值数组中查找其索引。如果“position”变量大于-1,则表示它在数组中找到了有效位置

选中此项:
你可以这样做

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);
        }

你的具体问题是什么?您看到错误消息了吗?一个
异常
?是如何将
文本框解析为
int
?好的,使用
int.Parse(Textbox.Text)
或者更好的
int.TryParse(Textbox.Text,out int-value)
问题很清楚,我想。。。如何从textbox中获取值并检查其索引或是否存在于数组中?问题并不清楚,因为textbox的值是
string
not
int
类型,并且您没有解释是要将其转换为int还是做其他事情。你看过蒂姆的评论了吗?这就是你想要做的吗?@TimSchmelter,这给了我格式异常错误我没有使用:if(array>-1)就做了同样的事情,我一直在标签上得到-1?“-1”在数组中表示什么?@CavidHummatov如果返回-1,则表示无法在数组中找到值。此处的“状态”表示什么?它给出了“上下文中不存在”错误。我在if语句中声明了布尔值,因此它只存在于上下文中。如果您想在其他地方使用它,请在需要使用它的更高范围内声明它。回答您的问题:我没有使用:If(array>-1)就做了同样的事情,我一直在标签上得到-1?“-1”在数组中指的是什么?答:您使用的是Int数组,因此在传递文本框值之前,您需要将其中的值解析为Int,并将其传递给Indexof function.bool status=values.Contains(Convert.ToInt16(txtValue.Text));lblindex.Text=status.ToString();-给出了格式异常错误。我刚刚发现两者一起使用会引发格式异常错误。原因是什么?如何保持这两种方法都没有错误?