如何隐藏gridview中的特定值(列)?

时间:2013-07-31 08:06:07

标签: c# asp.net gridview boundfield

在我的gridview中,我有以下内容,如我在page_load中使用gridview绑定sql所示,因为我希望它在打开页面时加载。

SqlConnection conn = new SqlConnection();
        conn.ConnectionString = "Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI";
        conn.Open();

        DataSet ds = new DataSet();

        SqlDataAdapter da = new SqlDataAdapter("SELECT memberreportid, typeofcrime, crdatetime, address, detail, incidentdate, incidenttime, property, victim, suspect from memberreport", conn);
        da.Fill(ds);

        GWCase.DataSource = ds;
        GWCase.DataBind();

        conn.Close();

但是,我试图阻止财产,受害者和可疑列出现在gridview中。我用了

Visible = false;

在我的gridview中,但它完全删除了我的gridview(当然)。

我尝试在gridview中使用boundfield,如下所示,并将可见性设置为false,以专门将列可见性设置为false

    <asp:GridView ID="GWCase" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" Width="100%" AutoGenerateSelectButton="True" OnSelectedIndexChanged="GWCase_SelectedIndexChanged">
        <FooterStyle BackColor="#CCCCCC" />
        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
        <RowStyle BackColor="White" />
        <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#F1F1F1" />
        <SortedAscendingHeaderStyle BackColor="#808080" />
        <SortedDescendingCellStyle BackColor="#CAC9C9" />
        <SortedDescendingHeaderStyle BackColor="#383838" />

     <Columns>

       <asp:BoundField DataField="property" HeaderText="property" SortExpression="property" Visible="false"/>
       <asp:BoundField DataField="victim" HeaderText="victim" SortExpression="victim" Visible="false" />
       <asp:BoundField DataField="suspect" HeaderText="suspect" SortExpression="suspect" Visible="false" />

     </Columns>
    </asp:GridView>

但是,该列仍在显示。如何从gridview中删除该3列。请不要让我从我的sql语句中删除3属性,因为我需要更多函数的数据。

我也试过这个方法,我在SO {/ 3>中找到了thread

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[7].Visible = false;
        e.Row.Cells[8].Visible = false;
        e.Row.Cells[9].Visible = false;
    }

但它也不起作用:/

问候。

2 个答案:

答案 0 :(得分:1)

您需要在行创建的事件中添加此代码。

    protected void yourGrid_RowCreated(object sender, GridViewRowEventArgs e)
    {
    e.Row.Cells[7].Visible = false;
    e.Row.Cells[8].Visible = false;
    e.Row.Cells[9].Visible = false;
    }

编辑:

另一个选项可能是在将数据源分配到网格视图后,您可以编写这些行 在你的代码中的这一行之后

   GWCase.DataSource = ds;
   GWCase.DataBind();

   GWCase.Columns[7].Visible = false;
   GWCase.Columns[8].Visible = false;
   GWCase.Columns[9].Visible = false;

答案 1 :(得分:0)

将gridview的属性AutoGenerateColumns设置为false(默认情况下为true)。然后添加要在<Columns>标记内显示的所有行,就像您对不想显示的列一样。只要您自动生成列,Columns标记就不起作用。

相关问题