How to reference a dynamically created DropDownList array outside of the method that created it.
Posted on 2004-03-29
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
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; 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);
drSelectSql = cmdSelectSql.ExecuteReader();
ddlAttributeName[cnt].DataSource = drSelectSql;
ddlAttributeName[cnt].DataTextField = "ListItem";
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.SelectedItem.Value.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.