2013-05-09 174 views
0

我使用下面的代碼將字典對象綁定到下拉列表中,並從下拉列表中選擇值。asp.net中的下拉列表項選擇

protected void Page_Load(object sender, EventArgs e) 
    { 
     Dictionary<int, string> dict = new Dictionary<int, string>(); 
     dict.Add(1, "apple"); 
     dict.Add(2, "bat"); 
     dict.Add(3, "cat"); 
     ddl.DataSource = dict; 
     ddl.DataValueField = "Key"; 
     ddl.DataTextField = "Value"; //will display in ddl 
     ddl.DataBind(); 
    } 
    protected void btn_Click(object sender, EventArgs e) 
    { 
     string key = ddl.SelectedValue; 
     string value = ddl.SelectedItem.Text; 
    } 

無論我在ddl中選擇了什麼值,它總是在鍵中獲得'1'而在值中獲得'apple'。我的代碼有什麼問題?

回答

3

那是因爲你對每個職位綁定列表回來,你應該檢查IsPostBack

protected void Page_Load(object sender, EventArgs e) 
{ 
    if(!Page.IsPostBack) // better if you refactor binding code to a method 
     { 
     Dictionary<int, string> dict = new Dictionary<int, string>(); 
     dict.Add(1, "apple"); 
     dict.Add(2, "bat"); 
     dict.Add(3, "cat"); 
     ddl.DataSource = dict; 
     ddl.DataValueField = "Key"; 
     ddl.DataTextField = "Value"; //will display in ddl 
     ddl.DataBind(); 
     } 
} 
2

dropdownlist得到復位每次頁面被加載,所以用IsPostBack這樣的更新代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if(!IsPostBack) 
    { 
    // Validate initially to force asterisks 
    // to appear before the first roundtrip. 

    Dictionary<int, string> dict = new Dictionary<int, string>(); 
    dict.Add(1, "apple"); 
    dict.Add(2, "bat"); 
    dict.Add(3, "cat"); 
    ddl.DataSource = dict; 
    ddl.DataValueField = "Key"; 
    ddl.DataTextField = "Value"; //will display in ddl 
    ddl.DataBind(); 
    } 
} 
1

Sudha,你可以使用選擇Map界面。

這將實際滿足您的要求,因爲它將數據存儲在鍵和值對的組合中。

+1

Rajesh,Map is in Java,Dictionary is equivalent in C# – Habib 2013-05-09 12:09:22