Reputation: 103
I am trying to bind a value from database in an already existing dropdown list. the dropdown list
<select class='form-control' id='P_Group'>
<option value='HB'>HB</option>
<option value='SPRING'>SPRING</option>
<option value='PC'>PC</option>
</select>
sending it db like this
var user = {};
user.P_GROUP = $("[id*=P_Group]").val();
Now want to bind the value which is saved in database to this another in dropdown
<select class='form-control' id='lblP_Groupn' runat="server">
<option value='HB' runat="server">HB</option>
<option value='SPRING' runat="server">SPRING</option>
<option value='PC' runat="server">PC</option>
</select>
Like this shown below after reading data
while (ReadData.Read())
{lblP_Groupn.DataValueField= ReadData["p_group"].ToString();
}
But default value which has been saved in the database is not seen while binding. it is again showing a dropdown with all the options.I want the saved option to be seen by default. and again he can select any option in it.Any idea would be appreciated.
Upvotes: 0
Views: 201
Reputation: 1391
You should use DataSource
, DataTextField
,DataValueField
and DataBind()
to fill values in HtmlSelect
.
Or use HtmlSelect.Items.Add()
to add values to existing dropdown with existing values.
After you are done adding items, use Items
again to find the value and mark selected.
Change code to
while (ReadData.Read())
{
lblP_Groupn.Items.Add(new ListItem(ReadData["p_group"].ToString(), ReadData["p_group"].ToString()));
}
Now use
var item = lblPGroupn.Items.FindByValue(SOMEVALUE);
if(item!=null)
{
item.Selected=true;
}
Upvotes: 1