You can also use the
SqlDataAdapter
class and fill a
DataTable
with the returned values.
For more information see MSDN
SqlDataAdapter Class (System.Data.SqlClient)[
^]
The code in your case would be something like this:
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from Table1", con);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd1;
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
con.Close();
if ((dataTable.Rows.Count > 0) && (dataTable.Columns.Count > 2))
{
textBox1.Text = dataTable.Rows[0][0].ToString();
textBox2.Text = dataTable.Rows[0][2].ToString();
}
if ((dataTable.Rows.Count > 2) && (dataTable.Columns.Count > 4))
{
textBox3.Text = dataTable.Rows[2][4].ToString();
}
A better way would be to used named columns in the query.
con.Open();
SqlCommand cmd1 = new SqlCommand("Select Column1, Column3, Columns5 from Table1", con);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd1;
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
con.Close();
if (dataTable.Rows.Count > 0)
{
textBox1.Text = dataTable.Rows[0]["Column1"].ToString();
textBox2.Text = dataTable.Rows[0]["Column3"].ToString();
}
if (dataTable.Rows.Count > 2)
{
textBox3.Text = dataTable.Rows[2]["Column5"].ToString();
}
The column names are of course only examples, it should be names like Id, Name, CurrentDate or similar.