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
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"));
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>";
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
精彩评论