注册 登录
编程论坛 ASP.NET技术论坛

GridView怎么删除行

pietro 发布于 2006-11-19 18:36, 8355 次点击
我想在GridView里删除行,代码如下:
private void GridViewToBind()
{
OleDbConnection con = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:/web/mdb/data.mdb");
con.Open();
OleDbDataAdapter odr = new OleDbDataAdapter();
odr.SelectCommand = new OleDbCommand("select * from login", con);
DataSet ds = new DataSet();
odr.Fill(ds, "emp");
this.GridView1.DataKeyNames = "userID";
this.GridView1.DataSource = ds.Tables["emp"].DefaultView;
this.GridView1.DataBind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string userID = this.GridView1.DataKeys[e.RowIndex].ToString();
OleDbConnection con = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:/web/mdb/data.mdb");
con.Open();
OleDbCommand cmd = new OleDbCommand("delete from login where userID='" + userID + "'", con);
cmd.ExecuteNonQuery();
this.GridViewToBind();
}


运行错误,提示说无法将类型“string”隐式转换为“string[]”,错误行为:
this.GridView1.DataKeyNames = "userID";


请问怎么写才对???
6 回复
#2
bygg2006-11-19 20:29
你在属性里面设置 DataKeyNames 它的值吧.因为 DataKeyNames 是个数组类型,可以同时为多个.
#3
tel19822007-05-12 13:12

怎么设置呀版主??

#4
jclman2007-05-12 14:59
如果直接在.aspx.cs文件里面编写的话,就这样写:

private void GridViewToBind()
{
OleDbConnection con = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:/web/mdb/data.mdb");
con.Open();
OleDbDataAdapter odr = new OleDbDataAdapter();
odr.SelectCommand = new OleDbCommand("select * from login", con);
DataSet ds = new DataSet();
odr.Fill(ds, "emp");

string[] user=new string[]{"userID"};
this.GridView1.DataKeyNames =user;

//当然这里是单个就直接=user,如是多个就的用数组表示

this.GridView1.DataSource = ds.Tables["emp"].DefaultView;
this.GridView1.DataBind();
}

#5
川流不息2007-05-13 21:44

this.GridView1.DataKeyNames = "userID";
this.GridView1.DataSource = ds.Tables["emp"].DefaultView;
this.GridView1.DataBind();

你把順序搞反了:


this.GridView1.DataSource = ds.Tables["emp"].DefaultView;
this.GridView1.DataKeyNames = "userID";
this.GridView1.DataBind();


#6
stonefang2007-05-27 22:48

请楼上的看看我的,我做删除也不能,不知道怎么改.
错误是:索引超出范围。必须为非负值并小于集合大小。
参数名: index
protected void Gv_userlist_RowDeleting(object sender, GridViewDeleteEventArgs e)
{//删除
string st_sqlstr = "delete from Users where User_id=@userid";
SqlCommand st_comm = new SqlCommand(st_sqlstr, conn);
st_comm.Parameters.Add(new SqlParameter("@userid", SqlDbType.VarChar, 50));
//st_comm.Parameters["@userid"].Value = st_dtg_userinformation.DataKeys[(int)e.Item.ItemIndex];
//st_comm.Parameters["@userid"].Value = Gv_userlist.DataKeys[(int)e.RowIndex].ToString();//debug
st_comm.Parameters["@userid"].Value=Gv_userlist.DataKeys[(int)e.RowIndex].Values[0].ToString();
st_comm.Connection.Open();
try
{
st_comm.ExecuteNonQuery();
Lbl_note.Text = "删除成功";

}
catch (SqlException)
{
Lbl_note.Text = "删除失败";
Lbl_note.Style["color"] = "red";
}
st_comm.Connection.Close();
St_BindGridView();
}

#7
bygg2007-05-28 09:23
上面的代码有没有什么错误信息???
1