Our first example was very little ASP.NET'ish. With ASP.NET, databinding is the big thing, and once you've used it for a while, you will likely understand why. Databinding can really save some time for you. We will start off with a very basic example of databinding, but even though it's simple, it's also extremely useful. Populating a dropdown list can be a boring job, but have a look how easy it can be done. Start off by adding a dropdown list to the page:
This is just a basic example. Later on, when we work with repeaters, datagrids etc. you will surely realize the true potential of databinding.
<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.