Whenever I try to retrieve data from my database i keep getting null. The code i'm using is below:
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand("spSelectCustomer", myConnection);
cmd.CommandType = CommandType.StoredProcedure;
myConnection.Open();
SqlParameter custId = cmd.Parameters.Add("@CustomerId", SqlDbType.Int);
custId.Direction = ParameterDirection.Input;
custId.Value = 10;
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
Label1.Text = dr["FirstName"].ToString();
Label2.Text = dr["LastName"].ToString();
Label3.Text = dr[3].ToString();
Label4.Text = dr["Email"].ToString();
}
private static string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["Lab3ConnectionString"].ConnectionString;
}
In SQL, to retrieve data stored in our tables, we use the SELECT statement. The result of this statement is always in the form of a table that we can view with our database client software or use with programming languages to build dynamic web pages or desktop applications.
You can then add a new C source file and replace it with this content. Using the ODBC APIs SQLAllocHandle, SQLSetConnectAttr, and SQLDriverConnect, you should be able to initialize and establish a connection to your database.
The syntax is: SELECT column1, column2 FROM table1, table2 WHERE column2='value'; In the above SQL statement: The SELECT clause specifies one or more columns to be retrieved; to specify multiple columns, use a comma and a space between column names.
You need to call Read
before you can access data, Your code should be
While (dr.Read())
{
Label1.Text = dr["FirstName"].ToString();
Label2.Text = dr["LastName"].ToString();
Label3.Text = dr[3].ToString();
Label4.Text = dr["Email"].ToString();
}
//close DataReader
dr.Close();
Before you read column values from DataReader you must invoke Read() method from data reader.
if (dr.Read())
{
Label1.Text = dr["FirstName"].ToString();
Label2.Text = dr["LastName"].ToString();
Label3.Text = dr[3].ToString();
Label4.Text = dr["Email"].ToString();
}
You can also try:
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With