This article describes the implementation method of comboBox control data binding in WinForm. Share it for your reference, as follows:
The following introduces three ways to bind comboBox, namely IList and Dictionary in generics, and dataset DataTable
1. IList
Now we create a List collection directly and bind
IList<string> list = new List<string>(); ("111111"); ("222222"); ("333333"); ("444444"); = list;
After execution, we will find that the binding is successful, but we know that generally there will be a value and a displayed content for the binding of the drop-down box. At this time, we can create a class, encapsulate both value and text into this class, as the type of list
public class Info { public string Id { get; set; } public string Name { get; set; } } private void bindCbox() { IList<Info> infoList = new List<Info>(); Info info1 = new Info() { Id="1",Name="Zhang San"}; Info info2 = new Info() { Id="2",Name="Li Si"}; Info info3 = new Info() { Id = "3",Name = "Wang Wu" }; (info1); (info2); (info3); = infoList; = "Id"; = "Name"; }
At this time, we can directly obtain the value and displayed content
2. Dictionary
This is a bit special and cannot be bound directly. You need to use the class BindingSource to complete the binding
Dictionary<int, string> kvDictonary = new Dictionary<int, string>(); (1, "11111"); (2, "22222"); (3, "333333"); BindingSource bs = new BindingSource(); = kvDictonary; = bs; = "Key"; = "Value";
3. Dataset
This is quite common, very simple
//Dataset bindingprivate void BindCombox() { DataTable dt = new DataTable(); DataColumn dc1 = new DataColumn("id"); DataColumn dc2 = new DataColumn("name"); (dc1); (dc2); DataRow dr1 = (); dr1["id"] = "1"; dr1["name"] = "aaaaaa"; DataRow dr2 = (); dr2["id"] = "2"; dr2["name"] = "bbbbbb"; (dr1); (dr2); = dt; = "id"; = "name"; }
Notice:
When we trigger the SelectedIndexChanged event of combox, we will execute it when loading the form. I was also fascinated at the beginning, which leads to errors. We can take some methods to avoid execution of this, such as defining a variable fig=false
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if() { string selectValue = (); = selectValue; } }
Then we must have to execute the form after loading it, so after loading the form we must set the value of fig to true
private void SetAutoMessage_Load(object sender, EventArgs e) { loadCombox(); loadMessageTemplet(); fig= true; }
For more information about C# related content, please check out the topic of this site:Summary of WinForm control usage》、《Summary of C# form operation skills》、《C# data structure and algorithm tutorial》、《Tutorial on the usage of common C# controls》、《Introduction to C# object-oriented programming tutorial"and"Summary of thread usage techniques for C# programming》
I hope this article will be helpful to everyone's C# programming.