0

This is my gridview's link button onclick(ViewProfile_Click), there is a error when we click the link button and cant retrieve the cells value for selected row.

  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>
Jess Yun
  • 1
  • 1
  • It's not a good idea to name your GridView GridView. See how confusing that is? Avoid using a name that conflicts with the name of something else. It may not solve your problem here, but it will definitely help you out down the road. – mason Jan 23 '15 at 14:34

1 Answers1

0

See: What is a NullReferenceException, and how do I fix it?

This is because GridView.SelectedRow is null. You don't actually have a selected row.

A row becomes selected when a button with CommandName="Select" is clicked, or if you click the automatically generated selected button created by use of AutoGenerateSelectButton.

If you don't want or need to use a SelectedRow, you can still get the row of the button that was clicked using NamingContainer.

LinkButton ViewProfile = (LinkButton)sender;
GridViewRow row = (GridViewRow)ViewProfile.NamingContainer;
string userid = row.Cells[0].Text;
string username = row.Cells[1].Text;
Community
  • 1
  • 1
j.f.
  • 3,908
  • 2
  • 29
  • 42