第一種:使用DataSource數(shù)據(jù)源中自帶的編輯刪除方法,這種不常用,在這里就不加說明了。
第二種:使用GridView的三種事件:GridView1_RowEditing(編輯)、GridView1_RowUpdating(更新)、GridView1_RowCancelingEdit(取消編輯)。GridView1屬性中將DataKeyNames的值設(shè)置為主鍵名,否則找不到索引,這個很重要哦。
該方法有2種操作,一種是不對綁定列轉(zhuǎn)換為模板列,另外一種是轉(zhuǎn)換為模板列。
這里先說不轉(zhuǎn)換為模板列的情況;
首先;先對GridView進行數(shù)據(jù)綁定,不管用代碼綁定還是DataSource綁定都可以。綁定好后,對GridView添加綁定列
然后,分別激活上述提到的三種事件,然后添加代碼:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{ //執(zhí)行刪除
string str = "delete from tb_hby where id='"+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";
db.Delete(str); //db是操作類的實例,Delete是刪除數(shù)據(jù)的方法
this.GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{//執(zhí)行更新
string cell1 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim();//第一列注意這種寫法很重要
string cell2 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim();//第二列注意這種寫法很重要
string str = "update tb_hby set hby_title='" + cell1 + "',hby_Datetime='" + cell2 + "' where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
db.Update(str);//db是操作類的實例,Update是更新數(shù)據(jù)的方法
GridView1.EditIndex = -1;
GView();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{//激活編輯按鈕的事件
this.GridView1.EditIndex = e.NewEditIndex;
GView();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{//取消編輯狀態(tài)的事件
GridView1.EditIndex = -1;
GView();
}
說明:此方法中,如果要求某個綁定列不做編輯,則在它的前臺代碼中加入ReadOnly=”true”即可。
此方法有一些缺點,比如對日期列進行格式化時,顯示的時候是格式化后的日期,但是在編輯狀態(tài)下仍然顯示出日期的原貌,還有,某一列的字符太長時,不好對它進行字符截取。
在點擊刪除按鈕的時候,如果需要一個彈出刪除提示,則要將刪除列轉(zhuǎn)化為模板列,其代碼如下:
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" OnClientClick="return confirm('確定要刪除嗎?')" Text="刪除"></asp:LinkButton>
</ItemTemplate>
也可以這樣寫:
在RowDataBind事件中:
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkdelete = (LinkButton)e.Row.FindControl("lnkdelete");
lnkdelete.Attributes.Add("onclick","return confirm('您確定要刪除嗎?')");
}
如果不轉(zhuǎn)化為模板列,這這樣寫:
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
//((LinkButton)e.Row.Cells[7].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你確認要刪除:\"" + e.Row.Cells[0].Text + "\"嗎?')");
((LinkButton)e.Row.Cells[7].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你確認要刪除嗎?')");
}
}
完整代碼如下:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="hby_Title" HeaderText="hby_Title" SortExpression="hby_Title" AccessibleHeaderText="fgfg" />
<asp:BoundField DataField="hby_Datetime" DataFormatString="{0:HH:mm}" />
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" OnClientClick="return confirm('確定要刪除嗎?')"
Text="刪除"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
后臺代碼:
public partial class Default3 : System.Web.UI.Page
{
DBconn db = new DBconn();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GView();
}
}
private void GView()
{
string strbind = "select id,hby_title,hby_Datetime from tb_hby order by id desc";
this.GridView1.DataSource = db.getDataSet(strbind);
this.GridView1.DataBind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string str = "delete from tb_hby where id='"+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";
db.Delete(str);
this.GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
this.GridView1.EditIndex = e.NewEditIndex;
GView();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string cell1 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim();//第一列
string cell2 = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim();//第二列
string str = "update tb_hby set hby_title='" + cell1 + "',hby_Datetime='" + cell2 + "' where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
db.Update(str);//db是操作類的實例,Update是更新數(shù)據(jù)的方法
GridView1.EditIndex = -1;
GView();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GView();
}
}
以下是對綁定列轉(zhuǎn)換為模板列的操作(包括將編輯列和刪除列都轉(zhuǎn)化為模板列):
private void GView()
{//綁定數(shù)據(jù)源
string strbind = "select top 15 id,hby_title,hhhhh,hby_Datetime from tb_hby";
this.GridView1.DataSource = db.getDataSet(strbind);
this.GridView1.DataBind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{//執(zhí)行刪除
string str = "delete from tb_hby where id='"+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";
db.Delete(str);
//GView();
Response.Write("<script language='JavaScript'>");
Response.Write("alert('刪除成功!');location.href='default3.aspx';");
Response.Write("</script>");
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{//激活編輯
this.GridView1.EditIndex = e.NewEditIndex;
GView();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{//執(zhí)行更新
string EditTitle = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TextBox1"))).Text.ToString().Trim();
string DateTimestr = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TextBox2"))).Text;//注意:日期字段不要加ToString(),否則會報錯,而nvarchar和int的字段可以加
string hhh = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TextBox3"))).Text.ToString();
string str = "update tb_hby set hby_title='" +EditTitle + "',hby_Datetime='" + DateTimestr + "',hhhhh='"+hhh+"' where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
db.Update(str);
GridView1.EditIndex = -1;
GView();
}
這里千萬要注意:
當對綁定列轉(zhuǎn)換為模板列了之后,編輯列這樣寫:
string EditTitle = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("TextBox1"))).Text.ToString().Trim();
不轉(zhuǎn)化為模板列的時候,編輯列這樣寫:
string EditTitle = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim();
這里容易搞錯,以致經(jīng)常發(fā)生疑惑。
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{//取消編輯狀態(tài)
GridView1.EditIndex = -1;
GView();
}
以下是前臺代碼:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
SortExpression="id" />
<asp:TemplateField AccessibleHeaderText="fgfg" HeaderText="hby_Title" SortExpression="hby_Title">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("hby_Title") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("hby_Title") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("hby_Datetime", "{0:HH:mm}") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("hby_Datetime", "{0:HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="好">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("hhhhh") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("hhhhh") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LkBtnUpdate" runat="server" CausesValidation="True" CommandName="Update"
Text="更新"></asp:LinkButton>
<asp:LinkButton ID="LkBtnCtrl" runat="server" CausesValidation="False" CommandName="Cancel"
Text="取消"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<img src="img/edt.gif" /><asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Edit"
Text="編輯"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" HeaderText="刪除">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" OnClientClick="return confirm('確定要刪除嗎?')"
Text="刪除"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
以上綁定中,無論是Eval或者Bind都可以。
第三種方法:將編輯和顯示都放在模板列中,代碼如下:
前臺綁定:
<asp:TemplateField HeaderText="出團日期">
<ItemTemplate>
<asp:TextBox ID="tbx_ctrq" runat="server" Text='<%# Eval("cspd_ctrq") %>' Visible="false"></asp:TextBox>
<asp:Label ID="lbl_ctrq" runat="server" Text='<%# Eval("cspd_ctrq") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="84px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="價格">
<ItemTemplate>
<asp:TextBox ID="tbx_price" runat="server" Text='<%# Eval("cspd_price") %>' Visible="false"></asp:TextBox>
<asp:Label ID="lbl_price" runat="server" Text='<%# Eval("cspd_price") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="編輯" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LB_edit" runat="server" CausesValidation="False" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' CommandName="iEdit" Text="編輯"></asp:LinkButton>
<asp:LinkButton ID="LB_upd" runat="server" CausesValidation="True" CommandName="iUpdate"
Visible="false" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' Text="更新"></asp:LinkButton>
<asp:LinkButton ID="LB_cancel" runat="server" CausesValidation="False" CommandName="iCancel" Visible="false" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' Text="取消"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="刪除">
<ItemTemplate>
<asp:LinkButton ID="LB_Del" runat="server" OnClientClick="return confirm('確定要刪除嗎?')"
CommandName="Delete" Text="刪除"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
后臺代碼如下:
protected void GV_Main_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "iEdit")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
((LinkButton)GV_Main.Rows[rowIndex].FindControl("LB_edit")).Visible = false;
((LinkButton)GV_Main.Rows[rowIndex].FindControl("LB_upd")).Visible = true;
((LinkButton)GV_Main.Rows[rowIndex].FindControl("LB_cancel")).Visible = true;
((Label)GV_Main.Rows[rowIndex].FindControl("lbl_chanpin")).Visible = false;
((TextBox)GV_Main.Rows[rowIndex].FindControl("tbx_chanpin")).Visible = true;
((Label)GV_Main.Rows[rowIndex].FindControl("lbl_ctrq")).Visible = false;
((TextBox)GV_Main.Rows[rowIndex].FindControl("tbx_ctrq")).Visible = true;
}
if (e.CommandName == "iCancel")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
((LinkButton)GV_Main.Rows[rowIndex].FindControl("LB_edit")).Visible = true;
((LinkButton)GV_Main.Rows[rowIndex].FindControl("LB_upd")).Visible = false;
((LinkButton)GV_Main.Rows[rowIndex].FindControl("LB_cancel")).Visible = false;
((Label)GV_Main.Rows[rowIndex].FindControl("lbl_chanpin")).Visible = true;
((TextBox)GV_Main.Rows[rowIndex].FindControl("tbx_chanpin")).Visible = false;
((Label)GV_Main.Rows[rowIndex].FindControl("lbl_ctrq")).Visible = true;
((TextBox)GV_Main.Rows[rowIndex].FindControl("tbx_ctrq")).Visible = false;
}
if (e.CommandName == "iUpdate")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
if (!wpf.IsNum(((TextBox)GV_Main.Rows[rowIndex].FindControl("tbx_price")).Text.Trim()))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Startup", "<script>alert('價格必須是數(shù)字!');</script>");
}
string strupd = "UPDATE [tb_cspd] SET [cspd_chanpin] = '" + wpf.checkStr(((TextBox)GV_Main.Rows[rowIndex].FindControl("tbx_chanpin")).Text.Trim()) + "', [cspd_ctrq] = '" + wpf.checkStr(((TextBox)GV_Main.Rows[rowIndex].FindControl("tbx_ctrq")).Text.Trim()) + "', WHERE [id] = " + GV_Main.DataKeys[rowIndex][0].ToString();
//Response.Write(strupd);
wpf.SqlQuery(strupd);
GV_Main.DataBind();
}
}
}
點擊編輯按鈕后統(tǒng)一列在文本框中進行編輯:
效果:
首先還是在GridView1屬性中將DataKeyNames的值設(shè)置為主鍵名
前臺代碼:
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView3_RowCommand" DataKeyNames="News_Id">
<Columns>
<asp:BoundField DataField="News_Title" HeaderText="標題" />
<asp:BoundField DataField="News_Source" HeaderText="來源" />
<asp:BoundField DataField="News_Date" HeaderText="日期" />
<asp:TemplateField HeaderText="編輯">
<ItemTemplate>
<asp:LinkButton ID="LkBtnbianji" runat="server" CommandName="edit_ok" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>'>編輯</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
后臺代碼:
private void GView3()
{
string strbind = "select News_Id,News_Title,News_Source,News_Date from tb_News";
this.GridView3.DataSource = db.getDataSet(strbind);
this.GridView3.DataBind();
}
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "edit_ok")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
string strbind = "select News_Id,News_Title,News_Source,News_Date from tb_News where News_Id=" + GridView3.DataKeys[rowIndex][0].ToString();
DataRow dr = db.getDataSet(strbind).Tables[0].Rows[0];
this.BunAdd.CommandArgument = GridView3.DataKeys[rowIndex][0].ToString();
this.TextTitle.Text = dr["News_Title"].ToString();
this.TextType.Text=dr["News_Source"].ToString();
this.TextDatetime.Text = dr["News_Date"].ToString();
}
}
protected void BunAdd_Click(object sender, EventArgs e)
{
string up = "update tb_News set News_Title='" + this.TextTitle.Text.Trim() + "',News_Source='" + this.TextType.Text.Trim() + "',News_Date='" + this.TextDatetime.Text.Trim() + "' where News_Id="+BunAdd.CommandArgument;
db.Update(up);
GView3();
}