문제

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();
도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top