아래 코드를 사용하여 사전 개체를 드롭 다운 목록에 바인딩하고 드롭 다운 목록에서 값을 선택하십시오.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();
}
}
Rajesh, Map은 자바로, Dictionary는 C# – Habib