首页 技术 正文
技术 2022年11月21日
0 收藏 310 点赞 4,849 浏览 3153 个字

在.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[].Controls[])).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() > )
{
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 = -;
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 = -;
this.Bind();
}
135   }
136 }

至于前台页面,无非就是绑定相关的事件了,在这就不贴代码了

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,903
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,427
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,244
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,057
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,687
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,726