Tuesday, May 10, 2011

Fill Drop Down List Box using data table.

Using C#

string qry = "Select * from table";
con.Open();
DataTable dt = new DataTable();
dt.Columns.Add("field1");
dt.Columns.Add("field2");
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataReader dr = cmd.ExecuteReader();
if ((dr.HasRows))
{
    while (dr.Read)
    {       
        DataRow drr = null;
        drr = dt.NewRow();
        drr["field1"] = dr("field1").ToString;
        drr["field2"] = dr("field2").ToString;
        dt.Rows.Add(drr);       
    }
}
con.Close();
ddl_Temp.DataSource = dt;
ddl_Temp.DataValueField = "field1";
ddl_Temp.DataTextField = "field2";
ddl_Temp.DataBind();


Using VB. Net

Dim qry As String = "Select * from table"
con.Open()
Dim dt As New DataTable()
dt.Columns.Add("field1")
dt.Columns.Add("field2")
Dim cmd As New SqlCommand(qry, con)
Dim dr As SqlDataReader = cmd.ExecuteReader()
If (dr.HasRows) Then
 While dr.Read
  Dim drr As DataRow = Nothing
  drr = dt.NewRow()
  drr("field1") = dr("field1").ToString
  drr("field2") = dr("field2").ToString
  dt.Rows.Add(drr)
 End While
End If
con.Close()
ddl_Temp.DataSource = dt
ddl_Temp.DataValueField = "field1"
ddl_Temp.DataTextField = "field2"
ddl_Temp.DataBind()

No comments: