【问题标题】:For loop with if statement is not sending the value to the text box带有 if 语句的 For 循环未将值发送到文本框
【发布时间】:2016-11-15 10:01:19
【问题描述】:

我将数组 1 中的特定位置 [0] 与数组 2 中的位置 [i] 进行比较,当它们彼此相等时,我希望将具有位置 [i] 的第三个数组放置在文本框字段中。

问题是值不会放在文本框中。 我检查了这些值是否相等并且它们是相等的。

MessageBox.Show(" id [0] is : " + id[0] + "orderID [0] is : " + orderID[0] + " name 0 is : " + name[0]);

消息框显示:

这是for循环。

for (int i = 0; i < id.Length; i++)
{
    if (orderID[0] == id[i])
    {
        text1.Text = name[i];
    }

}

编辑: 声明:

string[] orderID = new string[aa.Length];
        string[] id = new string[bb.Length];
        string[] name = new string[bb.Length];

【问题讨论】:

  • 你想要什么,要打印的MessageBox?当前操作有什么问题
  • 使用List&lt;T&gt; 似乎会更容易、更简单、更不容易出错
  • @un-lucky - 我编辑了我的帖子。我忘了贴几行。
  • so .. 在 if 语句中放一个断点,看看它是否命中 ..
  • orderIDid 字符串数组吗?

标签: c# arrays if-statement for-loop


【解决方案1】:

您似乎在 id[0]orderID[0] 中有换行符 '\n',因为我在您的代码中没有看到它们,但 MessageBox 显示了它们。

当你填充数组时,修剪字符串或像这样转换它们:

orderID = orderID.Select(s => (s ?? "").Trim()).ToArray();
id = id.Select(s => (s ?? "").Trim()).ToArray();

然后你可以将你的代码简化为

int i = id.IndexOf( orderID[0] );      // this returns -1 if not found
if ( i >= 0 ) text1.Text = name[i];

【讨论】:

  • 我已经尝试过你的建议,但我收到了这个错误:PrintScreen
  • 我没想到会那么糟糕..那么你可以用(s ?? "").Trim替换s.Trim
  • 它适用于 [1st part : ](prntscr.com/bt8ll7) 但不适用于 2nd part : 代码 screenshot 因为长度。我将文件 1a.dll 拆分为 2 个数组字符串。第一个是偶数,第二个是奇数。
  • 将代码添加到您的问题中,也许是 1a.dll 文件的示例
  • 其实.. 最好把它作为一个新任务发布
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多