2013-02-07 54 views
3

設置下拉列表值我一直在使用C#如何在asp.net使用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(); 
} 

現在我需要選擇編輯頁面像這樣的默認值來填充在asp.net的下拉列表的方法。

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(); 

,但值不設置,因爲格局研究是這樣的

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

任何幫助或指導,如果我可以在下拉列表設置時,英國mystore.country值是6

回答

2

的你首先不需要通過ComboBox作爲參考。

要選擇DataBoud組合框的值,這樣做:

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 

它將預選給予的價值。

0

我認爲這個問題是在這一行:

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

在ASP.NET中,你可以通過DropDownList的(在的WinForms等)的Text property設置SelectedValue屬性。請注意差異,您可以通過文本屬性設置值。但ListItem.ToString返回的文本不是value屬性。

因此,你需要這樣的:

countary_box.Text = my_store.countary.ToString(); // if countary is the int which is used as key 

或同一使用SelectedValue直接:

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