Question

Hi I have created a dataset to a gridview, when it runs it is showing all of the columns in the dataset, I would like to control which columns it displays; however, when I click on edit columns in the designer it is not showing me any columns to edit. When I use an SQLDataSource control and choose that as my data set I can see and select all columns that I want to see. How can I code this without using the SqlDataSource control?

SqlConnection PTConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Project_Tracker"].ConnectionString);
SqlCommand PTCmd = new SqlCommand("Select * from tbl_Projects", PTConn);
SqlDataAdapter PTda = new SqlDataAdapter(PTCmd);
DataSet PTds = new DataSet();
PTda.Fill(PTds);

GridView1.DataSource = PTds;
GridView1.DataBind();
Was it helpful?

Solution

You need to either handle the RowDataBound event:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[index].Visible = false;
}

or, you can set the AutoGenerateColumns property to false and create either templated custom columns or DataBound Columns:

<Columns>
    <asp:BoundField DataField="field1" HeaderText="Field1" />
    <asp:BoundField DataField="field2" HeaderText="Field2" />
    <asp:BoundField DataField="field3" HeaderText="Field3" />
    ...
</Columns>

The final option, is to modify your SQL statement to explicity SELECT the fields you need instead of selecting *:

SqlCommand PTCmd = new SqlCommand("Select field1, field2, field3 from tbl_Projects", PTConn);

However, if you need, for example, the ID, then the latter probably isn't an option. I think the first option would be the easiest and fastest to implement.

OTHER TIPS

If you want to see the individual columns, you have to explicitly select the fields you want to see rather than using SELECT *. That's what I've done before.

The designer is intended to be used with a "known" data source at design time. You cannot use the designer to edit a GridView field list when the data source is programmatically assigned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top