Populating ASP.net DropDownList from SQL Server using OLEDB and DataTable

Firstly we need to ensure that we have referenced System.Data.OleDb in order to connect to the Database.

Using System.Data.OleDb

Now the database connection:

string dbConnectionString = @"Provider=SQLNCLI10;Server=servername;Database=databasename;Uid=username;Pwd=password;";
OleDbConnection dbConnection = new OleDbConnection(dbConnectionString);
dbConnection.Open();

NB: for connection string help / information this is a great resource http://www.connectionstrings.com/

Now we have our open database connection we can populate our DataTable:

In the example below we are selecting USER_ID and USER_NAME from a table called USER. We use an OleDbCommand object to execute our SQL and send the results to an OleDbDataAdapter. We then use the OleDbDataAdapter to populate the DataTable. Finally we close the Database connection.

    string dbSQL = "";
    dbSQL = "SELECT USER_ID, USER_NAME FROM USER";
    OleDbCommand dbCommand = new OleDbCommand(dbSQL, dbConnection);
    dbCommand.CommandType = CommandType.Text;

    OleDbDataAdapter daList = new OleDbDataAdapter(dbCommand);
    DataTable dtList = new DataTable();
    daList.Fill(dtList);
    dbConnection.Close();

Now we have our DataTable (dtList) populated with our data we simply need to bind it to our DropDownList (in this case ddlUser), and specify the DataTextField and DataValueField:

    ddlUser.DataSource = dtList;
    ddlUser.DataTextField = "USER_NAME";
    ddlUser.DataValueField = "USER_ID";
    ddlUser.DataBind();

Now that is job done. However, I like to have the list with an empty first value and set the selected index to this:

    ddlUser.Items.Insert(0, new ListItem(string.Empty, string.Empty));
    ddlUser.SelectedIndex = 0;
Advertisements
This entry was posted in Programming and tagged , , , , , , , , . Bookmark the permalink.

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