我想根据选定的组合框项目从datagridview中的数据库加载表格。我正在使用实体框架。我的代码如下:
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();
}
}
}
任何帮助将不胜感激,谢谢。
答案 0 :(得分:0)
您可以使用reflation动态设置表名。如下所示。
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();
TableName必须是在与数据库表对应的NameEntities中创建的属性名称。