How to reference a dynamically created DropDownList array outside of the method that created it.

Ok, so I am creating a web form that will ask a user to enter the properties for different types of computers and hardware. Based on the different type of hardware they choose, there will be different attributes they can select. Ex - Laptop

CPU Speed
HD Size
Video Card
Owner

etc.

Since each piece of hardware is different, the attribute list must be created programmatically. So I have set it up that when the user selects a piece of hardware, my page populates a table with a label in one column, and either a drop down list or text box in the other. It loops until every attribute is show on the page.

I am encountering a problem when trying to pull the users selection from the drop down/textbox, and put it in a variable, or write it to the database. Here is a snippet of the code that adds the drop down list. I have already declared DropDownList ddlAttributeName[] = new DrowDownList[50]; as a global variable. Keep in mind, this is within a loop. the "cnt" variable keeps track of where i am in my loop.

ddlAttributeName[cnt] = new DropDownList(); //i had to instatiate it like this here, otherwise i would get build errors.
                                                      
SqlCommand cmdSelectSql = new SqlCommand(strSelectSql,sqlConnection2);
SqlDataReader drSelectSql;
drSelectSql = cmdSelectSql.ExecuteReader();
                              
ddlAttributeName[cnt].DataSource = drSelectSql;
ddlAttributeName[cnt].DataTextField = "ListItem";
ddlAttributeName[cnt].DataBind();
drSelectSql.Close();
tCell1.Controls.Add(ddlAttributeName[cnt]); \\adding the drop down list to the table


Then I have a button that will commit the record to the database. When I try to reference the drop down in the button_click code like this:

string attributeName = ddlAttributeName[0].SelectedItem.Value.Trim();
or SelectedItem.Text.Trim()

I get a runtime error when the button is clicked. The error says:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

It must be recognizing the dropdownlist as a new object. I am stumped as to how get around this.
atsciAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
eric_duncanConnect With a Mentor Commented:
It sounds to me like this might be a classic dynamic control creation problem. Make sure you are recreating all of your controls on postback - dynamic controls must be rebuilt each time the page loads, and you should probably be building your controls in the Page_Load event.

A lot of people are tempted to put control creation into a (!IsPostBack) conditional statement, but because they have to be recreated each time this won't work.

Hope this helps!

Eric
0
 
gillitCommented:
Usually that error means it cannot find the control in your page (eg <asp:DropDownList id="ddl" runat="server"/>).
0
 
codewiz51Commented:
Are you sure that you have initialized ddlAttributeName[0]?  I would check that your counter is moving from 0..49 in your code.  Possibly, your counter is stepping from 1..50?
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
atsciAuthor Commented:
Thanks for the responses so far, but I'm still not having any luck. Eric's response was good...I had to change things around and create another page so I could build all the controls in the Page_Load event, but I encounter the same error.  Here is the exact code I have:

#region Declarations

      string strAssetTypeId = "";
      string[] strAttributeName = new string[50];
      DropDownList[] ddlAttributeName = new DropDownList[50];
      protected AssetTrack.dsAssetInfo dsAssetInfo1;
      TextBox[] txtAttributeName = new TextBox[50];

#endregion

      
      private void Page_Load(object sender, System.EventArgs e)
      {
                      sqlConnection1.Open();
            sqlConnection2.Open();

            if (Request.QueryString["pcp"] != "")
            {
                  strAssetTypeId = Request.QueryString["pcp"];

                  SqlCommand cmdAssetTypeId = new SqlCommand
                        ("Select AttributeName, SelectSql From tblAssetTypeAttribute Where AssetTypeId = '" + strAssetTypeId + "'", sqlConnection1);

                  SqlDataReader drAssetTypeId;
                  drAssetTypeId = cmdAssetTypeId.ExecuteReader();

                  int cnt = 0;

                  DropDownList[] ddlAttributeName = new DropDownList[50];
                  TextBox[] txtAttributeName = new TextBox[50];

                  while(drAssetTypeId.Read())
                  {

                        strAttributeName[cnt] = drAssetTypeId["AttributeName"].ToString();
                        string strSelectSql = drAssetTypeId["SelectSql"].ToString().Trim();

                        TableRow tRow = new TableRow();
                        Table1.Rows.Add(tRow);
                        
                        TableCell tCell = new TableCell();
                        TableCell tCell1 = new TableCell();
                        tRow.Cells.Add(tCell);
                        tRow.Cells.Add(tCell1);
                        tCell.Controls.Add(new LiteralControl(strAttributeName[cnt]));

                        //if the SelectSql string isn't blank, populate the table with a list of attributes and drop down lists to fill those attributes. Use a SqlDataReader to pull info from the Lookup table and populate those values into the drop down list.
                        
                        if(strSelectSql != "")
                        {
                              //if I add the next line, the drop down lists will at least get added to the page, but I still can't reference them outside this method.
                              //ddlAttributeName[cnt] = new DropDownList();      
                              
                              SqlCommand cmdSelectSql = new SqlCommand(strSelectSql,sqlConnection2);
                              SqlDataReader drSelectSql;
                              drSelectSql = cmdSelectSql.ExecuteReader();

                              //ddlAttributeName[cnt].SelectedIndex = -1;
                              
                              ddlAttributeName[cnt].DataSource = drSelectSql;
                              ddlAttributeName[cnt].DataTextField = "ListItem";
                              ddlAttributeName[cnt].DataBind();
                              drSelectSql.Close();
                              tCell1.Controls.Add(ddlAttributeName[cnt]);
                              
                        }
                        //If the selectsql string is blank, just add a text box.
                        else
                        {
                                                                                \\same problem i am having with the drop down lists occurs with the textbox
                              \\txtAttributeName[cnt] = new TextBox();
                              tCell1.Controls.Add(txtAttributeName[cnt]);
                        }//end if-else

                        cnt++;
                  }//end while

                  drAssetTypeId.Close();
            }//end if Query string not blank
                  
            sqlConnection1.Close();
            sqlConnection2.Close();

      }//end Page Load


I know there has to be a way to do this.

Thanks in advance,
Chris
0
 
atsciAuthor Commented:
Actually, Eric's response was perfect. I just had to uncomment out the lines of code the initialize each element in the array as it goes through the loop:

ddlAttributeName[cnt] = new DropDownList();

and

txtAttributeName[cnt] = new TextBox();

It didn't work when I was creating these on the fly in an already loaded page, but when I have a new page open and have all the elements created in the Page_Load procedure, it works perfectly.

Thank you very much!
0
 
eric_duncanCommented:
Thanks for the points! Let me know if you have any more questions.

Eric
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.