Tayyab zaheer
Tayyab zaheer

Reputation: 35

Does Not Contain Definition for DataBind

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();
}

I tried this code but this displays an error

Does Not Contain Definition for DataBind

Upvotes: 1

Views: 1552

Answers (2)

China Syndrome
China Syndrome

Reputation: 993

Problem is that the datareader must iterate over the an object try this instead create a custome class to hold your data.like below. If that is too much trouble use an data adaptor and use DataSets

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();

Upvotes: 0

Tayyab zaheer
Tayyab zaheer

Reputation: 35

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];

Now i try this Code and its works really fine for me

Upvotes: 1

Related Questions