2013-02-01 122 views
3

每當我嘗試從我的數據庫中檢索數據時,我總是收到空值。我使用的代碼如下:使用存儲過程使用C#從sql數據庫檢索數據

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; 
} 

回答

6

你需要調用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(); 
+0

非常感謝,您的解決方案工作完美! – russian

+0

@russian,如果這有助於你解決你的問題,請標記/檢查我的文章作爲答案。 –

1

在您閱讀從DataReader的列值必須調用從數據讀取器Read()方法。

if (dr.Read()) 
{ 
    Label1.Text = dr["FirstName"].ToString(); 
    Label2.Text = dr["LastName"].ToString(); 
    Label3.Text = dr[3].ToString(); 
    Label4.Text = dr["Email"].ToString(); 
} 

你還可以嘗試:

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow); 
2

你缺少你的讀者Read()通話。我還建議你將IDisposable對象包含在using聲明中,如下所示。

SqlDataReader檢索您的值時,您似乎也在使用列名稱和序數位置的奇怪組合。

protected void Button2_Click(object sender, EventArgs e) 
{ 
    using (SqlConnection myConnection = new SqlConnection(GetConnectionString())) 
    { 
     using (SqlCommand cmd = new SqlCommand("spSelectCustomer", myConnection)) 
     { 
      cmd.CommandType = CommandType.StoredProcedure; 
      myConnection.Open(); 

      SqlParameter custId = cmd.Parameters.AddWithValue("@CustomerId", 10); 

      using (SqlDataReader dr = cmd.ExecuteReader()) 
      { 
       if (dr.Read()) 
       { 
        Label1.Text = dr["FirstName"].ToString(); 
        Label2.Text = dr["LastName"].ToString(); 
        Label3.Text = dr[3].ToString(); 
        Label4.Text = dr["Email"].ToString(); 
       } 
      } 
     } 
    } 
} 
相關問題