Fill a label from a datatable


Someone can help me, what happens is that I would like to fill label with data from a query in sql, the query returns only one result but I can not show it in label this is my code in c #:

SqlCommand cmd2 = conexion.CreateCommand();
cmd2.Parameters.AddWithValue("@codigo1", txtcod.Text);
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "select PROD_NOMBRE as Producto from dbo.CAT_PRODUCTOS where PROD_COD1 = @codigo1 ";
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
label1.Text = dt2.ToString();
asked by p0ncho14 06.09.2018 в 02:30

1 answer


In your question I see a couple of problems that are easier to solve than what you are looking for.

As a first step, your command could execute a ExecuteScalar , which directly returns the value of the first row and the first column of the resulting query, with which you would already have the value you are looking for.

Making a datatable for all this, is an unnecessary waste of resources.

However, you can bring the values from the datatable, accessing the properties of it:

dt2.rows[0] would equal the first row, so if you make dt2.rows[0].columns[0] you would be bringing the first value of the first row.

Another thing that you should do, is to use a using for the connection object, since that way you release the resources when you finish. As a general rule, if an object implements dispose , use it within a using.

answered by 06.09.2018 / 03:34