Tutorial :Find a HTML control using FindControl in ASP.NET



Question:

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


Solution:1

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"));  


Solution:2

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>";  


Solution:3

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »