【发布时间】:2016-03-25 17:33:33
【问题描述】:
我试图通过遍历值并找到与我的直径变量匹配的值来分配组合框索引。 (组合框项会根据直径而变化,例如,某些管道类型只有 0.5"、1.0" 而其他可能具有中间 0.75" 值)。
代码比较似乎永远不会成立(因此 myIndex 从未在初始化之外分配任何内容),尽管当我在其上放置断点时,文本字符串会在适当的迭代中匹配。
int myIndex = 0;
for (int i = 0; i <= cboDiameter.Items.Count-1; i++)
{
if (cboDiameter.GetItemText(cboDiameter.Items[i]) == formPipe.diameter.ToString())
{
//this line never executes, even when there's seemingly a text match
myIndex = i;
}
}
cboDiameter.SelectedIndex = myIndex;
这是我用来分配管道直径的,但它被截断了。 (例如,当组合框文本为“1.0”时,管道直径被指定为“1”
//assign the value of the dropdown to the object
double.TryParse(cboDiameter.GetItemText(cboDiameter.SelectedItem), out value);
formPipe.diameter = value;
【问题讨论】:
-
你确定
formPipe.diameter.ToString()返回一个带有"的字符串吗? -
你比较字符串。
1.0和1这样的字符串不相同。 -
你需要使用
.EndsWith函数或者.Contains和.Split() -
你调试过你的代码吗?你发现了什么?
-
威梅尔是正确的。 formPipe.diameter = 1.0,但是当我使用.ToString()方法时,它被截断为1。有没有办法避免这种截断?
标签: c# for-loop text-comparison