This article is currently in the process of being translated into Spanish (~30% done).


MySQL - Data Binding

Nuestro primer ejemplo tuvo muy poco del estilo de ASP.NET. Con ASP.NET, el enlace de datos es muy importante, una vez que te acostumbres, entenderás por qué. El enlace de datos puede ayudarte a ahorrar algo de tiempo. Comenzaremos con un ejemplo muy básico, pero por más simple que parezca, es extremadamente útil. Popular una lista desplegable puede ser un trabajo aburrido, pero puede ser muy fácil también. Comienza por añadir una lista desplegable a la página:

<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:

    using(OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString))
        using(OdbcCommand command = new OdbcCommand("SELECT id, name FROM test_users", connection))
        using(OdbcDataReader dr = command.ExecuteReader())
            ddlUsers.DataSource = dr;
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.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!