Solved

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

Posted on 2004-03-29
6
530 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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

744 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

15 Experts available now in Live!

Get 1:1 Help Now