我用datagrid做了一个数据库的连接实例,为什么删除某一行的时候不管用呀。错误信息是:
索引超出范围。必须为非负值并小于集合大小。参数名: index
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.ArgumentOutOfRangeException: 索引超出范围。必须为非负值并小于集合大小。参数名: index
源错误:
行 46: myCommand = new System.Data.SqlClient.SqlCommand(deleteCmd, sqlConnection1);
行 47: myCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Id", SqlDbType.NVarChar,11));
行 48: myCommand.Parameters["@Id"].Value =this.DataGrid1.DataKeys[(int)e.Item.ItemIndex];
行 49: myCommand.Connection.Open();
后台代码:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace emp
{
/// <summary>
/// delete 的摘要说明。
/// </summary>
public class delete : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected System.Data.SqlClient.SqlConnection sqlConnection1;
protected System.Web.UI.WebControls.Label Message;
protected System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1;
protected System.Data.SqlClient.SqlCommand myCommand;
private void Page_Load(object sender, System.EventArgs e)
{
sqlConnection1= new System.Data.SqlClient.SqlConnection("server=QQQQ;database=firminformation;Trusted_Connection=yes");
if (!IsPostBack)
BindGrid();
}
public void BindGrid()
{
sqlDataAdapter1= new System.Data.SqlClient.SqlDataAdapter("select * from employee", sqlConnection1);
DataSet ds = new DataSet();
sqlDataAdapter1.Fill(ds,"employee");
DataGrid1.DataSource=ds.Tables["employee"].DefaultView;
DataGrid1.DataBind();
}
public void MyDataGrid_Delete(Object sender, DataGridCommandEventArgs e)
{
String deleteCmd = "DELETE from employee where e_id = @Id";
myCommand = new System.Data.SqlClient.SqlCommand(deleteCmd, sqlConnection1);
myCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Id", SqlDbType.NVarChar,11));
myCommand.Parameters["@Id"].Value =this.DataGrid1.DataKeys[(int)e.Item.ItemIndex];
myCommand.Connection.Open();
try
{
myCommand.ExecuteNonQuery();
Message.Text = "<b>已删除记录</b><br>" + deleteCmd;
}
catch (System.Data.SqlClient.SqlException)
{
Message.Text = "错误:未能删除记录";
Message.Style["颜色"] = "红色";
}
myCommand.Connection.Close();
BindGrid();
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.sqlConnection1 = new System.Data.SqlClient.SqlConnection();
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
帮帮我,好吗谢谢呀!
[此贴子已经被作者于2006-8-21 8:08:05编辑过]