c# - binding dropdownlist to a dataset returned from a function -


i have written following method binds dropdown dataset. need call method twice in project on different pages. created class , put method in , trying access method creating object. having trouble doing so...

 public void bind()     {         dataset ds1 = new dataset();         sqlconnection con = new sqlconnection(system.configuration.configurationmanager.appsettings["connectionstring"]);         con.open();         string strquery = "select countryname + '(+' + countrycode + ')' countryname,countrycode acountry";         sqlcommand cmd = new sqlcommand(strquery, con);         using (sqldataadapter da = new sqldataadapter(cmd))         da.fill(ds1, "auser");         ddlcountrycode.datasource = ds1.tables["auser"];         ddlcountrycode.datatextfield = "countrycode";          //ddlcountrycode.selectedvalue = "india(+91)";         ddlcountrycode.databind();         ddlcountrycode.selectedindex = ddlcountrycode.items.indexof(ddlcountrycode.items.findbytext("india(+91)"));         con.close();     } 

if write complete method in new class, not recognize controls (the dropdownlist) used in & throws error. included following part in it:

  public void bindddl()     {         dataset ds1 = new dataset();         sqlconnection con = new sqlconnection(system.configuration.configurationmanager.appsettings["connectionstring"]);         con.open();         string strquery = "select countryname + '(+' + countrycode + ')' countryname,countrycode acountry";         sqlcommand cmd = new sqlcommand(strquery, con);         using (sqldataadapter da = new sqldataadapter(cmd))         da.fill(ds1, "auser");          con.close();     } 

now returns dataset need bind dropdown list on form (.aspx). how do that?

protected void page_load(object sender, eventargs e)     {         bind objbind = new bind();         ddlcountrycode.datasource = objbind.---->?????????;         ddlcountrycode.datatextfield = "countrycode";          //ddlcountrycode.selectedvalue = "india(+91)";         ddlcountrycode.databind();         ddlcountrycode.selectedindex = ddlcountrycode.items.indexof(ddlcountrycode.items.findbytext("india(+91)"));     } 

also, else can do? there better option here?

make function returns dataset assign whatever want

 public dataset bindddl()     {         dataset ds1 = new dataset();         sqlconnection con = new sqlconnection(system.configuration.configurationmanager.appsettings["connectionstring"]);         con.open();         string strquery = "select countryname + '(+' + countrycode + ')' countryname,countrycode acountry";         sqlcommand cmd = new sqlcommand(strquery, con);         using (sqldataadapter da = new sqldataadapter(cmd))         da.fill(ds1, "auser");          con.close();          return ds1;     } 

then assign them below.

bind objbind = new bind(); ddlcountrycode.datasource = objbind.bindddl().tables["auser"]; 

Comments