Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my problem is i have a dropdown list in which i have 2 options gatepass and leave now for the leave gridview i have declared bound fields and i am populating it from a datasource let that datasource be dt1 now for gatepass (dt2) option i want to use the same gridview but the columns are not same in that datasource how can i use the same structure for both datasouces. is it even possible?
Posted
Comments
Mahesh Bailwal 13-Jul-13 11:38am    
Its not possible, but why you want to do that?
a2ulthakur 13-Jul-13 11:49am    
because i have two totally unrelated datatables which i have to show conditionally in the same gridview... well and i guess its possible i just found out about dataset so i ll try and use that. if u know how to use that let me know.
Mahesh Bailwal 13-Jul-13 11:58am    
Well if you want to bind one data-source at one time then its always possible but if you want to bind same grid with more than one data-source at the same time then its not possible and your dataset approach is correct.

1 solution

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:

C#
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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900