Skip to content

Error when getting User info from Separate table in foreach loop #35

Description

@ranaanees

Hello,

I want to Show all Users on a Page. I am storing Profile info in a Separate table called UserProfileInfo. All is working ok. In a foreach loop when I get the FirstName or other fields stored in UserProfileInfo table it give error all the time in WebForms Application...

Here is my code

public class ApplicationUser : IdentityUser
{
public virtual UserProfileInfo UserProfileInfo { get; set; }
}
public class UserProfileInfo
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

WebForm Code Behind to Load all Users

private ApplicationDbContext context;
private UserManager manager;
public List allUser;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) 
        {
            allUser = manager.Users.ToList();
            foreach (var usr in manager.Users) {
              lblUsers.Text += usr.UserName;   // Ok  
              lblUsers.Text += usr.UserProfileInfo.FirstName;  // Error
            }
        }
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        context = new ApplicationDbContext();
        manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    }
HTML For Loop with same error
     <% if (allUser.Count() > 0 )
            { %>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>User Name</th>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody>
                <% foreach (var user in allUser)
                   { %>
                <tr>
                    <td><%: user.Id %></td>
                    <td><%: user.UserName %></td>
                    <td><%: user.UserProfileInfo.FirstName %></td>
                </tr>
                <% } %>
            </tbody>
        </table>
        <% } else { %>
        <p class="text-danger">No User Found.</p>
        <% } %>

Error
An exception of type 'System.NullReferenceException' occurred in App_Web_4cfuyuel.dll but was not handled in user code

Need help...

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions