为什么rowdatabound在gridview中找不到链接按钮?

时间:2017-02-28 09:31:50

标签: c# asp.net .net gridview webforms

我试图通过RowDataBound从gridview获取链接按钮,但它返回null,为什么?这个名字是对的。即使你可以在代码中看到,但它仍然无法正常工作。

GridView的:

     <asp:GridView ID="grdViewWorks" OnRowDataBound="grdViewWorks_RowDataBound" runat="server" OnRowCommand="grdViewWorks_RowCommand" AutoGenerateColumns="false" EmptyDataText="No Data Found"
CssClass="table table-responsive table-bordered table-striped">
    <Columns>
        <asp:TemplateField HeaderText="Work No">
            <ItemTemplate>
                <asp:Label ID="lblWorkNo" runat="server" Text='<%# Eval("WorkNo") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="NIT No">
            <ItemTemplate>
                <asp:Label ID="lblNITNo" runat="server" Text='<%# Eval("NIT_No") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="WorkName" HeaderText="Work Name" />
        <asp:BoundField DataField="OpeningDate" HeaderText="Opening Date" />
        <asp:BoundField DataField="OpeningTime" HeaderText="Opening Time" />
        <asp:BoundField DataField="OrganizationName" HeaderText="Organization" />
        <asp:BoundField DataField="OfficeName" HeaderText="Office" />
        <asp:TemplateField HeaderText="Show Contractors">
            <ItemTemplate>
                <asp:LinkButton ID="btnShowContractors" runat="server" Text="Show Contractors"
                    OnClick="btnShowContractors_Click"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

的.cs

protected void grdViewWorks_RowDataBound(object sender, GridViewRowEventArgs e)
{
    try
    {
        LinkButton lb = e.Row.FindControl("btnShowContractors") as LinkButton;
        ScriptManager.GetCurrent(this).RegisterPostBackControl(lb);
    }
    catch (Exception ex)
    {

        Utility.Msg_Error(this.Master, ex.Message);
    }
}

lb始终为null。为什么?

2 个答案:

答案 0 :(得分:0)

在将任何内容放入rowdatabound事件之前,您必须使用此条件

  if (e.Row.RowType == DataControlRowType.DataRow)
    {
       LinkButton lb = e.Row.FindControl("btnShowContractors") as LinkButton;
        ScriptManager.GetCurrent(this).RegisterPostBackControl(lb);
     }

答案 1 :(得分:0)

试试这种方式

if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = e.Row.FindControl("btnShowContractors") as LinkButton;
}