下面是我尝试从组合框中提取密钥的代码。如果您查看foreach (int value in comboBox1.ValueMember)
,我想将值90与组合框数据源中添加的所有键进行比较。该怎么做?
namespace SetComboBoxEnum
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
AddComboBoxItems(comboBox1, 10, "Sunday");
AddComboBoxItems(comboBox1, 20, "Tuesday");
AddComboBoxItems(comboBox1, 100, "Friday");
}
private void button1_Click(object sender, EventArgs e)
{
this.textBox1.Text = comboBox1.SelectedValue.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
bool s=true;
int x = 90;
foreach (int value in comboBox1.ValueMember)
{
if (x == value)
{
s = true;
}
}
if (s == true)
{ comboBox1.SelectedValue = x; }
else
{
comboBox1.Text = x.ToString();
}
}
IDictionary<int, string> comboSource = new Dictionary<int, string>();
public void AddComboBoxItems(ComboBox cmbbox, int itemvalue, string itemstring)
{
comboSource.Add(new KeyValuePair<int, string>(itemvalue, itemstring));
cmbbox.DataSource = new BindingSource(comboSource, null);
cmbbox.DisplayMember = "Value";
cmbbox.ValueMember = "Key";
}
}
}
答案 0 :(得分:0)
ComboBox.Items.Contains(对象值)将用于检查,因为键成为了comboBox中所有项的值。使用类似以下代码
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
AddComboBoxItems(comboBox1, 10, "Sunday");
AddComboBoxItems(comboBox1, 20, "Tuesday");
AddComboBoxItems(comboBox1, 100, "Friday");
}
IDictionary<int, string> comboSource = new Dictionary<int, string>();
public void AddComboBoxItems(ComboBox cmbbox, int itemvalue, string itemstring)
{
comboSource.Add(new KeyValuePair<int, string>(itemvalue, itemstring));
cmbbox.DataSource = new BindingSource(comboSource, null);
cmbbox.DisplayMember = "Value";
cmbbox.ValueMember = "Key";
}
private void button2_Click(object sender, EventArgs e)
{
int x = 20;
if (comboBox1.Items.Contains(x))
{ comboBox1.SelectedValue = x; }
else
{
comboBox1.Text = x.ToString();
}
}
}