How to set Dropdownlist value in asp.net using c #
I have a way to populate a dropdown list in asp.net using c #
public void get_country_box_populated(ref System.Web.UI.WebControls.DropDownList dropDown, bool add_initial_text)
{
dropDown.Items.Clear();
//dropDown.Items.Add(0,"Select Any Country");
var context = new db_vmartEntities();
var query = from c in context.tbl_countary
where c.status == true
select new { c.countary_id, c.countary_name };
var dictionary = new Dictionary<int, string>();
if (add_initial_text)
{
dictionary.Add(0, "Select Any Country");
}
foreach (var item in query)
{
dictionary.Add(item.countary_id, item.countary_name);
}
dropDown.DataTextField = "Value";
dropDown.DataValueField = "Key";
dropDown.DataSource = dictionary; //Dictionary<int, string>
dropDown.DataBind();
}
now I need to select the default on the edit page something like this.
store_registration my_store = str.get_store_by_id(Session["user"].ToString(), sid);
c.get_country_box_populated(ref countary_box,false);
countary_box.Text = countary_box.Items.FindByValue(my_store.countary).ToString();
but no value set because patteren is like this
Dictionary<key,value>
Dictionary<5,Pakistan>
Dictionary<8,India>
Dictionary<9,Iran>
Dictionary<6,UK>
any help or guidance if i can set uk in dropdown when mystore.country is 6
source to share
First of all, you don't need to pass ComboBox
by link.
To select a DataBoud
ComboBox value , follow these steps:
countary_box.SelectedValue = my_store.countary_id; //im not 100% sure that this is the key, so change it to equivalent of item.countary_id
And it will preselect the value.
source to share
I guess the problem is on this line:
countary_box.Text = countary_box.Items.FindByValue(my_store.countary).ToString();
In ASP.NET, you can set a property SelectedValue
via a Text
property DropDownList
(just like in Winforms). Note the difference, you set a value on the text property. But it ListItem.ToString
returns text not to the value property.
So, you need this:
countary_box.Text = my_store.countary.ToString(); // if countary is the int which is used as key
or the same with SelectedValue
:
countary_box.SelectedValue = my_store.countary.ToString();
source to share