1,GridView中如何使用CommandField刪除時,彈出確認框?
在.net2005提供的GridView中我們可以直接添加一個CommandField刪除列:<asp:CommandField ShowDeleteButton="True" />,完後在它的RowDeleting事件中完成刪除。但在多半我們在做這種刪除操作時都需要先讓操作者再確認下,完後再進行刪除,以避免誤操作引起的誤刪除。
可以通過下面方法給GridView刪除前加上個確認對話框。
首先,在GridView的屬性對框話框中點擊“Columns”進入它的“字段”設計器。接着在“字段”設計器中選擇以前已加上的那個CommandField“刪除”列,這時在它的屬性列表下會看到一個“將此它段轉換爲 TemplateFied”的項,點擊將它轉換爲TemplateFied列。
完後退出該字段設計器,切換到源碼視圖你會發現該列已由原來的:<asp:CommandField ShowDeleteButton="True" />
變爲了:
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" Text="刪除"></asp:LinkButton>
</ItemTemplate>
最後在<asp:LinkButton>中加入:OnClientClick="return confirm('確認要刪除嗎?');"
這樣點擊刪除時就會先在客戶端彈出“確認要刪除嗎?”對話框,而原來在RowDeleting事件中寫的代碼完全不用改變。
2,
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex > -1)
{
int id = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
LinkButton lbtnDelete = (LinkButton)e.Row.FindControl("lbtnDelete");
if (lbtnDelete != null)
{
lbtnDelete.CommandArgument = id.ToString();
lbtnDelete.Attributes.Add("onClick", "<script>return confirm('是否確認刪除!')</script>");
}
}
}
}
3,先引用System.windwos.Forms,然後在進行處理.
using System.Windows.Forms;
protected void gvNewList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DialogResult result = MessageBox.Show("確定要刪除本行嗎?", "信息提示!", MessageBoxButtons.YesNo, MessageBoxIcon.Question,MessageBoxDefaultButton.Button2,MessageBoxOptions.ServiceNotification);
if (result == DialogResult.Yes)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
4,添加一個刪除列
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
TableCell tc = (TableCell)e.Row.Cells[e.Row.Cells.Count - 1];
for (int i = 0; i < tc.Controls.Count; i += 2)
{
// cerco il controllo ImageButton (ho utilizzato quello)
Object o = tc.Controls[i];
if (o is ImageButton)
{
// controllo trovato!
// ora aggiungo l'evento js onClick per chiedere conferma all'utente
ImageButton lb = (ImageButton) o;
((ImageButton)lb).Attributes.Add("onclick", @"javascript:return confirm('Attenzione: sicuro di voler cancellare?');");
}
}
}
-------------------------------------------------------------
<asp:TemplateField ShowHeader="False">
<ItemStyle HorizontalAlign="Center" Width="16px" />
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CausesValidation="False" CommandName="Delete" ImageUrl="~/img/ico_elimina.gif" AlternateText="Cancella data" OnClientClick="return confirm('Sicuro di voler cancellare?');" />
</ItemTemplate>
</asp:TemplateField>
以上方法總結
---------Template way-----------------------------------------------
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
Text="刪除" OnClientClick='return confirm("Are you sure you want to delete this record?");'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
-------------RowDeleting method------------------------------------------------
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Response.Write("<script>window.confirm('確定刪除嗎?');</script>");
}
-------------RowDataBound method--------------------------------------------------------------
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((LinkButton)e.Row.Cells[4].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('確實要刪除該記錄嗎?')");
}
}
-------------------------Total three ways-------------------end-------------------------------
補充:完全代碼下使GridView中的刪除按鈕實現刪除提示的功能
首先,HTML代碼:
</asp:GridView>
第二步,初始化GridView Columns:
{
ShowGrid();
}
private void ShowGrid()
{
DataTable customerTable = new DataTable("Customers");
grdSubject.AutoGenerateColumns = false;
grdSubject.ShowHeader = false;
grdSubject.DataKeyNames = new String[] { "Id" };
DataControlFieldCollection dcfc = grdSubject.Columns;
dcfc.Clear();
BoundField bf;
bf = new BoundField();
bf.DataField = "Id";
bf.Visible = false;
dcfc.Add(bf);
bf = new BoundField();
bf.DataField = "Title";
dcfc.Add(bf);
bf = new BoundField();
bf.DataField = "BeginDate";
bf.SortExpression = "BeginDate";
bf.HtmlEncode = false;
bf.DataFormatString = "{0:yyyy-MM-dd}";
dcfc.Add(bf);
bf = new BoundField();
bf.DataField = "EndDate";
bf.HtmlEncode = false;
bf.DataFormatString = "{0:yyyy-MM-dd}";
dcfc.Add(bf);
ButtonField selectRow = new ButtonField();
selectRow.ButtonType = ButtonType.Button;
selectRow.CommandName = "Select";
selectRow.Text = "選擇";
dcfc.Add(selectRow);
ButtonField delRow = new ButtonField();
delRow.ButtonType = ButtonType.Button;
delRow.AccessibleHeaderText = "Delete";
delRow.CommandName = "Delete";
delRow.Text = "刪除";
delRow.CausesValidation = true;
dcfc.Add(delRow);
grdSubject.DataSource = dt.DefaultView;
grdSubject.DataBind();
}
第三步:RowDataBound
{
//判斷是否是DataRow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//鼠標經過Row時的效果
e.Row.Attributes.Add("onmouseover", "e=this.style.backgroundColor; this.style.backgroundColor='linen'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=e");
//當開始時間大於現在時間,顯示行爲藍色
if (DateTime.Parse(e.Row.Cells[2].Text) > DateTime.Now)
{
e.Row.BackColor = Color.LightSkyBlue;
}
//當結束時間小於現在時間,顯示行爲灰色
if (DateTime.Parse(e.Row.Cells[3].Text) < DateTime.Now)
{
e.Row.BackColor = Color.Silver;
}
//當點擊刪除按鈕時激活提示
Button btn = (Button)e.Row.Cells[5].Controls[0];
btn.Attributes.Add("onclick", "javascript:return confirm('你確認要刪除:/"" + e.Row.Cells[1].Text + "/"嗎?')");
}
}
其中的關鍵是Button btn=(Button)e.Row.Cells[5].Controls[0]; 即聲明此事件是由第6列中的第一個控件調用。
第四步:執行
{
}
void grdSubject_RowCommand(object sender, GridViewCommandEventArgs e)
{
//單擊Grid中按鈕時發生throw new Exception("The method or operation is not implemented.");
int selIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = grdSubject.Rows[selIndex];
if (e.CommandName == "Select")
{
txtSubjectTitle.Text = selectedRow.Cells[1].Text;
dateBegin.Value = selectedRow.Cells[2].Text;
dateEnd.Value = selectedRow.Cells[3].Text;
}
if (e.CommandName == "Delete")
{
Hsf.Touch.Dto.Subject item = new Hsf.Touch.Dto.Subject();
item.Id = int.Parse(grdSubject.DataKeys[selIndex].Value.ToString());
try
{
TouchFactory.CreateSubjectManage().Delete(item);
//刪除成功,清除輸入框內容
Clear();
}
catch (Exception err)
{
ShowMessageBox("刪除失敗 /n" + err.Message);
}
}
ShowGrid();
}