Severiano
Severiano

Reputation: 1093

Object reference not set to an instance of an object ascx

I'd like to know whats wrong with this piece of code, it returns this error "Object reference not set to an instance of an object" and i cant understand why.

int count = com.Execute("select * from users").Rows.Count;
Label[] lbs = new Label[count];
for (int i = 0; i < count; i++)
{
    foreach (DataRow item in com.Execute("select * from users;").Rows)
    {
        lbs[i].Text = item["nickname"].ToString();
    }
    panel.Controls.Add(lbs[i]);
}

I've tried diferent ways, but allways the same error.

Upvotes: 1

Views: 967

Answers (2)

Steve
Steve

Reputation: 216263

You have created a space (array) for count labels, but you don't have created any label.
So the line lbs[i] contains a null value, hence the error.

At least add this line after the first for...

lbs[i] = new Label();

However it is still not clear what are you attempting to do in the second loop.
If I understand your code correctly, you replace the same label text (lbs[i].Text) with the nickname for each user you have in the table users, ending with the nickname of the last user. Seems really wrong.

that's could be a working solution

        DataTable dt = com.Execute("select * from users").Rows; 
        Label[] lbs = new Label[dt.Rows.Count]; 
        int i = 0;
        foreach (DataRow item in dt.Rows) 
        { 
            lbs[i] = new Label();
            lbs[i].Text = item["nickname"].ToString(); 
            panel.Controls.Add(lbs[i]);
            i++;
        } 

Upvotes: 2

Adil
Adil

Reputation: 148110

You have to create object of Label after creating array. Secondly getting data for count and the again calling for rows is not good. you can do both with single call to database. I made few adjustments in your code.

Label[] lbs = new Label[count];

foreach (DataRow item in com.Execute("select * from users;").Rows)
{
      lbs[i] = new Label();
      lbs[i].Text = item["nickname"].ToString();
      panel.Controls.Add(lbs[i]);
}

Upvotes: 1

Related Questions