简体   繁体   中英

C# View tables in datagridview based upon combobox item selection

I want to load tables from database in datagridview based upon selected combobox item. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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