[英]C# - How to check if the user's input is present in the ComboBox (used Data Bound Items)
[英]How to check user input in combobox in c#
我有一个从名为class1的类填充的ComboBox,然后从该类创建了名为obj的对象,我使用SqlDataReader
combobox1.DataSource = obj.Myfunction();
combobox1.ValueMember = "ID";
combobox1.DisplayMember = "Name";
并且用户还可以在ComboBox中写我要检查用户输入是否在ComboBox项中
if( comboBox1.Items.Contains(comboBox1.Text) )
//do something
else
{
MessageBox.Show("The comboBox1 contains new value");
}
但结果错误
我不想使用其他方法,例如SqlDataAdapter
谢谢先进
更新
作为临时解决方案,我使用了这段代码
int m = combobox1.SelectedIndex;
if (((class1)combobox1.Items[m]).Name.ToString() == combobox1.Text)
{
}
else
{
MessageBox.Show("The comboBox1 contains new value");
}
再次感谢你
我的解决方案有点冗长,但这可以解决您的问题
int count = 0;
for (int i = 0; i < comboBox1.Items.Count; i++)
{
string value = comboBox1.GetItemText(comboBox1.Items[i]);
if (value.Contains(comboBox1.Text))
{
count++;
break;
}
}
if (count > 0)
{
//do something
}
else
{
MessageBox.Show("The comboBox1 contains new value");
}
这段代码非常简单易懂,但是您可以使用LINQ来缩短代码。
我猜这里,但我想从
obj.Myfunction();
(您要设置为数据源的)不是List<string>
,因此,当检查combobox的内部集合是否包含string
(从comboBox1.Text
返回)时,它不包含字符串,而是一个对象。 因为这两个总是不同的( object
和string
),所以它总是错误的。
您是否尝试过将数据源设置为字符串列表?
Items是ItemCollection,而不是字符串列表。 在您的情况下,它是ComboboxItem的集合,您需要检查其Content属性。
comboboxId.Items.Cast<ComboBoxItem>().Any(com=> com.Content.Equals("Your string"));
我假设您正在使用您的类类型的列表绑定到组合。
您应针对组合框的来源进行验证,例如-
List<ClassType> cboSource = comboBox1.DataSource as List<ClassType>;
var itemAlreadyThere = cboSource.Any(a => a.Name == comboBox1.Text);
if (itemAlreadyThere)
{
MessageBox.Show("The comboBox1 contains old value");
}
//do something
else
{
MessageBox.Show("The comboBox1 contains new value");
}
作为建议,不要强制转换组合数据源,而应使用私有变量,然后将其填充并用于绑定到组合和进行验证
几个月前,我有这种行为。
我用类数据填充了一个组合框
class MyValue
{
public string ID { get; set; }
public string prop1 { get; set; }
public string prop2 { get; set; }
public int Value { get; set; }
public static List<MyValue> Get()
{
//create a list of MyValues and return it
return new List<MyValue>();
}
}
在GUI中:
mycombo.ValueMember = "ID";
mycombo.DisplayMember = "prop1";
mycombo.DataSource = MyValue.Get();
之后,我将selectedvalue作为属性:
public MyValue SelectedValue
{
get
{
if(mycombo.SelectedValue is MyValue)
return (MyValue)mycombo.SelectedValue);
else
{
MessageBox.Show(string.Format("{0} as new value", mycombo.SelectedText));
return new MyValue{prop1 = mycombo.SelectedText};
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.