3

i have a method to populate the dropdownlist 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 a default value on 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 value in not set because patteren is like this

Dictionary<key,value>
Dictionary<5,Pakistan>
Dictionary<8,India>
Dictionary<9,Iran>
Dictionary<6,UK>

any help or guide if i can set UK in dropdownlist when mystore.country value is 6

2 Answers 2

2

First of all you don't need to pass ComboBox by reference.

To select value of DataBoud ComboBox do this:

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 give value.

Sign up to request clarification or add additional context in comments.

Comments

0

I assume the problem is in this line:

countary_box.Text = countary_box.Items.FindByValue(my_store.countary).ToString();

In ASP.NET you can set the SelectedValue property via the Text property of a DropDownList (like in Winforms). Note the difference, you set the value by the text property. But ListItem.ToString returns the text not 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 using SelectedValue directly:

countary_box.SelectedValue = my_store.countary.ToString();  

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.