datalist的删除无法实现

来源:百度知道 编辑:UC知道 时间:2024/06/02 11:32:45
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandSource.GetType() == typeof(LinkButton))
{
if (((LinkButton)e.CommandSource).CommandName == "delete")
{
int ID = (int)this.DataList1.DataKeys[e.Item.ItemIndex];

SqlConnection conn = new SqlConnection("server=localhost;database=mydatabase;Integrated Security=True");
SqlCommand cmd = new SqlCommand("delete from shopcar where 产品ID='" + ID + "'", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
DataList1.DataBind();

}
}
}

int ID = (int)this.DataList1.DataKeys[e.Item.ItemIndex];这句话出现了索引超出范围的错误,请大家帮帮忙

你把LinkButton换成Button试试
设置DataList的DataKeyField=主键,Button的CommandName="Delete"
在DataList的ItemCommand的事件里面:
ItemCommand:
if (e.CommandName=="Delete")
{
int ID =(int)DataList.DataKeys[e.Item.Itemindex]
//int就是要删的主键,删除这条纪录就行了
}

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int id = (int)DataList1.DataKeys[e.Item.ItemIndex];
Response.Write(id);
}
}

//删除事件
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.Item.ItemIndex != -1 && e.CommandName == "RemoverZD")//判断索引和CommandName
{
int id = int.Parse(e.CommandArgument.ToString());//获取激发事件时的行的主键ID
TradeManager man = new TradeManager();