Asp tutorial. net dropdownlist dynamic binding methods
Dynamic binding method 1: dynamically binding fields in the database tutorial.
Sqlconnection conn = utilitysqlclass. operatedatabase. returnconn ();
String strsql = "select * from companytype ";
Sqldataadapter ada = new sqldataadapter (strsql, conn );
Dataset ds = new dataset ();
Ada. fill (ds, "companytype ");
Dropdownlist1.datasource = ds. tables ["companytype"]. defaultview;
Dropdownlist1.datavaluefield = ds. tables ["companytype"]. columns [1]. columnname;
Dropdownlist1.datatextfield = ds. tables ["companytype"]. columns [1]. columnname;
Dropdownlist1.databind ();
Ds. dispose ();
Dynamic binding method 2: Use the dropdownlist. items. add method.
Protected void page_load (object sender, eventargs e)
{
If (! Ispostback)
{
Sqlconnection conn = utilitysqlclass. operatedatabase. returnconn ();
Try
{
Conn. open ();
This. dropdownlist1.items. add ("");
String strsql = "select companytype from companytype ";
Sqlcommand com = new sqlcommand (strsql, conn );
Sqldatareader dr = com.exe cutereader ();
While (dr. read ())
{
This. dropdownlist1.items. add (dr ["companytype"]. tostring ());
}
}
Catch (exception ex)
{
Response. write ("<scirpt> alert ('" + ex. message. tostring () + "') </script> ");
}
Finally
{
Conn. close ();
}
}
}
Method 1:
String connstring = configurationsettings. apps tutorial ettings ["connectionstring"];
// Create a sqlconnection
Sqlconnection conn = new sqlconnection (connstring );
String SQL _select = "select id, itemname from ddlitem order by id desc ";
// Construct a sqldataadapter
Sqldataadapter myadapter = new sqldataadapter (SQL _select, conn );
// Start reading data
Conn. open ();
Dataset = new dataset ();
Myadapter. fill (dataset, "table1 ");
Conn. close ();
// Start binding dropdownlist
// Specify the data source used by dropdownlist
Dropdownlist1.datasource = dataset. tables ["table1"]. defaultview;
// Specify the fields in the table used by dropdownlist
Dropdownlist1.datatextfield = "itemname"; // The text field of dropdownlist
Dropdownlist1.datavaluefield = "id"; // The value Field of dropdownlist
Dropdownlist1.databind ();
Method 2:
Con. open ();
Sqlcommand cmd = new sqlcommand (strsql, con );
Sqldatareader dr = cmd.exe cutereader ();
While (dr. read ())
{
Dropdownlist1.items. add (new listitem (dr ["status"]. tostring (), dr ["status_id"]. tostring ()));
}