如何在asp.net gridview中仅对第一行具有选择选项?

时间:2018-08-17 10:24:56

标签: c# asp.net

我正在使用asp.net gridview,其中显示带有选择选项的多个记录。 但是根据我的要求,我只希望网格上的第一行具有选择选项。

下面是我的aspx页面代码:

<asp:GridView ID="id" runat="server" AutoGenerateColumns="False" CellPadding="3"
    ShowHeaderWhenEmpty="true" AutoGenerateSelectButton="True" PageSize="5" CssClass="mGridSmall"
    GridLines="None" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
    OnPageIndexChanging="id_PageIndexChanging" OnRowDataBound="id_RowDataBound"
    OnSelectedIndexChanged="id_SelectedIndexChanged">
    <AlternatingRowStyle CssClass="alt" />
    <Columns>
        <asp:BoundField DataField="Col1" Visible="false" />
        <asp:BoundField DataField="Col2" HeaderText="Col2" SortExpression="Col2"
            Visible="true" />
        <asp:BoundField DataField="Col3" HeaderText="Col3" SortExpression="Col3"
            Visible="true" />
        <asp:BoundField DataField="Col4" HeaderText="Col4" SortExpression="Col4"></asp:BoundField>
        <asp:BoundField DataField="Col5" HeaderText="Col5" SortExpression="Col5"></asp:BoundField>
        <asp:BoundField DataField="Col6" HeaderText="Col6" SortExpression="Col6"></asp:BoundField>
        <asp:BoundField DataField="Col7" Visible="false"></asp:BoundField>
    </Columns>
    <PagerStyle CssClass="pgr" />
    <SelectedRowStyle BackColor="#fcb814" />
</asp:GridView>

这是我用于行绑定的.cs文件代码:

protected void id_RowDataBound(object sender, GridViewRowEventArgs e)
{
    try
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;

            //sorting
            e.Row.Cells[1].Text = Convert.ToString(drv.Row["Col1"]);
            e.Row.Cells[2].Text = Convert.ToString(drv.Row["Col2"]);
            //e.Row.Cells[3].Text = Convert.ToString(drv.Row["Col3"]);
            e.Row.Cells[3].Text = Convert.ToString(drv.Row["Col3"]);
            e.Row.Cells[4].Text = Convert.ToString(drv.Row["Col4"]);
            e.Row.Cells[5].Text = Convert.ToString(drv.Row["Col5"]);
            e.Row.Cells[6].Text = Convert.ToString(drv.Row["Col6"]);
            e.Row.Cells[7].Text = Convert.ToString(drv.Row["Col7"]);
        }
    }
    catch (Exception ex)
    {

        clsErrorHandler.LogError(ex);
    }
}

1 个答案:

答案 0 :(得分:1)

您可以在RowDataBound事件中执行此操作。检查行索引,然后在除第一个单元格外的所有单元格中隐藏控件。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.DataItemIndex > 0)
        {
            LinkButton lb = e.Row.Cells[0].Controls[0] as LinkButton;
            lb.Visible = false;
        }
    }
}