.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> / ...
随机推荐
- c++中 cin、cin.get()、cin.getline()、cin.getchar()的区别
①cin>>:无法接收空格.Tap键且以空格.Tap键.回车符为分隔符: ②cin.get( ):可以接收空格.Tap键且以回车符为结束符: 一:可输入单个字符 格式: char ch; ...
- 在ubuntu14.14 安装php扩展扩展出现的问题
我是在ubuntu14.14 安装的 lnmp. 部分扩展.均已安装好,但是我用apt-get 方式安装 redis和curl扩展时,我的配置都设置但是从phpinfo里面看没有响应的配置项. 于是我 ...
- SQL中对日期进行模糊查询的方法
在我们通过SQL语句对数据库中的数据进行查询时,难免会遇到针对datetime的查询,但是因为一般情况下,输入的时间条件为年月日,所以,这种情况下,我们就要进行一下模糊查询,首先,摒弃一种投机取巧的方 ...
- XAMPP安装教程
XAMPP(Apache+MySQL+PHP+PERL)是一个功能强大的建站集成软件包.这个软件包原来的名字是LAMPP,但是为了避免误解,最新的几个版本就改名为 XAMPP 了.它可以在Window ...
- 数值统计 AC 杭电
数值统计 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submi ...
- Asp.net core与golang web简单对比测试
最近因为工作需要接触了go语言,又恰好asp.net core发布RC2,就想简单做个对比测试. 下面是测试环境: CPU:E3-1230 v2 内存:16G 电脑有点不给力 操作系统:Centos7 ...
- 常见MYSQL导入导出数据命令
导出数据库: mysqldump –uuser -ppassword -hhost databasename > target_20150225.sql 打包: tar zcvf target_ ...
- Linux永久挂载远程网络目录
一般我们不永久挂载可以这样: mount -t cifs -o user=administrator,password=Fjqx2012,codepage=cp936,iocharset=cp936 ...
- 在QTreeWidget中删除QTreeWidgetItem
我就想删除topLevelItem stackoverflow上是这样说的: http://stackoverflow.com/questions/9392051/how-do-i-delete-a ...
- linux中fork()函数
man fork: FORK() Linux Programmer's Manual FORK(2) NAME fork - create a child process SYNOPSIS #incl ...