繁体   English   中英

基于组合框项目选择的C#视图在datagridview中的表

[英]C# View tables in datagridview based upon combobox item selection

我想基于选定的组合框项从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();
            }
        }

    }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM