[英]How to set Selectedvalue in Combobox c#
I have one combobox in which I have set DataSource Value, but when I try to set SelectedValue, the ComboBox returns null. 我有一个组合框,其中设置了数据源值,但是当我尝试设置SelectedValue时,ComboBox返回null。 so please help.
所以请帮忙
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;
when I set SelectedValue with 4 then it returns NULL. 当我将SelectedValue设置为4时,它将返回NULL。
Agree with @Laazo change to string. 同意@Laazo更改为字符串。
cboGridSize.SelectedValue = "4";
or somthing similar to this 或类似的东西
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
"Index: " + selectedIndex.ToString());
and refer to this looks as if it would be good for your issue: 并指出这看起来对您的问题有好处:
I came across this question while also trying to solve this problem. 我在尝试解决此问题的同时遇到了这个问题。 I solved it by creating the following extension method.
我通过创建以下扩展方法解决了它。
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);
}
}
}
I also created an interface called IDatabaseTableClass (probably not the best name). 我还创建了一个名为IDatabaseTableClass的接口(可能不是最佳名称)。 This interface has one property, int ID { get;
该接口具有一个属性,即int ID {get; set;
组; } To ensure that we actually have an ID to compare to the int id from the parameter.
为了确保我们实际上有一个ID与参数中的int id进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.