2013-05-09 4 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"입니다. 내 코드에서 무엇이 잘못 되었습니까? 당신이

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

답변

3

, 귀하의 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(); 
    } 
} 
2

같은 IsPostBack을 확인해야합니다 당신은 다시 각 게시물에있는 목록을 결합하기 때문이다

1

수다, 당신은지도 인터페이스를 선택할 수 있습니다.

키와 값 쌍의 조합으로 데이터를 저장하므로 실제로 요구 사항을 충족합니다.

+1

Rajesh, Map은 자바로, Dictionary는 C# – Habib

관련 문제