Tôi đang tạo combobox từ List
của KeyValuePair<int, string>
. Cho đến nay nó đã được làm việc rất tốt trong việc cung cấp cho người dùng tên mô tả trong khi trả lại cho tôi một id số.
Tuy nhiên, bất cứ điều gì tôi cố gắng, tôi không thể chọn giá trị ban đầu được chọn.Chọn giá trị được chọn ban đầu cho ComboBox có Danh sách KeyValuePair làm DataSource
public StartUpForm()
{
InitializeComponent();
FlowLayoutPanel flowLayout = new FlowLayoutPanel(); //This is necessary to protect the table, which is for some reason collapsing...
flowLayout.FlowDirection = FlowDirection.TopDown;
flowLayout.AutoSize = true;
flowLayout.AutoSizeMode = AutoSizeMode.GrowAndShrink;
var comboBox = new ComboBox();
{
var choices = new List<KeyValuePair<int, string>>();
choices.Add(new KeyValuePair<int, string>(1, "hello"));
choices.Add(new KeyValuePair<int, string>(2, "world"));
comboBox.DataSource = choices;
comboBox.ValueMember = "Key";
comboBox.DisplayMember = "Value";
flowLayout.Controls.Add(comboBox);
}
Controls.Add(flowLayout);
//None of these work:
comboBox.SelectedValue = 2;
comboBox.SelectedValue = 2.ToString();
comboBox.SelectedValue = new KeyValuePair<int, string>(2, "world");
comboBox.SelectedValue = "world";
comboBox.SelectedItem = 2;
comboBox.SelectedItem = 2.ToString();
comboBox.SelectedItem = new KeyValuePair<int, string>(2, "world");
comboBox.SelectedItem = "world";
return;
}
Kết quả luôn luôn là như nhau:
Làm thế nào tôi có thể chọn giá trị ban đầu được lựa chọn trong một ComboBox
sử dụng như DataSource một List<KeyValuePair<int, string>>
?
Tuyệt vời, nó hoạt động! Cảm ơn! Một câu hỏi: Làm thế nào là một trong những nghĩa vụ phải biết điều này? – Antonio
@Antonio Đã xảy ra sự cố tương tự. . . nhiều năm trước. – LarsTech