在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
在c# WinApp中,我如何同时添加文本和值到我的组合框的项目? 我做了一个搜索,通常答案是使用“绑定到一个源”..但在我的情况下,我没有一个绑定源准备在我的程序… 我怎么做这样的事情:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
当前回答
// Bind combobox to dictionary
Dictionary<string, string>test = new Dictionary<string, string>();
test.Add("1", "dfdfdf");
test.Add("2", "dfdfdf");
test.Add("3", "dfdfdf");
comboBox1.DataSource = new BindingSource(test, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
// Get combobox selection (in handler)
string value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;
其他回答
// Bind combobox to dictionary
Dictionary<string, string>test = new Dictionary<string, string>();
test.Add("1", "dfdfdf");
test.Add("2", "dfdfdf");
test.Add("3", "dfdfdf");
comboBox1.DataSource = new BindingSource(test, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
// Get combobox selection (in handler)
string value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).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调用仍然有效。
类创造:
namespace WindowsFormsApplication1
{
class select
{
public string Text { get; set; }
public string Value { get; set; }
}
}
Form1代码:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<select> sl = new List<select>();
sl.Add(new select() { Text = "", Value = "" });
sl.Add(new select() { Text = "AAA", Value = "aa" });
sl.Add(new select() { Text = "BBB", Value = "bb" });
comboBox1.DataSource = sl;
comboBox1.DisplayMember = "Text";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
select sl1 = comboBox1.SelectedItem as select;
t1.Text = Convert.ToString(sl1.Value);
}
}
}
您可以使用此代码将一些项插入到具有文本和值的组合框中。
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"/>
您应该在运行时使用动态对象来解析组合框项。
comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";
comboBox.Items.Add(new { Text = "Text", Value = "Value" });
(comboBox.SelectedItem as dynamic).Value