错误:索引超出限制

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 EventID=@EventID"; 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(); } } 

错误是 – “索引超出了数组的范围”。 我正在尝试根据事件下载文件。 到目前为止,我已经做了这么多的代码。 但我不明白错误的含义。 请告诉我什么错误“索引超出数组的意思”,并给我解决scheme。 谢谢

您尝试访问该行中最多7列,但只有1列(EventId)。

编辑:

读取命令时不能更改命令的命令文本。 那么,显然你可以,但你不会得到预期的结果。

读者包含以下声明的结果

 SELECT EventID from Event WHERE EventName = @EventName 

而不是为了这个声明

  Select * from Attendance where EventID=@EventID 

我会replace常量stringq

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

而不是*我会​​使用列名称,有两个原因:数据库服务器会更喜欢它,你会确定你将有哪些列

索引越界意味着,你正试图访问超过数组末尾的地方。

例如:

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

会抛出一个索引超出界限例外,因为在array没有第10位的项目(它只有3个项目,所以位置0,1和2)。

这应该足以让你尝试解决你的问题。 如果你仍然坚持让我知道,我会看看你的代码。

如果您读取一个数组并要求索引大于或等于数组的长度,则可能发生此错误。 检查您正在阅读的表格是否有8个字段,或者您是否select了8个字段。