Rico Brouwer Rico Brouwer - 2 months ago 7
ASP.NET (C#) Question

Bind data to gridview with existing columns but it also creates new columns

Im trying to fill my gridview with already existing columns, but instead of filling only the existing columns the code creates also new columns filled with the data

Here is my code:

protected void Button1_Click(object sender, EventArgs e)
{
connect = new SqlConnection(@"Data Source=LP12;Initial Catalog=Data;Integrated Security=True");
connect.Open();

SqlCommand cmd = new SqlCommand();
cmd.Connection = connect;
cmd.CommandText = "SELECT DrukSensor, FlowSensor
+ " FROM SysteemSensorInfo";

DataSet ds = new DataSet();
new SqlDataAdapter(cmd).Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
GridView1.AutoGenerateColumns = false;
}


I know it has something to do with the "new dataset" but i kinda blacked out at the moment and am pretty new to the programming world.

Can anyone please tell me to rewrite my code in the right way.

This is what happens now:

enter image description here

Thank you in advance!

Answer

Actually you have to set GridView1.AutoGenerateColumns = false at first:

protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.AutoGenerateColumns = false;            

        connect = new SqlConnection(@"Data Source=LP12;Initial Catalog=Data;Integrated Security=True");
        connect.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = connect;
        cmd.CommandText = "SELECT DrukSensor, FlowSensor              
                          + " FROM SysteemSensorInfo";

        DataSet ds = new DataSet();
        new SqlDataAdapter(cmd).Fill(ds);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();

    }
Comments