每当我尝试从我的数据库中检索数据时,我总是得到 null。我使用的代码如下:
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;
}
最佳答案
你需要先调用Read
才能访问数据,你的代码应该是
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();
关于c# - 使用C#和存储过程从sql数据库中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14654064/