0

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

3 Answers 3

2

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"));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.