如何在c#.net的组合框中检索值tem对的值?
我有一个表单,在这个表单中,我需要用数据库中的文本-值对填充一个组合框,这样我就可以在数据库的更新查询中使用该值 我发现了一些方法,它使用一个类来创建同时具有文本和值的对象,如下所示:如何在c#.net的组合框中检索值tem对的值?,c#,combobox,C#,Combobox,我有一个表单,在这个表单中,我需要用数据库中的文本-值对填充一个组合框,这样我就可以在数据库的更新查询中使用该值 我发现了一些方法,它使用一个类来创建同时具有文本和值的对象,如下所示: class RequestType { public string Text { get; set; } public string Value { get; set; } public RequestType(string text, string va
class RequestType
{
public string Text { get; set; }
public string Value { get; set; }
public RequestType(string text, string val)
{
Text = text;
Value = val;
}
public override string ToString()
{
return Text;
}
我像这样把它们添加到组合框中
RequestType type1 = new RequestType("Label 1", "Value 1");
RequestType type2 = new RequestType("Label 2", "Value 2");
comboBox1.Items.Add(type1);
comboBox1.Items.Add(type2);
comboBox1.SelectedItem = type2;
RequestType t = comboBox1.SelectedItem as RequestType;
现在我不知道如何检索所选项目的值,即id标签1被选中,它必须返回值1,如果标签2被选中,它将返回值2
需要帮忙吗???thanxx提前我想您可以使用:
if (combobox1.SelectedItem != null)
val2 = (comboBox1.SelectedItem as RequestType).Value;
或
现在,所选项目的值=
type.Value
组合框的项目集合是类型,因此当您使用
comboBox1.Items.Add(type1);
您正在将RequestType对象添加到集合中。现在,当您想要从该集合中检索单个选定项时,可以使用如下语法
RequestType type1 = new RequestType("Label 1", "Value 1");
RequestType type2 = new RequestType("Label 2", "Value 2");
comboBox1.Items.Add(type1);
comboBox1.Items.Add(type2);
comboBox1.SelectedItem = type2;
RequestType t = comboBox1.SelectedItem as RequestType;
理论上,(当您完全控制组合框项的添加时)可以避免检查使用as
关键字应用的转换是否成功,但情况并非如此,因为SelectedItem可能为null,因此使用
if(t != null)
{
Console.WriteLine(t.Value + " " + t.Text);
}
您可以将comboBox1.SelectedItem强制转换为您的类型RequestType,然后可以读取其属性。正确,但您应该检查t是否为null…:)抱歉@Marco,测试失败了coming@Marco实际上,我并没有编写完整的代码片段,只是演示了如何获取选定项的值。。。但不管怎样,这总是一件很重要的事情(检查…;)