.NET中使用GridView控件输入数据时出现“ Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"的问题
在.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"的问题的更多相关文章
- devexpress中gridview控件编辑时改变输入法状态
在win7环境下使用Devexpress中的SpinEdit控件,切换成中文[简/繁]输入法输入数字键时有不少输入法会重复产生数字如输入1会变成11,输入123会变成112233.使用SpinEdit ...
- asp.net中的GridView控件的部分知识点
<PagerTemplate> <br /> <asp:Label ID="lblPage" runat="server" Tex ...
- 在GridView控件内文本框实现TextChanged事件
本篇是教你实现GridView控件内的TextBox文本框实现自身的TextChanged事件.由于某些功能的需求,GridView控件内嵌TextBox,当TextBox值发生变化时,触发TextC ...
- GridView控件中加自动排列序号
GridView控件中加自动排列序号 为 Gridview 增加一个新的空白列,如下: <asp:BoundField HeaderText="序号"> < ...
- ASP.NET中GridView控件删除数据的两种方法
今天在用GridView控件时,发现了一个问题,就是使用GridView控件在删除数据时的问题.接下来我们通过模板列方式和CommandField方式删除某条数据讲解下两者之间的区别. 方式一:通 ...
- 027. asp.net中数据绑定控件之 GridView控件
GridView控件支持下面的功能: 绑定至数据源控件, 如SqlDataSource 内置排序功能 内置更新和删除功能 内置分页功能 内置行选择功能 可以编程方式访问GridView对象模型以动态设 ...
- GridView控件RowDataBound事件中获取列字段值的几种途径
前台: <asp:TemplateField HeaderText="充值总额|账号余额"> <ItemTemplate> <asp:Label ID ...
- GridView内按钮Click获取记录主键值 在GridView控件中,每行记录内会放置一个铵钮,当用
在GridView控件中,每行记录内会放置一个铵钮,当用户点击这个铵钮时,获取当笔记录的主键值.可看演示(是一个gif动画,重新播放尝试刷新网页): 实现这个功能,你需要为GridView控件设置Da ...
- Winform 中DataGridView、dev Gridview控件添加行标题
有很多种方法. 1.可以在DataGridView控件中的RowStateChanged事件改变行标题单元格的值(Row.HeaderCell.Value) /// <summary> / ...
随机推荐
- Helloworld和程序员人生
转:Helloworld和程序员人生 高中时期 10 PRINT "HELLO WORLD" 20 END 大学新生 program Hello(input, output) be ...
- 《Effective C++》 阅读小结 (笔记)
A person who is virtuous is also courteous. "有德者必知礼" 书本介绍:<Effective C++:改善程序与设计的55个具体做 ...
- SQL Server 触发器(转)
触发器是一种特殊类型的存储过程,它不同于之前的我们介绍的存储过程.触发器主要是通过事件进行触发被自动调用执行的.而存储过程可以通过存储过程的名称被调用. Ø 什么是触发器 触发器对表进行插入.更新.删 ...
- Ubuntu 12.04更换显示器后显示“显示不支援”,只能进恢复模式工作
以前用的一台14寸液晶,换成17寸后,进入系统显示器上“显示不支援” .仔细观查,电脑硬盘自检能显示后,后面都是黑屏. 解决过程. 因为grub 启动菜单不能显示.盲按方向键,发现菜单里的其它项目可 ...
- C程序设计语言练习题1-15
练习1-15 重新编写1.2节中的温度转换程序,使用函数实现温度转换计算. 代码如下: #include <stdio.h> // 包含标准库的信息. float fahrToCelsiu ...
- Speed-BI报表按钮链接设置
使用Speed-BI开发报表的时候,常常会需要增加一个链接按钮,点击按钮可跳转到其他报表或外部链接:那么我们可以通过新增‘仪表盘’--‘文本框’图表(如图1), <ignore_js_op> ...
- [SQL注入3]from_sqli_to_shell_II
[SQL注入1]这关学习盲注 ,这篇还有些东西没理透,后面搞明白了再修改. http://www.pentesterlab.com/exercises/from_sqli_to_shell_II/ 准 ...
- spark Association failed with [akka.tcp:sparkMaster@ip:7077]
今搭建spark集群, conf/spark-env.sh 配制如下 export SPARK_MASTER_IP=masterexport SPARK_MASTER_PORT=7077export ...
- quartz2.2.1-测试01
工程列表: (1)web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app versio ...
- SQL basic
Function 从例子学习 drop function dbo.getWorkingDateCount; --getWorkingDateCount = functionName CREATE FU ...