在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
当前回答
Visual Studio 2013是这样做的:
单一项目:
comboBox1->Items->AddRange(gcnew cli::array< System::Object^ >(1) { L"Combo Item 1" });
多个项目:
comboBox1->Items->AddRange(gcnew cli::array< System::Object^ >(3)
{
L"Combo Item 1",
L"Combo Item 2",
L"Combo Item 3"
});
不需要重写类或包含任何其他内容。是的,comboBox1->SelectedItem和comboBox1->SelectedIndex调用仍然有效。
其他回答
一个使用DataTable的例子:
DataTable dtblDataSource = new DataTable();
dtblDataSource.Columns.Add("DisplayMember");
dtblDataSource.Columns.Add("ValueMember");
dtblDataSource.Columns.Add("AdditionalInfo");
dtblDataSource.Rows.Add("Item 1", 1, "something useful 1");
dtblDataSource.Rows.Add("Item 2", 2, "something useful 2");
dtblDataSource.Rows.Add("Item 3", 3, "something useful 3");
combo1.Items.Clear();
combo1.DataSource = dtblDataSource;
combo1.DisplayMember = "DisplayMember";
combo1.ValueMember = "ValueMember";
//Get additional info
foreach (DataRowView drv in combo1.Items)
{
string strAdditionalInfo = drv["AdditionalInfo"].ToString();
}
//Get additional info for selected item
string strAdditionalInfo = (combo1.SelectedItem as DataRowView)["AdditionalInfo"].ToString();
//Get selected value
string strSelectedValue = combo1.SelectedValue.ToString();
我喜欢fab的答案,但不想为我的情况使用字典,所以我替换了一个元组列表。
// set up your data
public static List<Tuple<string, string>> List = new List<Tuple<string, string>>
{
new Tuple<string, string>("Item1", "Item2")
}
// bind to the combo box
comboBox.DataSource = new BindingSource(List, null);
comboBox.ValueMember = "Item1";
comboBox.DisplayMember = "Item2";
//Get selected value
string value = ((Tuple<string, string>)queryList.SelectedItem).Item1;
您应该在运行时使用动态对象来解析组合框项。
comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";
comboBox.Items.Add(new { Text = "Text", Value = "Value" });
(comboBox.SelectedItem as dynamic).Value
这类似于其他一些答案,但是很紧凑,如果已经有一个列表,就避免了转换到字典。
给定一个窗口窗体上的ComboBox“ComboBox”和一个具有字符串类型属性Name的类SomeClass,
List<SomeClass> list = new List<SomeClass>();
combobox.DisplayMember = "Name";
combobox.DataSource = list;
这意味着SelectedItem是list中的SomeClass对象,并且组合框中的每个项目将使用其名称显示。
您可以使用此代码将一些项插入到具有文本和值的组合框中。
C#
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
combox.Items.Insert(0, "Copenhagen");
combox.Items.Insert(1, "Tokyo");
combox.Items.Insert(2, "Japan");
combox.Items.Insert(0, "India");
}
XAML
<ComboBox x:Name="combox" SelectionChanged="ComboBox_SelectionChanged_1"/>