The situation is that I have 2 controls, a text box and a combo box. The user can select something in the combo box, it fills the text box with the value member, if the user types into the text box, I want to check if it exists in the combo box's values and then select the corresponding display member.
The method I was expecting to be there was something like
if(cmb1.valueMembers.Contains(txt1.Text))
but I can't find anything like this, I also thought looping through them could find it? so I've got
foreach (System.Data.DataRowView row in cmb1.Items)
{}
but can't find the value member anywhere in the row?
Thanks
Ok, here's a simple example but I guess that's the main idea. We have a MyClass
which have Id
for the ValueMember and Name
for the DisplayMember.
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();
}
}
Feel free to ask if something's not clear.
PS: In the example I'm assuming that integers will be typed in the textbox