您的位置:首页 > 其它

.NET中使用GridView控件输入数据时出现“ Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"的问题

2014-04-17 14:13 1091 查看
在.NET中使用GridView控件的在线编辑数据时,出现了“ Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"的关于数据索引值错误的问题,在网上查了许多,感觉都没有什么文章是直接指出解决问题的方法,先就总结下吧

其实,这个问题在操作时是需要非常注意的,它并不在GridView控件的RowEditing或者RowUpdating方法中,而是需要在获取数据的类中指定GridView控件的主键,后台代码如部分如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace UI
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//判断是否第一次加载Bind()类
if (!IsPostBack)
{
Bind();
}
}

/// <summary>创建返回数据库连接的公共类
/// </summary>
/// <returns>返回连接数据库的类</returns>
public SqlConnection GetConnection()
{
string str_conn = ConfigurationManager.AppSettings["myConStr"].ToString();
SqlConnection myConn = new SqlConnection(str_conn);
return myConn;
}

/// <summary>将查询的数据绑定到GridView控件中
/// </summary>
public void Bind()
{
try
{
SqlConnection myConn = GetConnection();
myConn.Open();

string sql_Str = "select * from stuInfo order by stuAge desc";

SqlDataAdapter myda = new SqlDataAdapter(sql_Str, myConn);
DataSet myDs = new DataSet();
myda.Fill(myDs);

GridView1.DataSource = myDs;

//为GridView控件设置主键,此处必须有否则会产生如下代码中的溢出错误
/*
* Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
*/
 GridView1.DataKeyNames = new string[] { "stuNo" };//GridView控件设置主键,此处最为关键,稍不留意就忘掉了,切记呀
GridView1.DataBind();

myDs.Dispose();
myda.Dispose();
myConn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

/// <summary>创建GridView控件的RowEditing事件类
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.Bind();
}

/// <summary>创建GridView控件的RowUpdating事件类
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//获取在GridView控件里相关事件的键值
int stuNum = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string newName = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();

SqlConnection myConn = GetConnection();
myConn.Open();

/*
* string sql_str = "update stuInfo set stuName='" + newName + "' where stuNo='" + stuNum + "'";
*与上句相比,以下使用带参数的SQL语句在一定程度上可防止SQL注入攻击
*/
string sql_str = "update stuInfo set stuName=@newName where stuNo=@stuNum";
SqlCommand myCmd = new SqlCommand(sql_str, myConn);
myCmd.Parameters.Add("@newName", SqlDbType.NVarChar).Value = newName;
myCmd.Parameters.Add("@stuNum", SqlDbType.VarChar).Value = stuNum;

if (myCmd.ExecuteNonQuery() > 0)
{
Response.Write("<script type='text/javascript'>alert('更新成功');</script>");
}
else
{
Response.Write("<script type='text/javascript'>alert('更新失败');</script>");
}

//调试用
textbox1.Text = "学号:" + stuNum + " , 姓名:" + newName + ", " + sql_str + ", ExecuteNonQuery状态:" + myCmd.ExecuteNonQuery();

myCmd.Dispose();
myConn.Close();
GridView1.EditIndex = -1;
this.Bind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

/// <summary>创建GridView控件的RowCancelingEdit事件类
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowsCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
this.Bind();
}
135   }
136 }


至于前台页面,无非就是绑定相关的事件了,在这就不贴代码了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐