The second column has an index of 2, and so on. Here is an example that gets the values of different fields: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { using (SqlConnection Connect = new SqlConnection("Data Source=(local);" + "Database='Exercise';" + "Integrated Security=SSPI;")) { string strItems = "SELECT * FROM Employees WHERE EmployeeNumber = '52-260';"; SqlCommand cmdEmployees = new SqlCommand(strItems, Connect); Connect.Open(); SqlDataReader rdr = cmdEmployees.ExecuteReader(); while (rdr.Read()) { txtEmployeeNumber.Text = rdr[0].ToString(); txtEmployeeName.Text = rdr[1].ToString(); txtDateHired.Text = rdr[2].ToString(); txtHourlySalary.Text = rdr[3].ToString(); } } } } To retrieve the actual data stored in a column, you may need to know the type of information the column is holding so you can read it accurately. Depending on the data type that a column was created with, you can access it as follows:
When using one of the Get... or GetSql... methods, before sending the data, you must convert the value read to the appropriate (and probably exact) format. Here are examples: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { using (SqlConnection Connect = new SqlConnection("Data Source=(local);" + "Database='Exercise';" + "Integrated Security=SSPI;")) { string strItems = "SELECT * FROM Employees WHERE EmployeeNumber = '52-260';"; SqlCommand cmdEmployees = new SqlCommand(strItems, Connect); Connect.Open(); SqlDataReader rdr = cmdEmployees.ExecuteReader(); while (rdr.Read()) { txtEmployeeNumber.Text = rdr.GetString(0); txtEmployeeName.Text = rdr.GetString(1); txtDateHired.Text = rdr.GetDateTime(2).ToString(); txtHourlySalary.Text = rdr.GetSqlMoney(3).ToString(); } } } } |
|