效果圖:
Html代碼
<table align="center" bgcolor="#c0de98" border="0" cellpadding="0" cellspacing="1" width="99%">
<tr>
<th colspan="2">
GridVIEw演示</th>
</tr>
<tr>
<td colspan="2" >
<ASP:GridView ID="GridView" runat="server" Width="100%" AutoGenerateColumns="False" AllowPaging="True" OnPageIndexChanging="GridView_PageIndexChanging" PageSize="12" OnRowDeleting="GridView_RowDeleting" OnRowDataBound="GridVIEw_RowDataBound" >
<Columns>
<ASP:BoundField DataFIEld="UserID" HeaderText="UserID" ReadOnly="True" />
<ASP:BoundField DataFIEld="C_Name" HeaderText="中文名字" ReadOnly="True" />
<ASP:BoundField DataFIEld="E_Name" HeaderText="英文名字" ReadOnly="True" />
<ASP:BoundField DataFIEld="QQ" HeaderText="QQ帳號" />
<ASP:CommandFIEld HeaderText="刪除" ShowDeleteButton="True" />
</Columns>
<RowStyle HorizontalAlign="Center" />
<PagerStyle HorizontalAlign="Right" />
</ASP:GridVIEw>
</td>
</tr>
</table>
C#代碼
using System;
using System.Data;
using System.Data.SqlClIEnt;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Demo11 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
BindData();
}
}
public void BindData()
{
string strSql = "select UserID,C_Name,E_Name,QQ from Demo_User ";
DataTable dt = SqlHelper.ExecuteDataset(SqlHelper.CONN_STRING, CommandType.Text, strSql, null).Tables[0];
GridVIEw.DataSource = dt;
GridVIEw.DataKeyNames = new string[] { "UserID" };//主鍵
GridVIEw.DataBind();
}
protected void GridView_PageIndexChanging(object sender, GridVIEwPageEventArgs e)
{
GridVIEw.PageIndex = e.NewPageIndex;
BindData();
}
protected void GridView_RowDeleting(object sender, GridVIEwDeleteEventArgs e)
{
int UserID = (int)GridVIEw.DataKeys[e.RowIndex].Value;
string strSql = "Delete Demo_User where UserID=@UserID";
SqlParameter[] para = {
new SqlParameter("@UserID", UserID),
};
SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING, CommandType.Text, strSql, para);
BindData();
}
protected void GridView_RowDataBound(object sender, GridVIEwRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[4].Controls[0]).Attributes.Add("onclick", "Javascript:return confirm('你確認要刪除:\"" + e.Row.Cells[1].Text + "\"嗎?')");
}
}
}
}