MySQL - Data Binding
<asp:DropDownList runat="server" id="ddlUsers" datavaluefield="id" datatextfield="name" />The datavaluefield property tells the control which database field should be used for the value property of each item, and the datatextfield tells the control which field to use for the actual text of the item. That's all we need in the markup department, so switch to CodeBehind. Here we will use almost the same code as in the last chapter, with a small modification:
try { using(OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString)) { connection.Open(); using(OdbcCommand command = new OdbcCommand("SELECT id, name FROM test_users", connection)) using(OdbcDataReader dr = command.ExecuteReader()) { ddlUsers.DataSource = dr; ddlUsers.DataBind(); dr.Close(); } connection.Close(); } } catch(Exception ex) { Response.Write("An error occured: " + ex.Message); }Only 2 things have changed from the last example: We've added a field to the query (the id field), and we have changed the loop to a couple of databinding lines. The first one assigns the datasource of the dropdown list to our datareader, and the second one tells the dropdown list to perform the databinding. That's all we need, which you will see if you run the website. The dropdown list will be filled with names from our test table.
This is just a basic example. Later on, when we work with repeaters, datagrids etc. you will surely realize the true potential of databinding.
Having problems with this chapter? Ask in our forums!
© net-tutorials.com 2006 - 2010