在c#中填充网格视图

时间:2017-06-03 06:50:44

标签: c# gridview

我是使用visual studio和ADO.NET的新手。我想在数据gridview中显示sqlserver数据库的结果。

这是我的代码,但它不会将数据填充到gridview。

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {


            SqlConnection con = new SqlConnection();
            SqlCommand Cmd = new SqlCommand("sp_Expert_person", con);
            con.Open();
            Cmd.CommandType = CommandType.StoredProcedure;
            Cmd.Parameters.Add("@takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
            SqlDataAdapter da = new SqlDataAdapter(Cmd);
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
            DataTable dt = new DataTable();       

            da.Fill(dt);
            SqlDataReader reader = Cmd.ExecuteReader();
            dt.Load(reader);
            dataGridView1.DataSource = dt;
            this.dataGridView1.Visible = true;
            dataGridView1.DataSource = dt;

        } 

1 个答案:

答案 0 :(得分:0)

为什么两次绑定到网格?

如果您的应用程序是 ASP.NET Webforms ,并且您尝试绑定GridView ID GridViewdataGridView1 “),然后使你的单一时间绑定并绑定GridView的数据,你需要在dataGridView1.DataBind();之后使用dataGridView1.DataSource = dt;

如果您的应用程序是 WindowsForms 应用程序,则修改您的代码,如下所示

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{
    dataGridView1.DataSource = null;

    string connectionString = "Define your connection string here";
    using(SqlConnection con = new SqlConnection(connectionString ))
    {
        SqlCommand cmd = new SqlCommand("sp_Expert_person", con);
        con.Open();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
        DataTable dt = new DataTable();       
        da.Fill(dt);                   
        this.dataGridView1.Visible = true;
        dataGridView1.DataSource = dt;
    }
} 
相关问题