Solved

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

Posted on 2004-03-29
6
532 Views
Last Modified: 2012-08-13
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.
0
Comment
Question by:atsci
6 Comments
 
LVL 3

Expert Comment

by:gillit
ID: 10709052
Usually that error means it cannot find the control in your page (eg <asp:DropDownList id="ddl" runat="server"/>).
0
 
LVL 2

Expert Comment

by:codewiz51
ID: 10710422
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
 
LVL 2

Accepted Solution

by:
eric_duncan earned 250 total points
ID: 10710600
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:atsci
ID: 10714309
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
 

Author Comment

by:atsci
ID: 10714504
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
 
LVL 2

Expert Comment

by:eric_duncan
ID: 10722711
Thanks for the points! Let me know if you have any more questions.

Eric
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

937 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now