【问题标题】:How to retrieve value from a textbox when using Contains or IndexOf methods to check the status or index of values?使用 Contains 或 IndexOf 方法检查值的状态或索引时如何从文本框中检索值?
【发布时间】:2018-05-04 09:10:21
【问题描述】:

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

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

【问题讨论】:

  • 您的具体问题是什么?您是否看到错误消息? Exception?
  • 您的问题是如何将您的Textbox.Text 解析为int?好吧,使用int.Parse(Textbox.Text) 或更好的int.TryParse(Textbox.Text, out int value)
  • 我认为问题很明确......如何从文本框中获取值并检查其索引或数组中的存在?
  • 问题不清楚,因为文本框的值是 string 而不是 int 类型,并且您没有解释是将其转换为 int 还是执行其他操作。你读过蒂姆的评论吗?这就是你想要做的吗?
  • @TimSchmelter 给我格式异常错误

标签: c# arrays contains indexof


【解决方案1】:

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

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

这只是从文本框中检索字符串值,将其转换为整数,然后在 values 数组中查找它的索引。如果 "position" 变量大于 -1,则表示它在数组中找到了有效位置。

检查这个: Checking if a string array contains a value, and if so, getting its position

【讨论】:

  • 我在不使用 : if (array > -1) 的情况下也在做同样的事情,而且我一直在标签上得到 -1?数组中的“-1”指的是什么?
  • @CavidHummatov 如果返回 -1 表示它无法在数组中找到值。
  • 这里的“状态”表示什么?它给出“上下文中不存在”错误
  • 我在 if 语句中声明了我的布尔值,所以它只存在于那里。如果您想在其他地方使用它,请在需要使用它的更高范围内声明它。
【解决方案2】:

你可以这样做

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

【讨论】:

  • 回复您的问题:我在不使用 : if (array > -1) 的情况下也在做同样的事情,并且我一直在标签上得到 -1? “-1”在数组中指的是什么? Ans:您使用的是 Int 数组,因此在传递文本框值之前,您需要将值解析为 int 并将其传递给 Indexof 函数。
  • bool status = values.Contains(Convert.ToInt16(txtValue.Text)); lblindex.Text = status.ToString(); - 给出格式异常错误。
  • 我刚刚发现同时使用它们会引发 FormatException 错误。原因是什么?如何保持这两种方法都没有错误?
猜你喜欢
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
相关资源
最近更新 更多