ASP.NET - how to bind the database data into asp.net listbox in codebehind in C#

Asked By Ramachandran on 21-Feb-13 05:07 AM
how to bind the database data into asp.net listbox in codebehind in C#
Danasegarane Arunachalam replied to Ramachandran on 21-Feb-13 05:58 AM
The below example fetches the Productname and Productid from table and fill it into the Listbox

private void bindListBox()
 
{
string connString="Fetch connection string";
string sql = "SELECT Productid,Productname FROM Employees";
        using (SqlCommand cmd = new SqlCommand(sql, new SqlConnection(connString)))
        {
          cmd.Connection.Open();
          SqlDataReader rdr = cmd.ExecuteReader();
          if (rdr.HasRows)
          {
            while (rdr.Read())
            {
              ListItem li = new ListItem(Convert.ToString(rdr["ProductName"]),
                            Convert.ToString(rdr["Productid"]));
              ListBox1.Items.Add(li);
            }
          }
        }
 
}
abdul rehman replied to Ramachandran on 21-Feb-13 06:02 AM
ListBox1.DataSource=ds or collection
ex:
sqldataadapter da=new sqldataadapter("select * from t1",con);
da.ExeRed();
da.fill(ds,"x");
ListBox1.DataSource=ds.Tables["x"];
ListBox1.DataBind();
Note:Map column name in listbox items