如何根据下拉选择将同一gridview绑定到两个不同的数据表? [英] how to bind same gridview with two different data tables based on dropdown selection?
本文介绍了如何根据下拉选择将同一gridview绑定到两个不同的数据表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题是我有一个下拉列表,其中我有两个选项gatepass现在离开gridview我已经声明了绑定字段,我从数据源填充它让数据源为dt1现在为gatepass(dt2)选项我想使用相同的gridview,但该数据源中的列不相同如何为两个数据源使用相同的结构。是否可能?
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?
推荐答案
您好,
您可以更改DataGridView的DataSource属性。有关如何有效使用DataSource的更多信息,请参阅此链接 [ ^ ]。
如果要解决问题,请参考下面的代码:
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;
}
谢谢,
Ankush Bansal
Thanks,
Ankush Bansal
这篇关于如何根据下拉选择将同一gridview绑定到两个不同的数据表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文