Click here to Skip to main content
15,909,437 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
DropDownList d = (DropDownList)Panel3.FindControl("Text" + i); value = d.SelectedValue.ToString();


"Object reference not set to an instance of an object." above code is written in second button.
in first buttion i created dynamically dropdownlist

C#
int a = Convert.ToInt32(TextBox1.Text);


for (int i = 0; i < a; i++)
{
d = new DropDownList();
d.ID = "Text" + i;
LiteralControl l1 = new LiteralControl("<br></br>");
SqlConnection con1 = new SqlConnection("Data Source=ABC-0D30299B90A;Initial Catalog=JAPIT;Integrated Security=True");
con1.Open();
d.Items.Add("anant");
d.Items.Add("Gautum");

//d.SelectedIndexChanged += new EventHandler(d_SelectedIndexChanged);


Panel3.Controls.Add(d);
Panel3.Controls.Add(l1);

con1.Close();
}
Posted
Updated 27-Oct-11 6:19am
v3

Could be one of 2 things:

  1. FindControl is returning null. Add a check there.
  2. SelectedValue is returning null. Add a check there as well.
 
Share this answer
 
If you try debugging and step through your code, you will get to the exact cause of the error.
Try fixing it, you will learn a lot in the process as you do this.
 
Share this answer
 
0. imho Nishant and Abhinav's answers give you exactly what you need to figure out what's going wrong.

1. you may wish to tag your question with 'ASP.NET'

2. is it absolutely clear that the second button has a valid reference to Panel3 where the DropDownLists are created in a loop at run-time ?

3. One suggestion: related to your creating DropDownLists in a loop. Why not keep a valid List of them as they are created for future reference:
C#
// keep a List of the created DropDownLists
public List<dropdownlist> ddList = new List<dropdownlist>();
//
for (int i = 0; i < a; i++)
{
d = new DropDownList();
d.ID = "Text" + i;
//
// add the new DropDownList
ddList.Add(d);
// ...</dropdownlist></dropdownlist>
Then, you can access them by index number as needed rather than using the 'indirect parsed look-up' inherent in the call to 'FindControl.

But, keep in mind that you may need to use some further technique ... other than using the modifier 'public' on the List declaration ... to expose this List of Type DropDownList to consumers if they are in a different class, container, etc.

To handle that, my choice would be to make the List private, and then expose it via a Public Property.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900