List and Combo are stand alone controls, which can be used independently of each other. However, you can easily integrate these controls to suit your requirements.
This topic discusses how to use the Combo control with the List control to implement the LookUp feature. The LookUp feature performs match lookup operation in a column or a row range, and returns the corresponding value from another column or row range as showcased in the following GIF.
Use the following steps to use the LookUp feature to change the value of Combo box on a button click.
C# |
Copy Code
|
---|---|
private DataTable GetDataTable(string tableName) { //Create the path of the Sample Common Database file in ComponentOne Samples folder var file = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\ComponentOne Samples\Common\C1NWind.mdb"; DataTable dt = new(tableName); //If sample Database file exists if (File.Exists(file)) { string connectionString = @"Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + file; if(tableName == "Categories") { categoriesDataAdapter = new($"Select * from [{tableName}]", connectionString); categoriesDataAdapter.Fill(dt); _ = new OdbcCommandBuilder(categoriesDataAdapter); } else { productsDataAdapter = new($"Select * from [{tableName}]", connectionString); productsDataAdapter.Fill(dt); _ = new OdbcCommandBuilder(productsDataAdapter); } } return dt; } |
C# |
Copy Code
|
---|---|
//adding DataTables into DataSet ds = new DataSet(); ds.Tables.Add(GetDataTable("Products")); ds.Tables.Add(GetDataTable("Categories")); |
C# |
Copy Code
|
---|---|
//Setting the DataSource for the List c1List1.DataSource = ds; c1List1.DataMember = "Products"; //Setting the DataSource for the C1Combo c1Combo1.DataSource = ds; c1Combo1.DataMember = "Categories"; |
C# |
Copy Code
|
---|---|
//Adding a relation between the DataTables DataColumn parentCol, childCol; parentCol = ds.Tables["Categories"].Columns["CategoryID"]; childCol = ds.Tables["Products"].Columns["CategoryID"]; DataRelation rel_ProductCategory = new("Product_Category", parentCol, childCol); ds.Relations.Add(rel_ProductCategory); |
C# |
Copy Code
|
---|---|
c1Combo1.DataBindings.Add("SelectedValue", ds, "Products.CategoryID"); |
C# |
Copy Code
|
---|---|
private void btnUpdate_Click(object sender, EventArgs e) { if (ds is not null) { try { //update the Categories Table in the Database categoriesDataAdapter.Update(ds, "Categories"); //update the Products Table in the Database productsDataAdapter.Update(ds, "Products"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } |