Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

[C#] Changing Child Controls at runtime

Status
Not open for further replies.

Mark4C

Programmer
Oct 18, 2007
1
NL
Hey all,

I'm currently developing a webpart in which SharePoint users need to fill in some form fields before the action can be performed.
I divided the form fields in several steps, each step is rendered seperately in the RenderWebPart method of the webpart. The values of a dropdownbox in step 2 depends on the selected value of a dropdownbox in step 1.

The problem: How do I fill an empty dropdownbox that is already created created in the CreateChildControls method at runtime? At the moment a dynamically filled dropdownlist displays the correct values but I get a NullReferenceException when I try to read the SelectedValue property.

Some sample code just to give an idea (haven't actually compiled it):

private DropDownList FirstBox;
private DropDownList SecondBox;

private Button FirstButton;
private Button SecondButton;

private int step = 1;

protected override void CreateChildControls()
{
step = 1;

FirstBox = new DropDownList();
FirstBox.Items.Add(new ListItem("1", "1"));
FirstBox.Items.Add(new ListItem("2", "2"));
Controls.Add(FirstBox);




SecondBox = new DropDownList();
Controls.Add(SecondBox);

FirstButton = new Button();
FirstButton.Text = "Next Step";
FirstButton.Click += new System.EventHandler(FirstAction);
Controls.Add(FirstButton);

SecondButton = new Button();
SecondButton.Text = "Next Step";
SecondButton.Click += new System.EventHandler(SecondAction);
Controls.Add(SecondButton);
}

protected override void RenderWebPart(HtmlTextWriter writer)
{
EnsureChildControls();

if(step == 1)
{


FirstBox.RenderControl(writer);

writer.Write("<br/>");


FirstButton.RenderControl(writer);

}
else if(step == 2)
{


SecondBox.RenderControl(writer);

writer.Write("<br/>");

Secondutton.RenderControl(writer);

}
}

private void FirstAction(object sender, System.EventArgs e)
{
string value = FirstBox.SelectedItem.Value.ToString();

if(value.Equals("1"))
{
SecondBox.Items.Add("3", "3");
SecondBox.Items.Add("4", "4");
}
else
{
SecondBox.Items.Add("5", "5");
SecondBox.Items.Add("6", "6");
}
step = 2;
}

private void SecondAction(object sender, System.EventArgs e)
{
string value = SecondBox.SelectedItem.Value.ToString(); // Throws an NullReferenceException
}



Any suggestions?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top