通过从组合框中选择任何表来填充datagridview [英] populate datagridview by selecting any table from combo box

查看:83
本文介绍了通过从组合框中选择任何表来填充datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码在combobox中显示我的sql db表的名称...现在我想要数据当我从组合框中点击任何这些表名时...我dgv填充该表的内容

i have used the following code for displaying names of my sql db tables in combobox...now i want dat when i click on any of these table names from combo box..my dgv populates with that table''s contents

private void Form1_Load(object sender, EventArgs e)
        {
            String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";

            SqlConnection con = new SqlConnection(strConnection);
            try
            {

                con.Open();

                SqlCommand sqlCmd = new SqlCommand();

                sqlCmd.Connection = con;
                sqlCmd.CommandType = CommandType.Text;
                sqlCmd.CommandText = "Select table_name from information_schema.tables";

                SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);

                DataTable dtRecord = new DataTable();
                sqlDataAdap.Fill(dtRecord);
                comboBox1.DataSource = dtRecord;
                comboBox1.DisplayMember = "TABLE_NAME";
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

推荐答案

你好mayuri



i认为它会对你有所帮助



hello mayuri

i think it will help you

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {

      string table_name=combobox1.selecteditem.tostring(); //or can use string table_name= combox1.text      
      con.Open();
      SqlDataAdapter da = new SqlDataAdapter("select * from " + table_name + " ",con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        dgv.DataSource = ds.Tables[0];
        dgv.DataBind();
    
        con.Close();
 }



乐于帮助


happy to help


确保你的gridview属性AutoGeneratedColumns = true,因为你动态绑定记录到gridview ...

Make sure that your gridview property "AutoGeneratedColumns=true", becouse you dynamically bind records to the gridview...
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedValue != null)
            {
                PopulateGridView(comboBox1.SelectedValue.ToString());
            }
        }



并确保在上面的代码comboBox1.SelectedValue中是你的表名..


and make sure that in above code "comboBox1.SelectedValue" is your table name..


这篇关于通过从组合框中选择任何表来填充datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆