45fan.com - 路饭网

搜索: 您的位置主页 > 网络频道 > 阅读资讯:怎么样给DataGrid添加确定删除的功能?

怎么样给DataGrid添加确定删除的功能?

2016-08-30 08:32:30 来源:www.45fan.com 【

怎么样给DataGrid添加确定删除的功能?

给DataGrid添加确定删除的功能

DataGrid的功能我想大家是知道的,我在实际的应用中遇到如下的问题,客户要求在删除之前做一次提示。类

似于windows。首先我们都知道DataGrid支持删除的功能,我们可以向DataGrid里面添加删除列就可以实现,

下面我想用模板列来实现带提示的删除按钮。我们用northwind的示例数据库作为例子数据库操纵Categories表。

DataGrid的Html页的内容如下:

<asp:DataGrid id="grdTest" style="Z-INDEX: 101; LEFT: 205px; POSITION: absolute; TOP: 134px"

runat="server">

<Columns>

<asp:TemplateColumn>

<ItemTemplate>

<asp:Button id="btnDelete"

runat="server" Text="Button" CommandName="Delete"></asp:Button>

</ItemTemplate>

</asp:TemplateColumn>

</Columns>

</asp:DataGrid>

我们只添加了一个模板列,其他的列都是在运行的时候自动生成的。

可以看出这个模板列很像删除列但是又不是删除列,我们给一个普通的Button添加了一个CommandName

="Delete"的属性。这是用来响应DataGrid的ItemCommand事件的!在删除列里面就是这样的!

接下来就是后台代码了,代码如下所示:

private DataSet ds = new DataSet();

private void Page_Load(object sender, System.EventArgs e)

{

// 在此处放置用户代码以初始化页面

if(!this.IsPostBack){

string strConnection = ConfigurationSettings.AppSettings

["sa"].ToString();

SqlConnection myConnection = new SqlConnection(strConnection);

SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT

CategoryID,CategoryName, DescriptionFROM Categories",myConnection);

myAdapter.Fill(ds);

this.grdTest.DataSource = ds.Tables[0].DefaultView;

this.grdTest.DataKeyField = "CategoryID";

this.grdTest.DataBind();

}

}

接下来我们给模板列里面的每一个按钮都添加一个客户端的onclick事件。我想大家都应改知道Attributes属

性吧!可以通过他向客户端输出客户端控件的属性比如:长度、颜色等等。但是通常情况我们使用它添加客户

端事件。知道javascript的朋友肯定知道confirm了!它会弹出一个确认对话框如果确定才提交form否则就不

提交,所以使用这个也是很自然的了。

private void grdTest_ItemDataBound(object sender,

System.Web.UI.WebControls.DataGridItemEventArgs e) {

switch(e.Item.ItemType){

case ListItemType.Item:

case ListItemType.AlternatingItem:

case ListItemType.EditItem:{

Button btn = (Button)e.Item.FindControl("btnDelete");

btn.Attributes.Add("onclick","return confirm('你是否

确定删除这条记录');");

break;

}

}

}

添加好这个事件里以后我们还需要添加如下的代码才能完成我们的工作:

private void grdTest_ItemCommand(object source,

System.Web.UI.WebControls.DataGridCommandEventArgs e) {

if(e.CommandName == "Delete"){

this.DeleteRow(this.grdTest.DataKeys[e.Item.ItemIndex].ToString

());

}

}

上面的事件就是我们点击DataGrid里面的控件的时候激发的事件,我们可以通过CommandName筛选出来我们想

要激发的方法DeleteRow(),一下就是这个方法的代码:

private void DeleteRow(string i){

string strConnection = ConfigurationSettings.AppSettings["sa"].ToString

();

SqlConnection myConnection = new SqlConnection(strConnection);

SqlCommand cmd = new SqlCommand("DELETE FROM Categories WHERE

(CategoryID = "+i+")",myConnection);

myConnection.Open();

cmd.ExecuteNonQuery();

myConnection.Close();

}

上面的函数接收一个参数,此参数是当前选中行的关键字。

有错误的地方请多多指教。e_mail:wu_jian830@hotmail.com

 

本文地址:http://www.45fan.com/a/question/69678.html
Tags: 功能 确定 DataGrid
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部