[英]C# View tables in datagridview based upon combobox item selection
I want to load tables from database in datagridview based upon selected combobox item. 我想基于选定的组合框项从datagridview中的数据库加载表。 I'm using entity framework.
我正在使用实体框架。 My code is as follows:
我的代码如下:
private void btnCRUDLoadTable_Click(object sender, EventArgs e)
{
//prompt user when "Load Table" button is clicked without selecting any database or table or user
if (cboSelectDB.SelectedIndex <= -1 || cboSelectUser.SelectedIndex <= -1 || cboSelectTable.SelectedIndex <= -1)
{
MessageBox.Show("Please Select Database, User and Table First");
}
else
{
//load data according to combobox selection in datagridview
if (cboSelectUser.Text.ToString() == "User_name")
{
var context = new NameEntities();
BindingSource bi = new BindingSource();
//here, instead of putting tablename is there a way to put
//combox item name? I have tried combobox.Text.ToString(),
//but it doesn't work, shows error
bi.DataSource = context.TableName;
dgvLoadTable.DataSource = bi;
dgvLoadTable.Refresh();
}
}
}
Any help will be appreciated, thanks. 任何帮助将不胜感激,谢谢。
You can use reflation to set the table name dynamically. 您可以使用reflation动态设置表名。 As below.
如下。
var context = new NameEntities();
BindingSource bi = new BindingSource();
//here, instead of putting tablename is there a way to put
//combox item name? I have tried combobox.Text.ToString(),
//but it doesn't work, shows error
var TableName = combobox.Text.ToString();
bi.DataSource = context.GetType().GetProperty(TableName).GetValue(obj, null);
dgvLoadTable.DataSource = bi;
dgvLoadTable.Refresh();
The TableName must be the property name created in NameEntities corresponding to the database table. TableName必须是在与数据库表相对应的NameEntities中创建的属性名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.