不包含DataBind的定义

时间:2018-07-20 16:25:51

标签: c# sql-server

using (SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-IIDC3HF\SQLEXPRESS;Initial Catalog=EmployeeNotifier;Integrated Security=True"))
{
    con.Open();

    SqlCommand cmd = new SqlCommand("Select Name,Salary FROM YOUR TABLE", con);

    SqlDataReader dr = cmd.ExecuteReader();

    dataGridView1.DataSource = dr;
    dataGridView1.DataBind();     // causing problem here

    con.Close();
}

我尝试了此代码,但是显示错误

  

不包含DataBind的定义

2 个答案:

答案 0 :(得分:0)

var select =q;
        var c = new SqlConnection(@"Your Connection String here ");  
        var dataAdapter = new SqlDataAdapter(select, c);
        var commandBuilder = new SqlCommandBuilder(dataAdapter);
        var ds = new DataSet();
        dataAdapter.Fill(ds);
        dataGridView1.ReadOnly = true;
        dataGridView1.DataSource = ds.Tables[0];

现在我尝试使用此代码,它对我来说真的很好

答案 1 :(得分:0)

问题是数据读取器必须遍历一个对象 尝试使用此方法,而不是创建一个custome类来保存您的数据。 如果那太麻烦了,请使用数据适配器并使用数据集

List<myCustomerCLass> list = new List<myCustomerCLass>();

  con.Open();

    SqlCommand cmd = new SqlCommand("Select Name,Salary FROM YOUR TABLE", con);

    SqlDataReader dr = cmd.ExecuteReader();
if (reader.HasRows)
        {
            while (reader.Read())
            {
myCustomerCLass  test = new myCustomerCLass();
                test.property1 = reader["Property1"]
test.property2 = reader["Property2"]
test.property3 = reader["Property3"]
list.add(test);
            }
        }

        reader.Close();
    dataGridView1.DataSource = list;
    dataGridView1.DataBind();     // causing problem here

    con.Close();