Solved

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

Posted on 2004-03-29
6
546 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
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…
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …

729 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