如何检查新项目添加是否在组合框项目列表中
问题描述:
相同的组合框项目中如何检查添加到combox的新项目.
你能帮我吗?
我尝试了以下代码...
how to check new item adding to the combox is in the same combobox items.
can u plz help me..
i tried following code...
for (int i = 0; i <= cmbdep.Items.Count; i++)
{
if (cmbdep.Text == cmbdep.Items.ToString())
{
c = 1;
break;
}
else
{
c = 0;
}
}
但不起作用...
but not working...
答
我不确定您为什么认为这会起作用.为什么不使用foreach遍历项目? Items.ToString()显然未使用您的索引.尝试Items [i] .Text,这意味着您不会一遍又一遍地检查同一件事,而是检查每个单独的项目.
另外,为什么用"c"代替布尔值?
I am not sure why you think this will work. Why not use foreach to iterate over the items ? Items.ToString() is obviously not using your index. Try Items[i].Text, that would mean you were not checking the same thing over and over, but instead checking each individual item.
Also, why use ''c'' instead of a bool ?
这一切都没有意义,外加一些错误:
与项目数量相比,您的迭代次数增加了一个;在循环结束条件中使用<
而不是<=
.
同样,cmbdep.Items.ToString()
不会返回您期望的结果.您可能需要按索引的项目,因此请使用cmbdep.Items[i].ToString()
.c
的计算没有任何意义.您是否只想检查文本是否为其中一项? (您不必回答.:-))—SA
It all makes no sense, plus a couple of bugs:
You make one iteration more that the number of items; use<
instead of<=
in the loop ending condition.
Also,cmbdep.Items.ToString()
will not return what you expect. You probably wanted an item by index, so usecmbdep.Items[i].ToString()
.
The calculation ifc
makes no sense. Do you simply want check up if the text is one of the items? (You don''t have to answer. :-))—SA