c# - dropdown list item selection in asp.net -


i using below code bind dictionary object dropdown list , select value dropdown list.

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

whatever value selected in ddl getting '1' in key , "apple" in value. wrong in code?

that because binding list on each post back, should check ispostback like

protected void page_load(object sender, eventargs e) {      if(!page.ispostback) // better if refactor binding code 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();        } } 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -