Yongwei Xing
Yongwei Xing

Reputation: 13441

Find a HTML control using FindControl in ASP.NET

I add a select control to a ASPX page like below:

hgc = new HtmlGenericControl();
hgc.InnerHtml = @"<select runat='server' id='my_selectlist'> \
                  <option value='volvo'>Volvo</option> \
                  <option value='saab'>Saab</option> \
                  <option value='mercedes'>Mercedes</option> \
                  <option value='audi'>Audi</option> \
                </select>";

Then in a Button click event, I use the code below, try to get the value selected

HtmlSelect s = (HtmlSelect)hgc.FindControl("my_selectlist");
label.Text = s.Value;

I get a error:"Object reference not set to an instance of an object." Does anyone try it before?

Best Regards

Upvotes: 0

Views: 8328

Answers (3)

rtpHarry
rtpHarry

Reputation: 13125

This would have worked if you had put the html into the actual page and then set runat="server"

The problem with putting it inside a HtmlGenericControl.InnerHtml is that the entire thing just gets output - if you look in the view source you will see it says runat="server" is there.

Its being output after the page has been parsed and the runats have been processed

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129782

The InnerHtml value here will actually be the rendered inner HTML, so runat server will just appear as any other attribute (albeit an invalid one), and not as a clue for .NET to handle it.

Try something like this:

hgc = new HtmlGenericControl();
hgc.TagName = "select";
hgc.ID = "my_selectlist";
hgc.InnerHtml = @"<option value='volvo'>Volvo</option> \
              <option value='saab'>Saab</option> \
              <option value='mercedes'>Mercedes</option> \
              <option value='audi'>Audi</option>";

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630349

HTML != Server Control :)

You can however get the value via: Request["my_Selectlist"]; Instead of a GenericControl, if you want access to it programmatically, you need to create a HtmlSelect control instead and add items to it.

Example:

var sl = new HtmlSelect();
sl.ID = "my_selectlist";
sl.Items.Add(new ListItem("Volvo", "volvo"));
sl.Items.Add(new ListItem("Saab", "saab"));
sl.Items.Add(new ListItem("Mercedes", "mercedes"));
sl.Items.Add(new ListItem("Audi", "audi"));

Upvotes: 2

Related Questions