Greetings Everyone,
Can you tell me how to take a query that returns a single row of data and load that data into textbox controls.
I know about ExecuteScalar but it is only good for a single column of data from the query.
Thanks.
Truly,
Emad
Greetings Everyone,
Can you tell me how to take a query that returns a single row of data and load that data into textbox controls.
I know about ExecuteScalar but it is only good for a single column of data from the query.
Thanks.
Truly,
Emad
Short answer: was pointing in the right direction — a forward-only data reader is simple and fast for a single-row result. Add a few practical safeguards: use parameterized SQL to avoid injection, wrap connection/command/reader in Using so they are disposed, request CommandBehavior.SingleRow when appropriate, and always test for DB nulls before assigning to TextBox.Text. In Web Forms, populate controls only when the page is first loaded (check If Not IsPostBack Then ...) so you do not overwrite user edits on postback.
Example pattern (VB.NET) showing those ideas:
Using conn As New SqlConnection(connString)
Using cmd As New SqlCommand("SELECT Col1, Col2 FROM MyTable WHERE Id = @id", conn)
cmd.Parameters.AddWithValue("@id", idValue)
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow)
If rdr.Read() Then
TextBox1.Text = If(rdr.IsDBNull(0), String.Empty, rdr.GetValue(0).ToString())
TextBox2.Text = If(rdr.IsDBNull(1), String.Empty, rdr.GetValue(1).ToString())
End If
End Using
End Using
End Using Additional tips: use typed getters like GetString/GetInt32 when you know the schema for a small performance gain; consider SqlDataAdapter + DataTable (or simple data-binding) if you prefer indexable rows; and centralize null/format handling so every textbox gets consistent output. See SqlCommand.ExecuteReader and SqlDataReader.IsDBNull for API details.
Jump to Post— kvprajapati 1,826ExecuteReader() method.
... SqlDataReader dr=cmd.ExecuteReader() if dr.Read() Then TextBox1.Text= dr("col1") & " " & dr("col2") End IF
ExecuteReader() method.
...
SqlDataReader dr=cmd.ExecuteReader()
if dr.Read() Then
TextBox1.Text= dr("col1") & " " & dr("col2")
End IF Hi adatapost,
Thanks for the help. I'll look up ExecuteReader().
Truly,
Emad
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.