C#基于组合框项目选择在datagridview中查看表

本文关键字:datagridview 选择 项目 于组合 组合 | 更新日期: 2023-09-27 18:23:58

我想根据所选的组合框项从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();
            }
        }
    }

任何帮助都将不胜感激,谢谢。

C#基于组合框项目选择在datagridview中查看表

您可以使用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中创建的属性名称。