protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "shanchu") //如果单击的是“选修”按钮
{
int index = Convert.ToInt32(e.CommandArgument.ToString()); //取出选修课程所在的行索引
DataKey key = GridView1.DataKeys[index]; //创建DataKey集合接收该行的主键
string stuID = GridView2.DataKeys[index].Values[0].ToString().Trim(); //取出学号主键值
string courceID = GridView1.DataKeys[index].Values[0].ToString().Trim();//取出课程编号主键值
string teaID = GridView1.DataKeys[index].Values[1].ToString().Trim(); //取出教师编号主键值
string userName = Session["userName"].ToString();
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string SqlStr = "delete from Elect where stuID='" + userName + "' and courceID='" + courceID + "' and teaID='" + teaID + "'";
try
{
SqlConnection conn = new SqlConnection(connStr);//创建连接对象
if (conn.State.ToString() == "Closed") //如果连接关闭,打开连接
conn.Open();
SqlCommand comm = new SqlCommand(SqlStr, conn);
comm.ExecuteNonQuery(); //执行插入选修课程
comm.Dispose();
if (conn.State.ToString() == "Open") //如果连接打开,关闭连接
conn.Close();
}
catch (Exception ex) //异常处理
{
Response.Write("数据库错误,错误原因:" + ex.Message);
Response.End();
}
}
}
这个Gridview的功能是点击删除按钮后从数据库中删除数据,表中主键分别是stuID,courceID,teaID,属性中的DataKeyNames也已经写上这三个了。编译运行也没问题可是点击按钮触发事件的时候就提醒“ DataKey key = GridView1.DataKeys[index];”这里超出索引,本人C#小白,望各位大大出手相助啊~~~
(之前有人问过,我看了下面的方法也试了下,都不行啊,用了e.Item.ItemIndex他又出现'System.Web.UI.WebControls.GridViewCommandEventArgs' 不包含'Item',···这问题弄了很长时间,真是要疯了)