GridView通过代码隐藏列

我想在我的GridView中隐藏ID列,我知道代码


GridView1.Columns[0].Visible = false;

但令人惊讶的是,我的GridView列的count属性为0!虽然我可以在中看到数据GridView,所以有什么想法吗?


谢谢,


更新:


这是填充该方法的完整代码 GridView


public DataSet GetAllPatients()

{

    SqlConnection connection = new SqlConnection(this.ConnectionString);


    String sql = "SELECT [ID],[Name],[Age],[Phone],[MedicalHistory],[Medication],[Diagnoses] FROM [dbo].[AwadyClinc_PatientTbl]order by ID desc";


    SqlCommand command = new SqlCommand(sql, connection);


    SqlDataAdapter da = new SqlDataAdapter(command);


    DataSet ds = new DataSet();


    da.Fill(ds);


    return ds;


}


弑天下
浏览 558回答 3
3回答

叮当猫咪

GridView.Columns.Count当GridView的AutoGenerateColumns属性设置为时,它将始终为0 true(默认值为true)。您可以显式声明列并将AutoGenerateColumns属性设置为false,也可以在后面的代码中使用它:GridView.Rows[0].Cells.Count一旦绑定了GridView数据即可获取列数,或者这样:protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e){    e.Row.Cells[index].Visible = false;}使用GridView的RowDataBound事件将列设置为不可见。

千巷猫影

您可以通过查询datacontrolfield集合以获取所需的列标题文本并将其可见性设置为true来隐藏特定的列。((DataControlField)gridView.Columns&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Cast<DataControlField>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Where(fld => (fld.HeaderText == "Title"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.SingleOrDefault()).Visible = false;

江户川乱折腾

我看到的一些答案说明了如何使单元格的内容不可见,而不是如何隐藏整个列,这是我想要做的。如果您有AutoGenerateColumns = "false"并且实际上BoundField要用于要隐藏的列,则Bala的答案很流畅。但是,如果您使用TemplateField该列,则可以处理该DataBound事件并执行以下操作:protected void gridView_DataBound(object sender, EventArgs e){&nbsp; &nbsp; const int countriesColumnIndex = 4;&nbsp; &nbsp; if (someCondition == true)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Hide the Countries column&nbsp; &nbsp; &nbsp; &nbsp; this.gridView.Columns[countriesColumnIndex].Visible = false;&nbsp; &nbsp; }}这可能不是OP所寻找的,但这是我发现自己问同样的问题时所寻找的解决方案。
打开App,查看更多内容
随时随地看视频慕课网APP