Introduction
In this article, let us see how to bind a combobox with different columns from different DataTables.
For example, I have a DataTable
“Server
” with columns
Server and Database. Another DataTable
“server1
” with columns
Servername and Databasename. Now I want to display all
the values in the Server and Servername columns in a single combobox.
Using the code
- Create a new Windows application. Add a combobox control.
- I have two XML files which I am going to dump in
DataSet
s. XML file 1
="1.0"="yes"
- <NewDataSet>
- <Table1>
<Server>Server1</Server>
<Database>Database1</Database>
</Table1>
- <Table1>
<Server>Server2</Server>
<Database>Database2</Database>
</Table1>
- <Table1>
<Server>Server3</Server>
<Database>Database3</Database>
</Table1>
</NewDataSet>
XML file 2
="1.0"="yes"
- <NewDataSet>
- <table2>
<ServerName>Server4</ServerName>
<DatabaseName>Database4</DatabaseName>
</table2>
- <table2>
<ServerName>Server5</ServerName>
<DatabaseName>Database5</DatabaseName>
</table2>
- <table2>
<ServerName>Server6</ServerName>
<DatabaseName>Database6</DatabaseName>
</table2>
</NewDataSet>
- Now in
form_load
, add the below code. I am going to merge two
DataTable
s from two DataSet
s. Then I am going to create
a new column in the merged DataSet
and fill the new
column with values from both DataTable
s. See the commented lines for more explanation and better understanding.
private void Form1_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
string path = "C:\\XMLFile1.xml";
ds.ReadXml(path);
path = "C:\\XMLFile2.xml";
DataSet ds2 = new DataSet();
ds2.ReadXml(path);
ds.Tables[0].Merge(ds2.Tables[0]);
ds.Tables[0].Columns.Add("All Servers", typeof(string));
foreach (DataRow dr in ds.Tables[0].Rows)
{
dr["All Servers"] = dr["server"].ToString();
}
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["All Servers"] == "")
dr["All Servers"] = dr["servername"].ToString();
}
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "All Servers";
}
- Now run the application, check the combobox, and you will have all the servers listed inside
the combobox.
I have attached the complete source code also.
I graduated as Production Engineer and started my career as Software Developer then worked as tester for a while before moving into Windows application development using Microsoft Technologies. But for the last few years i am working on javascript, React, Node, AWS, Azure Chatbots