gridview中的HyperLink控件产生System.NullReferenceException

时间:2015-01-23 14:31:05

标签: asp.net

这是我的gridview的链接按钮onclick(ViewProfile_Click),当我们点击链接按钮并且无法检索所选行的单元格值时出错。

  protected void ViewProfile_Click(object sender, EventArgs e)
    {
       // GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;

        string userid = GridView.SelectedRow.Cells[0].Text; <my error ishere
        string username = GridView.SelectedRow.Cells[1].Text;

        Session["UserID"] = userid;
        Session["UserName"] = username;

        Label1.Text = userid;
    }




  <asp:GridView ID="GridView" runat="server" Width="580px" AutoGenerateColumns="False">
                <Columns>
                    <asp:TemplateField HeaderText="View">
                    <ItemTemplate>
                    <asp:LinkButton ID="ViewProfile" runat="server"  OnClick="ViewProfile_Click">View User Profile</asp:LinkButton>
                    </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="UserID" HeaderText="User ID" />
                    <asp:BoundField DataField="UserName" HeaderText="User Name" />
                    <asp:TemplateField HeaderText="User Profile Picture">
                        <ItemTemplate>
                        <asp:Image ID="UserImage" runat="server" Width="100px" Height="100px"
                            ImageUrl ='<%#"ImageHandler.ashx?UserID=" + Eval("UserID")%>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

1 个答案:

答案 0 :(得分:0)

请参阅:What is a NullReferenceException, and how do I fix it?

这是因为GridView.SelectedRow为空。您实际上没有选定的行。

单击带有CommandName="Select"的按钮时,或者单击使用AutoGenerateSelectButton创建的自动生成的选定按钮时,将选择一行。

如果您不想或不需要使用SelectedRow,您仍然可以获取使用NamingContainer点击的按钮行。

LinkButton ViewProfile = (LinkButton)sender;
GridViewRow row = (GridViewRow)ViewProfile.NamingContainer;
string userid = row.Cells[0].Text;
string username = row.Cells[1].Text;