c# - 使用C#和存储过程从sql数据库中检索数据

标签 c# asp.net sql-server stored-procedures

每当我尝试从我的数据库中检索数据时,我总是得到 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/

相关文章:

c# - 未调用 EF 4.1 OnModelCreating

c# - 如何在 ASP.net 中的 IronPython 库上导入第 3 方 Python 库

sql-server - 将 DDL 从 Oracle 迁移到 SQL Server

SQL - 查询中的用户输入

c# - .net lambda 表达式和输出参数

c# - 调用 Async WebAPI 后,控制不会返回到等待的 webClient

c# - 对 BlockingCollection 进行排序/排序

asp.net - ASP.NET 5 中的 .NET 版本

javascript - 在让客户将 javascript 添加到网页之前,我应该采取哪些预防措施?

sql - 如何使用SQL计算时间序列数据的ADI和COV?