在C# WinApp中,我该如何将文本和值同时添加到ComboBox的项中? 我进行了搜索,通常的答案都是使用“绑定到源代码”...但在我的情况下,我的程序中没有准备好的绑定源... 我应该如何实现这样的功能:
combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
我喜欢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;
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();
public class ComboEnumItem {
public string Text { get; set; }
public object Value { get; set; }
public ComboEnumItem(Enum originalEnum)
{
this.Value = originalEnum;
this.Text = this.ToString();
}
public string ToString()
{
FieldInfo field = Value.GetType().GetField(Value.ToString());
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? Value.ToString() : attribute.Description;
}
}
OnLoad
事件处理程序中,您需要将组合框的源设置为基于您的Enum
类型中的每个Enum
的ComboEnumItems
列表。这可以通过使用Linq来实现。然后只需设置DisplayMemberPath
即可: void OnLoad(object sender, RoutedEventArgs e)
{
comboBoxUserReadable.ItemsSource = Enum.GetValues(typeof(EMyEnum))
.Cast<EMyEnum>()
.Select(v => new ComboEnumItem(v))
.ToList();
comboBoxUserReadable.DisplayMemberPath = "Text";
comboBoxUserReadable.SelectedValuePath= "Value";
}
您可以使用通用类型:
public class ComboBoxItem<T>
{
private string Text { get; set; }
public T Value { get; set; }
public override string ToString()
{
return Text;
}
public ComboBoxItem(string text, T value)
{
Text = text;
Value = value;
}
}
使用简单的int类型的示例:
private void Fill(ComboBox comboBox)
{
comboBox.Items.Clear();
object[] list =
{
new ComboBoxItem<int>("Architekt", 1),
new ComboBoxItem<int>("Bauträger", 2),
new ComboBoxItem<int>("Fachbetrieb/Installateur", 3),
new ComboBoxItem<int>("GC-Haus", 5),
new ComboBoxItem<int>("Ingenieur-/Planungsbüro", 9),
new ComboBoxItem<int>("Wowi", 17),
new ComboBoxItem<int>("Endverbraucher", 19)
};
comboBox.Items.AddRange(list);
}
类创建:
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);
}
}
}
using (SqlConnection con = new SqlConnection(insertClass.dbPath))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(
"SELECT CategoryID, Category FROM Category WHERE Status='Active' ", con))
{
//Fill the DataTable with records from Table.
DataTable dt = new DataTable();
sda.Fill(dt);
//Insert the Default Item to DataTable.
DataRow row = dt.NewRow();
row[0] = 0;
row[1] = "(Selecione)";
dt.Rows.InsertAt(row, 0);
//Assign DataTable as DataSource.
cboProductTypeName.DataSource = dt;
cboProductTypeName.DisplayMember = "Category";
cboProductTypeName.ValueMember = "CategoryID";
}
}
con.Close();
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
,它的值与第一个相同,然后当我改变主要的组合框时,第二个组合框的索引也会同时改变,然后我取第二个组合框的值并使用它。
这是代码:
public Form1()
{
eventos = cliente.GetEventsTypes(usuario);
foreach (EventNo no in eventos)
{
cboEventos.Items.Add(no.eventno.ToString() + "--" +no.description.ToString());
cboEventos2.Items.Add(no.eventno.ToString());
}
}
private void lista_SelectedIndexChanged(object sender, EventArgs e)
{
lista2.Items.Add(lista.SelectedItem.ToString());
}
private void cboEventos_SelectedIndexChanged(object sender, EventArgs e)
{
cboEventos2.SelectedIndex = cboEventos.SelectedIndex;
}
这是 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
的调用仍然有效。
如果只需要最终值作为字符串,那么这是一个非常简单的Windows窗体解决方案。项目名称将显示在组合框中,可以轻松比较所选值。
List<string> items = new List<string>();
// populate list with test strings
for (int i = 0; i < 100; i++)
items.Add(i.ToString());
// set data source
testComboBox.DataSource = items;
并在事件处理程序中获取所选值的值(字符串)
string test = testComboBox.SelectedValue.ToString();