不删除数据库,只删除GridView的某一行!
其实只要在取出来的DataTable或DataSet里面删除一行再绑定数据源就行了.
但是不要执行DataSet的acceptChanges().因为它能同步数据库和DataSet里面的数据变化。
<asp:GridView ID="view1" runat="server" OnRowCommand="gridview1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="刪除">
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" CssClass="button1" Text="刪除" CommandName="Del"
CommandArgument=' <%#Eval("ID") %>' OnClientClick="return window.confirm('您確定要刪除嗎?');" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID"));
dt.Columns.Add(new DataColumn("name"));
DataRow dr = dt.NewRow();
dr["ID"] = 1;
dr["name"] = "xx";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 2;
dr["name"] = "yy";
dt.Rows.Add(dr);
ViewState["DT"] = dt;
DataBind();
}
}
private void DataBind()
{
view1.DataSource = ViewState["DT"];
view1.DataBind();
}
protected void gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del")
{
int id = Convert.ToInt32(e.CommandArgument);
GridViewRow gvrow = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int index = gvrow.RowIndex;
DataTable dt = (DataTable)ViewState["DT"];
dt.Rows.RemoveAt(index);
DataBind();
}