I have a gridview that has a couple of Label server controls nested inside an ItemTemplate. I want to assign their Text value when each row is databound (I'm using Profile properties so I have to get the user and their profile to get the values).

<asp:GridView ID="grdUsers" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="UserName,UserID" DataMember="DefaultView" DataSourceID="dsUsers" EmptyDataText="There are no users">
                        <asp:HyperLinkField DataTextField="UserName" DataNavigateUrlFields="UserName" DataNavigateUrlFormatString="~/AddUser.aspx?UserName={0}"  HeaderText="Login Name" />
                                <asp:Label ID="lblLastName" runat="server"></asp:Label>
                                <asp:Label ID="lblFirstName" runat="server"></asp:Label>
                        <asp:CheckBoxField DataField="AdminRole" HeaderText="Admin" />
                        <asp:CheckBoxField DataField="AdminUsersRole" HeaderText="AdminUser" />
                        <asp:CheckBoxField DataField="ChangeProfileRole" HeaderText="Prof" />
                        <asp:CheckBoxField DataField="CreateAccountRole" HeaderText="Add" />
                        <asp:CheckBoxField DataField="DeleteAccountRole" HeaderText="Del" />
                        <asp:CheckBoxField DataField="EmulationRole" HeaderText="Emul" />
                        <asp:CheckBoxField DataField="ViewStatsRole" HeaderText="Stat" />
                        <asp:CheckBoxField DataField="VoidCheckRole" HeaderText="Void" />

I'm using the gridview's RowDataBound event to do the label.Text assignment

protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        if (e.Row.RowType == DataControlRowType.DataRow)
            memUser = Membership.GetUser(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "UserName")));
            userProfile = Profile.GetProfile(memUser.UserName);

            Label lastName = (Label)grdUsers.FindControl("lblLastName");
            Label firstName = (Label)grdUsers.FindControl("lblFirstName");
            lastName.Text = userProfile.LastName;
            firstName.Text = userProfile.FirstName;

It's failing and giving me an error message stating that lastName is null. What am I doing wrong here? Any and all assistance is much appreciated. Thanks in advance.

9 Years
Discussion Span
Last Post by postmaster

You need to bind the labels text to some field value like Text='<%#Bind(ColumnName) %>'

Since you are not binding i suppose you are getting the error for null values in


Another thought:
Do you allow NULL value in your database for LastName field?
If yes then you need to handle tat NULL in your code.


This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.