1

im trying to achieve below html code from c#

<select>
  <option value="volvo">Volvo</option>
  <option value="saab" selected>Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

my main goal is to do below line from c#

<option value="saab" selected>Saab</option>

so far i have done below code

StringWriter stringwriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringwriter);
DataTable dt1 = BAL.setDropDown(tablename, id_col, value_col, hotel_id);
//let say selected_value is 1 
if (dt1.Rows.Count > 0)
{
    foreach (DataRow row in dt1.Rows)
    {
        writer.RenderBeginTag(HtmlTextWriterTag.Option);
        if( row[0].ToString() ==1 )
        {
             // i want to add selected on option tag here!!!
        } 
        writer.AddAttribute(HtmlTextWriterAttribute.Value, row[0].ToString());
        writer.Write(row[1].ToString());
        writer.RenderEndTag();
    }
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
MD TAHMID HOSSAIN
  • 1,581
  • 7
  • 29
  • 54

1 Answers1

2

You can write this:

writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected");

It will render

<option value="saab" selected="selected">Saab</option>

which is acceptable by browsers.

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116