Home > ASP.Net > Bind DropdownList with Code

Bind DropdownList with Code


Hi

try this example:

public void Bind()
{
    Strng strConnect = default(Strng);
    strConnect = Session("ConnectionString");
   
    // Open the Connection
    SQLConnection Con = new SQLConnection(strConnect);
    Con.Open();
   
    // SQL Statement
    string strSQL = null;
    strSQL = "SELECT State_Name, State_Code FROM TableState ORDER BY State_Name";
   
    // Command, Data Reader
    SQLCommand Com = new SQLCommand(strSQL, Con);
    SQLDataReader rdr = Com.ExecuteReader();
   
    // Populate the Control
    while (rdr.Read()) {
        ListItem newListItem = new ListItem();
        newListItem.Text = rdr.GetString(0);
        newListItem.Value = rdr.GetString(1);
        DropDownList1.Items.Add(newListItem);
    }
}

//——–Another way——-

public void Get_Education_Level()
    {
        SqlDataReader ddDR = null;
        SqlConnection ddSqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Bag_ConnStr"].ConnectionString);
        SqlCommand ddSqlCommand = new SqlCommand("SELECT Id,Name FROM Education_Level ", ddSqlConnection);
        ddSqlCommand.CommandType = CommandType.Text;
        ddSqlConnection.Open();
        ddDR = ddSqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
        ddl_Education_Level.DataSource = ddDR;
        ddl_Education_Level.DataTextField = "Name";
        ddl_Education_Level.DataValueField = "Id";
        ddl_Education_Level.DataBind();

    }

Good Luck

Advertisements
Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: