Solved

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

Posted on 2004-03-29
6
538 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
ScreenConnect 6.0 Free Trial

Want empowering updates? You're in the right place! Discover new features in ScreenConnect 6.0, based on partner feedback, to keep you business operating smoothly and optimally (the way it should be). Explore all of the extras and enhancements for yourself!

 

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 AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

823 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