2010-11-27 88 views
0

我做SQL命令SqlDataReader但我有這個錯誤SQL數據讀取器類

System.IndexOutOfRangeException:用戶名

頁面加載事件:

protected void Page_Load(object sender, EventArgs e) 
{ 
    using (SqlConnection con = Connection.GetConnection()) 
    { 

     SqlCommand Com = new SqlCommand("Total", con); 
     Com.CommandType = CommandType.StoredProcedure; 
     SqlDataReader Dr = Com.ExecuteReader(); 
     if (Dr.Read()) 
     { 
      string Result= Dr["UserName"].ToString(); 
      Lbltotal.Text = Result; 
     } 
    } 
} 

存儲程序:

Alter proc Total 
as 
begin 
select Count (UserName) from Registration 
end 
+0

你的問題是什麼?你沒有顯示你的存儲過程。什麼是從它返回的結果集?其中有一個「UserName」列嗎?顯然不是例外。 – 2010-11-27 09:42:25

+0

是的,你需要在你的問題中包含存儲過程,並檢查你是否實際上有一個`UserName`列。 – gideon 2010-11-27 09:52:41

回答

0

您storder程序更改爲:

Alter proc Total 
as 
begin 
select Count (UserName) as UserName from Registration 
end 
0

您不返回任何名爲UserName的列 - 您只是返回一個沒有明確列名稱的計數。

如果你有這樣的事情 - 只是一個單一的價值 - 你也可以使用ExecuteScalar方法,它會返回一個值:

using(SqlCommand Com = new SqlCommand("Total", con)) 
{ 
    Com.CommandType = CommandType.StoredProcedure; 

    int count = (int)Com.ExecuteScalar(); 
} 

如果您堅持使用SqlDataReader,你只需要使用一個位置參數:

using(SqlCommand Com = new SqlCommand("Total", con)) 
{ 
    Com.CommandType = CommandType.StoredProcedure; 

    using(SqlDataReader Dr = Com.ExecuteReader()) 
    { 
     if (Dr.Read()) 
     { 
      string Result= Dr[0].ToString(); // take value no. 0 - the first one 
      Lbltotal.Text = Result; 
     } 
    } 
}