我有一个组合框,我在其中设置了DataSource Value,但是当我尝试设置SelectedValue时,ComboBox返回null。所以请帮忙。
BindingList<KeyValuePair<string, int>> m_items =
new BindingList<KeyValuePair<string, int>>();
for (int i = 2; i <= 12; i++)
m_items.Add(new KeyValuePair<string, int>(i.ToString(), i));
ComboBox cboGridSize = new ComboBox();
cboGridSize.DisplayMember = "Key";
cboGridSize.ValueMember = "Value";
cboGridSize.DataSource = m_items;
cboGridSize.SelectedValue = 4;
当我将SelectedValue设置为4时,它返回NULL。
答案 0 :(得分:0)
同意@Laazo更改为字符串。
cboGridSize.SelectedValue = "4";
或与此类似的东西
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
"Index: " + selectedIndex.ToString());
并参考这看起来好像对你的问题有好处:
答案 1 :(得分:0)
我在尝试解决此问题的同时遇到了这个问题。我通过创建以下扩展方法解决了该问题。
public static void ChooseItem<T>(this ComboBox cb, int id) where T : IDatabaseTableClass
{
// In order for this to work, the item you are searching for must implement IDatabaseTableClass so that this method knows for sure
// that there will be an ID for the comparison.
/* Enumerating over the combo box items is the only way to set the selected item.
* We loop over the items until we find the item that matches. If we find a match,
* we use the matched item's index to select the same item from the combo box.*/
foreach (T item in cb.Items)
{
if (item.ID == id)
{
cb.SelectedIndex = cb.Items.IndexOf(item);
}
}
}
我还创建了一个名为IDatabaseTableClass的接口(可能不是最佳名称)。该接口具有一个属性,即int ID {get;组; }为了确保我们确实有一个ID可以与参数中的int id进行比较。