1

I am pretty new at ASP.Net and I'm trying to program a website which creates wanted amount of buttons. I have a textbox and a button, I take the number of button I want from textbox by clicking button, it's simple. And I have this code I wrote. It should have worked but I get a "System.NullReferenceException: Object reference not set to an instance of an object." error at the line where d1[k].ID exists. I searched about this error a little bit and I found out it's because d1[k].ID variable is null, but I don't know what to do. How can I solve this error?

protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        int Sayi = Convert.ToInt32(TextBox1.Text);
        Button[] d1=new Button[Sayi];
        int Sy = 20;
        for (int k = 1; k <= Sayi; k++) {
            d1[k].ID = "Btn" + k.ToString();
            d1[k].Width = 100;
            d1[k].Height = 25;
            d1[k].Text = k.ToString();
            d1[k].Attributes.Add("style", "top:"+Sy+"; left:10 ;position:absolute");
            Sy += 20;

        }
    }
  • On which line do you get the exception. There are a ton of places where that exception could occur. – Complexity Jan 05 '15 at 10:56
  • 1
    Arrays are initialise to contain the default value in each element which for reference types is null. Add `d1[k] = new Button()` to the begining of your loop. – Ben Robinson Jan 05 '15 at 11:00

2 Answers2

2

You creating instance of Button Array, not button by itself, so it should be:

int Sayi = Convert.ToInt32(TextBox1.Text);
    Button[] d1=new Button[Sayi];
    int Sy = 20;
    for (int k = 0; k < Sayi; k++) {
        var b = new Button()
        b.ID = "Btn" + k.ToString();
        b.Width = 100;
        b.Height = 25;
        b.Text = k.ToString();
        b.Attributes.Add("style", "top:"+Sy+"; left:10 ;position:absolute");
        Sy += 20;
        d1[k] = b;
    }
Uriil
  • 11,948
  • 11
  • 47
  • 68
0

d1[k] doesn't have a Button reference, you need to create one at that index before setting properties:

d1[k] = new Button();
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129