In this tutorial, we’ll learn How to fill ComboBox with distinct value from database using List in C#.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | private void Form1_Load(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True")) { con.Open(); SqlCommand cmd = new SqlCommand("SELECT *FROM Customers", con); SqlDataReader dr = cmd.ExecuteReader(); List<string> list = new List<string>(); while (dr.Read()) { list.Add(dr["Country"].ToString()); } dr.Close(); list=list.Distinct().ToList(); list.Sort(); comboBox1.DataSource = list; } } |
Result: