public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var cbi1 = new ComboBoxItem("Item 1") { Id = 1 };
var cbi2 = new ComboBoxItem("Item 2") { Id = 2 };
var cbi3 = new ComboBoxItem("Item 3") { Id = 3 };
comboBox1.Items.Add(cbi1);
comboBox1.Items.Add(cbi2);
comboBox1.Items.Add(cbi3);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var id = ((ComboBoxItem)comboBox1.SelectedItem).Id;
MessageBox.Show(id.ToString());
}
}
public class ComboBoxItem
{
private readonly string text;
public int Id { get; set; }
public ComboBoxItem(string text)
{
this.text = text;
}
public override string ToString()
{
return text;
}
}
Is there a way to assign values to a combobox without using a datasource?
-
22-07-2023 - |
문제
I'm using Entity Framework to throw together a combobox with values from my MSSQL database using the following
using (var context = new Entity())
{
var things = (from p in context.Stuff
where ((p.SourceId == StuffId && p.Domain.Value == "Stuff")
|| (p.SourceId == OtherStuffId && p.Domain.Value == "OtherStuff"))
&& p.Done == true orderby p.StuffId
select p);
foreach(var stuff in things)
cboRejectTask.Items.Add(stuff.StuffId + ": " + stuff.StuffType.Description + " " + stuff.StuffType.DisplayName);
}
I'd like to assign values to each row so that when it comes time to grab what the user selected I don't have to do string manipulation to get what I want. I don't want to use a datasource if possible.
Solution:
Given there isn't a better way to do this than creating a custom class I went ahead and did so using the selected answer's code modified a bit for long-term use. (note: you could really use any given object as long as ToString() returned the "display text" and it had a Tag or any writeable property compatible with your needs)
public class ComboBoxItem
{
public string Display;
public object Value;
public override string ToString()
{
return Display;
}
}
Given this code I can now change my code to the following:
using (var context = new Entity())
{
var things = (from p in context.Stuff
where ((p.SourceId == StuffId && p.Domain.Value == "Stuff")
|| (p.SourceId == OtherStuffId && p.Domain.Value == "OtherStuff"))
&& p.Done == true orderby p.StuffId
select p);
foreach(var stuff in things)
cboRejectTask.Items.Add(new ComboBoxItem() { Display = stuff.StuffId + ": " + stuff.StuffType.Description + " " + stuff.StuffType.DisplayName, Value = stuff.StuffId });
}
해결책
다른 팁
I think you might find this usefull:
comboBox1.Items.Add(1);
comboBox1.Items.Add(2);
comboBox1.Items.Add(3);
private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
{
//this will set what gets displayed in the combobox, but does not change the value.
e.Value = "display value";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show((sender as ComboBox).SelectedItem.ToString());
}