Hi,
You can change the DataSource property of a DataGridView. For more information on how to effectively use the DataSource please refer to this
link[
^].
Please refer to below code, if should solve your problem:
DataTable _dt1;
DataTable _dt2;
public Form1()
{
InitializeComponent();
_dt1 = InitDataTableOne("Table 1");
_dt2 = InitDataTableTwo("Table 2");
dataGridView1.DataSource = _dt1;
comboBox1.Items.Add(_dt1.TableName);
comboBox1.Items.Add(_dt2.TableName);
comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
}
void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource = comboBox1.SelectedIndex == 0 ? _dt1 : _dt2;
}
private DataTable InitDataTableOne(string tableName)
{
DataTable dt = new DataTable(tableName);
dt.Columns.Add("Name");
dt.Columns.Add("Age");
dt.Rows.Add("A"+tableName, "20");
dt.Rows.Add("B"+tableName, "24");
return dt;
}
private DataTable InitDataTableTwo(string tableName)
{
DataTable dt = new DataTable(tableName);
dt.Columns.Add("Id");
dt.Columns.Add("Address");
dt.Rows.Add("A" + tableName, "Street 1");
dt.Rows.Add("B" + tableName, "Street 2");
return dt;
}
Thanks,
Ankush Bansal