通过从组合框中选择任何表来填充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..