情况是我有 2 个控件,一个文本框和一个组合框。用户可以在组合框中选择某些内容,它会用值成员填充文本框,如果用户在文本框中键入内容,我想检查它是否存在于组合框的值中,然后选择相应的显示成员。
我期望的方法是这样的
if(cmb1.valueMembers.Contains(txt1.Text))
但是我找不到这样的东西,我还以为循环它们可以找到它?所以我有
foreach (System.Data.DataRowView row in cmb1.Items)
{}
但在行中的任何位置都找不到值成员?
谢谢
最佳答案
好吧,这是一个简单的例子,但我想这就是主要思想。我们有一个 MyClass
,其中包含 ValueMember 的 Id
和 DisplayMember 的 Name
。
public partial class Form1 : Form
{
class MyClass
{
public MyClass(string name, int id)
{
Name = name;
Id = id;
}
public string Name { get; set; }
public int Id { get; set; }
}
List<MyClass> dsList = new List<MyClass>();
public Form1()
{
for (int i = 0; i < 10; i++)
{
dsList.Add(new MyClass("Name" + i , i));
}
InitializeComponent();
comboBox1.DataSource = dsList;
comboBox1.ValueMember = "Id";
comboBox1.DisplayMember = "Name";
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//Checks if item with the typed Id exists in the DataSource
// and selects it if it's true
int typedId = Convert.ToInt32(textBox1.Text);
bool exist = dsList.Exists(obj => obj.Id == typedId);
if (exist) comboBox1.SelectedValue = typedId;
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
MyClass obj = comboBox1.SelectedValue as MyClass;
if (obj != null) textBox1.Text = obj.Id.ToString();
}
}
如果有不清楚的地方,请随时询问。
PS:在示例中,我假设将在文本框中键入整数
关于c# - 如何确定组合框是否包含值成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13762719/