日期:2014-05-18  浏览次数:20441 次

gridview 添加CommandField 删除 时出错 大家帮下忙
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string stri = this.GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AviationConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("delete from routes where RID=@RID", con);
SqlParameter para = new SqlParameter("@RID", SqlDbType.Int, 4);
para.Value = stri;
cmd.Parameters.Add(para);
cmd.ExecuteNonQuery();
//this.GridDataBind();
this.DataBind();
}


  <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="RID" DataSourceID="SqlDataSource2" ForeColor="#333333"
GridLines="None" PageSize="20" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Width="1000px" OnRowDeleting="GridView1_RowDeleting">
..........
..........
<asp:CommandField ShowDeleteButton="True" >
<ItemStyle ForeColor="#804040" HorizontalAlign="Left" />
</asp:CommandField>


错误提示:除非指定了 DeleteCommand,否则数据源“SqlDataSource2”不支持删除操作。

------解决方案--------------------
解一:去掉数据源,
解二:保留数据源,并指定DeleteCommand SQL 语句

------解决方案--------------------
去掉GridView1_RowDeleting.
不知道你选择了自动生成SQL选项没有?如果选了,就不要写代码了.
在ASPX文件当中有SQL删除行的.自己找找.
------解决方案--------------------
如果读取的表包含主键,且在SqlDataSource的配置过程中指定了生成Insert,Update,Delete时,当点击GridView上的Delete按钮时,GridView会自动把GridView的DataKeys传递给SqlDataSource的DeleteParameters集合,所以你写的代码在这种情况下是多此一举。你最多在Delete CommandField的OnClientClick属性上加一句return confirm("确定要删除吗?);就可以了。


当你点击GridView上的删除按钮时, 触发GridView_RowDeleting,然后GRidView负责把DataKeyNames中指定的主键值赋值给SqlDataSource的DeleteParameters集合中对应DeleteParameter.
然后GridView自动调用SqlDataSource.Delete()方法,这时依次发生SqlDataSource.Deleting事件, 执行数据库删除操作,SqlDataSource.Deleted事件,GridView.RowDeleted事件。