在.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 }

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

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

  1. devexpress中gridview控件编辑时改变输入法状态

    在win7环境下使用Devexpress中的SpinEdit控件,切换成中文[简/繁]输入法输入数字键时有不少输入法会重复产生数字如输入1会变成11,输入123会变成112233.使用SpinEdit ...

  2. asp.net中的GridView控件的部分知识点

    <PagerTemplate> <br /> <asp:Label ID="lblPage" runat="server" Tex ...

  3. 在GridView控件内文本框实现TextChanged事件

    本篇是教你实现GridView控件内的TextBox文本框实现自身的TextChanged事件.由于某些功能的需求,GridView控件内嵌TextBox,当TextBox值发生变化时,触发TextC ...

  4. GridView控件中加自动排列序号

    GridView控件中加自动排列序号 为 Gridview 增加一个新的空白列,如下: <asp:BoundField  HeaderText="序号">    < ...

  5. ASP.NET中GridView控件删除数据的两种方法

      今天在用GridView控件时,发现了一个问题,就是使用GridView控件在删除数据时的问题.接下来我们通过模板列方式和CommandField方式删除某条数据讲解下两者之间的区别. 方式一:通 ...

  6. 027. asp.net中数据绑定控件之 GridView控件

    GridView控件支持下面的功能: 绑定至数据源控件, 如SqlDataSource 内置排序功能 内置更新和删除功能 内置分页功能 内置行选择功能 可以编程方式访问GridView对象模型以动态设 ...

  7. GridView控件RowDataBound事件中获取列字段值的几种途径

    前台: <asp:TemplateField HeaderText="充值总额|账号余额"> <ItemTemplate> <asp:Label ID ...

  8. GridView内按钮Click获取记录主键值 在GridView控件中,每行记录内会放置一个铵钮,当用

    在GridView控件中,每行记录内会放置一个铵钮,当用户点击这个铵钮时,获取当笔记录的主键值.可看演示(是一个gif动画,重新播放尝试刷新网页): 实现这个功能,你需要为GridView控件设置Da ...

  9. Winform 中DataGridView、dev Gridview控件添加行标题

    有很多种方法. 1.可以在DataGridView控件中的RowStateChanged事件改变行标题单元格的值(Row.HeaderCell.Value) /// <summary> / ...

随机推荐

  1. ioctl函数,可以获取ip地址,修改ip地址,网卡地址等

    部分转自http://www.cnblogs.com/zht-blog/p/4025903.html #include <sys/types.h>#include <sys/sock ...

  2. 转:perror和strerror的区别

    概述: perror和strerror都是C语言提供的库函数,用于获取与erno相关的错误信息,区别不大,用法也简单.最大的区别在于perror向stderr输出结果,而 strerror向stdou ...

  3. SignalR Troubleshooting

    This document contains the following sections. Calling methods between the client and server silentl ...

  4. 给你讲个笑话,我是创业公司CEO

      文/办公室奇葩说(Office 78)一个在办公室较为正经的八卦号. 前几天你看见朋友圈刷屏的文章<给你讲个笑话:我是做互联网的>. 你心想,写文章的那人是傻逼吗?觉得做互联网就是个笑 ...

  5. 转: Python 运算符与用法

    +加两个对象相加 3 + 5得到8.'a' + 'b'得到'ab'. (注意:6+'a'这样是错误的,但在PHP里这样是可以运行的) -减得到负数或是一个数减去另一个数 -5.2得到一个负数.50 - ...

  6. 设计模式(十五):Iterator迭代器模式 -- 行为型模式

    1.概述 类中的面向对象编程封装应用逻辑.类,就是实例化的对象,每个单独的对象都有一个特定的身份和状态.单独的对象是一种组织代码的有用方法,但通常你会处理一组对象或者集合. 集合不一定是均一的.图形用 ...

  7. iOS 9之WatchKit for WatchOS 2

    金田(github示例源码) 自AppleWatch发行的同时就可以为AppWatch开发相应的应用程序,不过最初的版本,能开发的功能极为有限,所以也只是有少数的App厂商为Apple定制了App,所 ...

  8. 【转】ArrayList和LinkedList的几种循环遍历方式及性能对比分析

    原文网址:http://www.trinea.cn/android/arraylist-linkedlist-loop-performance/ 主要介绍ArrayList和LinkedList这两种 ...

  9. android仿京东、淘宝商品详情页上拉查看详情

    话不多说,直接上干货,基本就是一个scrollview中嵌套两个scrollview或者webview;关键点事处理好子scrollview和父scrollview的触摸.滑动事件已达到想要的效果.大 ...

  10. OpenRisc-44-or1200的pipeline整体分析

    引言 我们在前面分析了ORPSoC,or1200_top,和or1200_cpu的整体架构,在最近,我们也分析了or1200的pipeline(流水线)中的两级,EX级和IF级. 但是,我们还没有从宏 ...