2011-10-05 73 views
0
protected void btnDownload_Click(object sender, EventArgs e) 
    { 

     //to request the name of the event from the listbox from Main.aspx 
     string EventName = Request.QueryString["ename"]; 

     //Select event id statement 
     //const string S = "SELECT EventName FROM Event WHERE EventID = @EventID"; 
     const string q = "SELECT EventID from Event WHERE EventName = @EventName"; 
     string eventid = ""; 
     using (SqlConnection c = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true")) 
     using (SqlCommand Command = new SqlCommand(q, c)) 
     { 
      Command.Parameters.AddWithValue("@EventName", EventName); 

      c.Open(); 
      using (SqlDataReader rdr = Command.ExecuteReader()) 
       while (rdr.Read()) 
       { 
        Command.CommandText = "Select * from Attendance where [email protected]"; 
        System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
        sb.Append(String.Format("\"{0}\",\"{1}\", \"{2}\", \"{3}\", \"{4}\", \"{5}\", \"{6}\", \"{7}\"n", 
       rdr[0], rdr[1], rdr[2], rdr[3], rdr[4], rdr[5], rdr[6], rdr[7])); 
       // I have an error here(Index out of bound) 

        // to get event id from the Event name 
        eventid = rdr.GetString(0); 
        rdr.Close(); 
        c.Close(); 

        byte[] ar = System.Text.Encoding.UTF8.GetBytes(sb.ToString()); 
        Response.ClearContent(); 
        Response.ClearHeaders(); 
        Response.AddHeader("Content.Type", "application/octet-stream"); 
        Response.AddHeader("Content-Length", ar.Length.ToString()); 
        Response.AddHeader("Content-Disposition", "attachment; filename=download.csv"); 
        Response.BinaryWrite(ar); 
        Response.Flush(); 
        Response.End(); 
       } 

     } 

錯誤是 - 「索引超出了數組的範圍。」 我正在嘗試根據事件下載文件。到目前爲止,我已經完成了大量的代碼。但我不明白錯誤的含義。請向我解釋「索引是否超出數組範圍」的錯誤,並請給我解決方案。謝謝錯誤:索引超出範圍

回答

0

如果您讀取數組並要求索引大於或等於數組長度,則可能會發生此錯誤。檢查您正在閱讀的表格是否有8個字段,或者您是否選擇了8個字段。

+0

我有10列,這意味着我必須有一個數組9我對嗎?但是在調試時不會假設任何東西,它仍然會給出錯誤消息 –

+0

@TerenceTeng。始終驗證。你沒有10列,但只有一列。當你只選擇一列時,表格有多少個並不重要。 –

0

索引越界意味着你正試圖訪問超出數組尾部的地方。

e.g:因爲沒有在位置10中array沒有項目

var array = new[] {0, 1, 2}; 
var temp = array[10]; 

將引發索引超出範圍的異常(它只有3項等位置0,1 & 2)。

這應該足以讓您嘗試解決您的問題。如果你仍然堅持讓我知道,我會看看你的代碼。

2

您嘗試訪問該行中最多7列,但只有1列(EventId)。

編輯:

而讀它你不能改變一個命令的CommandText。那麼,顯然你可以,但你不會得到預期的結果。

1

讀者包含以下語句的結果

SELECT EventID from Event WHERE EventName = @EventName 

,而不是此語句

Select * from Attendance where [email protected] 

我將取代常量串Q

const string q = @" Select * from dbo.Attendance 
        where EventID = (SELECT EventID from dbo.Event WHERE EventName = @EventName"); 

,而是*我會使用列名,原因有兩個:數據庫服務器將更喜歡它,你會確定你將有哪些列