girdView实现自定义分页,编辑,删除和修改(转)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PM_Base.aspx.cs" Inherits="PM_Base"
  2    EnableEventValidation="false" 
%>
  3
  4<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  5<html xmlns="http://www.w3.org/1999/xhtml">
  6<head runat="server">
  7    <title>基本信息</title>
  8</head>
  9<body>
 10    <form id="form1" runat="server">
 11        <!--导航事件按钮-->
 12        <table cellpadding="0" cellspacing="0" width="100%">
 13            <tr>
 14                <td align="right" style="height: 25px;" nowrap="nowrap">
 15                    <input type="hidden" id="HiddenID" name="HiddenID" runat="server" />
 16                    <input id="btnView" runat="server" type="button" value="查看" style="width: 50px; height: 20px;"
 17                        class="ClassBtn" onclick="return View();" />
 18                    <asp:Button ID="btnSearch" runat="server" Text="查询" Enabled="false" Width="50px"
 19                        Height="20px" OnClick="btnSearch_Click" />
 20                    <input id="btnAdd" runat="server" type="button" value="添加" style="width: 50px; height: 20px;"
 21                        class="ClassBtn" onclick="return Add();" />
 22                    <input id="btnEdit" runat="server" type="button" value="修改" style="width: 50px; height: 20px;"
 23                        class="ClassBtn" onclick="return Edit();" />
 24                    <asp:Button ID="btnDelete" runat="server" Text="删除" Width="50px" Height="20px" OnClick="btnDelete_Click"
 25                        OnClientClick="javascript:return ( checkSelect() && confirm('警告:删除将无法恢复!/n确认删除吗?') );" />
 26                    <asp:Button ID="btnPrint" runat="server" Text="打印" Width="50px" Height="20px" OnClick="btnToExcel_Click" />
 27                    <asp:Button ID="btnOut" runat="server" Text="导出" Width="50px" Height="20px" OnClick="btnToExcel_Click" />
 28                </td>
 29            </tr>
 30        </table>
 31        <asp:GridView ID="GridView1" SkinID="gvClass2" runat="server" Width="100%" DataKeyNames="ID"
 32            AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" OnDataBound="GridView1_DataBound"
 33            AllowSorting="True" OnSorting="GridView1_Sorting" AllowPaging="True" PageSize="10"
 34            OnPageIndexChanging="GridView1_PageIndexChanging">
 35            <PagerTemplate>
 36                <table width="100%">
 37                    <tr>
 38                        <td width="50%" align="left">
 39                            <asp:Label ID="MessageLabel" ForeColor="Blue" Text="页码:" runat="server" />
 40                            <asp:DropDownList ID="PageDropDownList" AutoPostBack="true" OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged"
 41                                runat="server" />
 42                            <asp:LinkButton CommandName="Page" CommandArgument="First" ID="linkBtnFirst" runat="server">首页</asp:LinkButton>
 43                            <asp:LinkButton CommandName="Page" CommandArgument="Prev" ID="linkBtnPrev" runat="server">上一页</asp:LinkButton>
 44                            <asp:LinkButton CommandName="Page" CommandArgument="Next" ID="linkBtnNext" runat="server">下一页</asp:LinkButton>
 45                            <asp:LinkButton CommandName="Page" CommandArgument="Last" ID="linkBtnLast" runat="server">尾页</asp:LinkButton>
 46                        </td>
 47                        <td width="50%" align="right">
 48                            <asp:Label ID="CurrentPageLabel" ForeColor="Blue" runat="server" />
 49                        </td>
 50                    </tr>
 51                </table>
 52            </PagerTemplate>
 53            <Columns>
 54                <asp:TemplateField>
 55                    <ItemTemplate>
 56                        <input id="check" runat="server" type="checkbox" value='<%# Eval("ID") %>' />
 57                    </ItemTemplate>
 58                    <HeaderTemplate>
 59                        <input id="checkAll" title="全选" onclick="javascript:CheckAll(this);" runat="server"
 60                            type="checkbox" />
 61                    </HeaderTemplate>
 62                    <ItemStyle Width="5%" />
 63                </asp:TemplateField>
 64                <asp:BoundField DataField="Name" HeaderText="名称" SortExpression="Name">
 65                    <ItemStyle Width="30%" HorizontalAlign="Left" />
 66                </asp:BoundField>
 67                <asp:BoundField DataField="Description" HeaderText="描述" SortExpression="Description">
 68                    <ItemStyle HorizontalAlign="Left" />
 69                </asp:BoundField>
 70            </Columns>
 71        </asp:GridView>
 72        <asp:Label ID="Message" runat="server" ForeColor="Red"></asp:Label>
 73    </form>
 74</body>
 75</html>
 76
 77<script language="javascript">
 78function $(s){return document.getElementById(s);}
 79function isNull(_sVal){return (_sVal == "" || _sVal == null || _sVal == "undefined");}
 80//获取地址栏参数
 81function GetURL(name)
 82{
 83    var URLParams = new Array();
 84    var aParams = document.location.search.substr(1).split('&');
 85    for (i=0; i < aParams.length; i++)
 86    {
 87        var aParam = aParams[i].split('=');
 88        URLParams[aParam[0]] = aParam[1];
 89    }

 90    //取得传过来的name参数
 91    return URLParams[name];
 92}

 93
 94var tgs;
 95var tmp_background_val; 
 96function tog(n,flags)
 97
 98    if (tgs){
 99     tgs.style.background= tmp_background_val ; 
100    }
 
101    n.style.background= '#99ccff' ;
102    tmp_background_val=flags;
103    tgs=n;
104}

105
106function GetRowIndex(obj)
107{
108    $('<%=HiddenID.ClientID %>').value = obj;
109}

110
111var HiddenID;
112function checkSelect()
113{
114    HiddenID=$('<%=HiddenID.ClientID %>').value;
115    if(isNull(HiddenID))
116    {
117        alert("请选择一条记录!");
118    }

119    return !isNull(HiddenID);
120}

121
122function CheckAll(spanChk)//CheckBox全选
123{
124    var oItem = spanChk.children;
125    var theBox=(spanChk.type=="checkbox")?spanChk:spanChk.children.item[0];
126    xState=theBox.checked;
127    elm=theBox.form.elements;
128    for(i=0;i<elm.length;i++)
129    if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)
130    {
131        if(elm[i].checked!=xState)
132        elm[i].click();
133    }

134}

135//---------------------------------------------------------
136//查看
137function View()
138{
139    if(checkSelect())
140    {
141        var url="PM_BaseEdit.aspx?ID=" + HiddenID + "&tableName=" + GetURL("tableName");
142        winOpen(url);
143    }

144}

145//添加
146function Add()
147{
148    var url="PM_BaseAdd.aspx?tableName=" + GetURL("tableName");
149    winOpen(url);
150}

151//编辑
152function Edit()
153{
154    if(checkSelect())
155    {
156        var url="PM_BaseEdit.aspx?ID=" + HiddenID + "&tableName=" + GetURL("tableName");
157        winOpen(url);
158    }

159}

160
161//弹出打开新页面-------------------------------------------
162function winOpen(url)
163{
164    var sFeatures='height=400, width=650, top=100, left=200,toolbar=0, menubar=0, scrollbars=auto, resizable=1, location=0, status=0';
165    window.open(url,"PM_Base",sFeatures);
166}

167
168function showDialog(url)
169{
170    var sFeatures = "dialogHeight:400px;dialogWidth:500px;resizeable:no;help:no;status:no";
171    var obj=showModalDialog(url,window,sFeatures); 
172}

173
</script>

PM_Base.aspx.cs


  1using System;
  2using System.Data;
  3using System.Data.OleDb;
  4using System.Data.SqlClient;
  5using System.Configuration;
  6using System.Collections;
  7using System.Web;
  8using System.Web.Security;
  9using System.Web.UI;
 10using System.Web.UI.WebControls;
 11using System.Web.UI.WebControls.WebParts;
 12using System.Web.UI.HtmlControls;
 13using System.Web.Caching;
 14using Framework.Components;
 15
 16public partial class PM_Base : Framework.UI.PageBase
 17{
 18    #region Page事件
 19    MX.PM.BLL.Progress myBiz = new MX.PM.BLL.Progress();
 20    string tableName;
 21
 22    protected void Page_Load(object sender, EventArgs e)
 23    {
 24        tableName = base.GetUrl("tableName");
 25        //首先要进行权限判断
 26        if (!string.IsNullOrEmpty(tableName))
 27        {
 28            if (!Page.IsPostBack)
 29            {
 30                if (!Framework.Globals.CurrentPrincipal.HasPermission((int)Framework.Helper.ProjectManage.BaseBrowse))
 31                {
 32                    Framework.AppException exception = new Framework.AppException("对不起,您无权操作此页面!");
 33                    GridView1.Visible = false;
 34                    btnView.Disabled = true;
 35                }

 36                if (!Framework.Globals.CurrentPrincipal.HasPermission((int)Framework.Helper.ProjectManage.BaseSelect))
 37                {
 38                    btnSearch.Enabled = false;
 39                    btnPrint.Enabled = false;
 40                    btnOut.Enabled = false;
 41                }

 42                if (!Framework.Globals.CurrentPrincipal.HasPermission((int)Framework.Helper.ProjectManage.BaseAdd))
 43                {
 44                    btnAdd.Disabled = true;
 45                }

 46                if (!Framework.Globals.CurrentPrincipal.HasPermission((int)Framework.Helper.ProjectManage.BaseUpdate))
 47                {
 48                    btnEdit.Disabled = true;
 49                }

 50                if (!Framework.Globals.CurrentPrincipal.HasPermission((int)Framework.Helper.ProjectManage.BaseDelete))
 51                {
 52                    btnDelete.Enabled = false;
 53                }

 54                // 在此处放置查询代码
 55                string strTableName = "PM_Progress";
 56                this.btnSearch.OnClientClick = "javascript:window.showModalDialog('../Tools/AjaxGeneralSearch/AjaxSeachPage.aspx?table=" + strTableName + "','','dialogWidth:500px; dialogHeight:400px; status:0; help:0; center:1; scroll:0; resizable:1;');";
 57            }

 58
 59            GetData();//重新获取操作后的数据源
 60            if (!Page.IsPostBack)
 61            {
 62                BindGrid();//绑定GridView,为删除服务
 63            }

 64        }

 65    }

 66
 67    #endregion

 68
 69    #region GridView
 70    #region 属性
 71    /// <summary>
 72    /// 获取或设置数据源
 73    /// </summary>

 74    public DataTable DataSource
 75    {
 76        get
 77        {
 78            if (ViewState["dataSource"== null)
 79                return null;
 80            else
 81                return (DataTable)ViewState["dataSource"];
 82        }

 83        set
 84        {
 85            ViewState["dataSource"= value;
 86        }

 87    }

 88    /// <summary>
 89    /// 获取或设置排序方向
 90    /// </summary>

 91    public SortDirection Sort_Direction
 92    {
 93        get
 94        {
 95            if (ViewState["sortDirection"== null)
 96                return SortDirection.Ascending;
 97            else
 98                return (SortDirection)ViewState["sortDirection"];
 99        }

100        set
101        {
102            ViewState["sortDirection"= value;
103        }

104    }

105    /// <summary>
106    /// 获取或设置当前分页码
107    /// </summary>

108    public int CurrentPage
109    {
110        get
111        {
112            if (ViewState["CurrentPage"== null)
113                return 0;
114            else
115                return (int)ViewState["CurrentPage"];
116        }

117        set
118        {
119            ViewState["CurrentPage"= value;
120        }

121    }

122        #endregion

123
124    #region 数据绑定
125    /// <summary>
126    /// 获取数据
127    /// </summary>

128    protected void GetData()
129    {
130        this.DataSource = myBiz.GetBase(tableName).Tables[0]; ;
131    }

132
133    /// <summary>
134    /// GridView 数据绑定
135    /// </summary>

136    private void BindGrid()
137    {
138        Message.Text = "";
139        GridView1.DataSource = this.DataSource;
140        GridView1.DataBind();
141        GridView1.PageIndex = CurrentPage;//设置当前页
142    }

143
144    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
145    {
146        if (e.Row.RowType == DataControlRowType.DataRow)
147        {
148            System.Web.UI.HtmlControls.HtmlInputCheckBox check = (System.Web.UI.HtmlControls.HtmlInputCheckBox)e.Row.FindControl("check");
149            string id = check.Value;
150
151            if (e.Row.RowIndex % 2 != 0)
152                e.Row.Attributes.Add("onclick""GetRowIndex('" + id + "'),tog(this,'#EFF3FB')");
153            else
154                e.Row.Attributes.Add("onclick""GetRowIndex('" + id + "'),tog(this,'#ffffff')");
155        }

156    }

157    #endregion

158
159    #region 分页绑定
160    protected void PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e)
161    {
162        GridViewRow pagerRow = GridView1.BottomPagerRow;
163        DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
164        GridView1.PageIndex = pageList.SelectedIndex;
165        this.CurrentPage = pageList.SelectedIndex;
166        BindGrid();
167    }

168
169    protected void GridView1_DataBound(Object sender, EventArgs e)
170    {
171        if (this.DataSource.Rows.Count > 0)
172        {
173            GridViewRow pagerRow = GridView1.BottomPagerRow;
174            LinkButton linkBtnFirst = (LinkButton)pagerRow.Cells[0].FindControl("linkBtnFirst");
175            LinkButton linkBtnPrev = (LinkButton)pagerRow.Cells[0].FindControl("linkBtnPrev");
176            LinkButton linkBtnNext = (LinkButton)pagerRow.Cells[0].FindControl("linkBtnNext");
177            LinkButton linkBtnLast = (LinkButton)pagerRow.Cells[0].FindControl("linkBtnLast");
178            if (GridView1.PageIndex == 0)
179            {
180                linkBtnFirst.Enabled = false;
181                linkBtnPrev.Enabled = false;
182            }

183            else if (GridView1.PageIndex == GridView1.PageCount - 1)
184            {
185                linkBtnLast.Enabled = false;
186                linkBtnNext.Enabled = false;
187            }

188            else if (GridView1.PageCount <= 0)
189            {
190                linkBtnFirst.Enabled = false;
191                linkBtnPrev.Enabled = false;
192                linkBtnNext.Enabled = false;
193                linkBtnLast.Enabled = false;
194            }

195            DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
196            Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
197            if (pageList != null)
198            {
199                for (int i = 0; i < GridView1.PageCount; i++)
200                {
201                    int pageNumber = i + 1;
202                    ListItem item = new ListItem(pageNumber.ToString() + "/" + GridView1.PageCount.ToString(), pageNumber.ToString());
203                    if (i == GridView1.PageIndex)
204                    {
205                        item.Selected = true;
206                    }

207                    pageList.Items.Add(item);
208                }

209            }

210            if (pageLabel != null)
211            {
212                int currentPage = GridView1.PageIndex + 1;
213                pageLabel.Text = "当前页: " + currentPage.ToString() +
214                  " / " + GridView1.PageCount.ToString();
215            }

216        }

217    }

218    #endregion

219
220    #region 分页
221    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
222    {
223        GridView1.PageIndex = e.NewPageIndex;
224        this.CurrentPage = e.NewPageIndex;//保存当前页码
225        BindGrid();
226    }

227    #endregion

228
229    #region 排序
230    /// <summary>
231    /// 排序
232    /// </summary>

233    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
234    {
235        SortGridView(ref GridView1, this.DataSource, e);
236    }

237    /// <summary>
238    /// 实现排序
239    /// </summary>

240    private void SortGridView(ref GridView gv, object dt, GridViewSortEventArgs e)
241    {
242        string sortDirection = "";
243        string sortExpression = e.SortExpression;
244        if (this.Sort_Direction == SortDirection.Ascending)
245        {
246            this.Sort_Direction = SortDirection.Descending;
247            sortDirection = "DESC";
248        }

249        else
250        {
251            this.Sort_Direction = SortDirection.Ascending;
252            sortDirection = "ASC";
253        }

254        DataView Source = new DataView((DataTable)dt);
255        Source.Sort = e.SortExpression + " " + sortDirection;
256        gv.DataSource = Source;
257        gv.DataBind();
258    }

259
260    #endregion

261    #endregion

262
263    #region 按钮事件
264    #region 查询
265    protected void btnSearch_Click(object sender, EventArgs e)
266    {
267        GetData();
268        BindGrid();
269    }

270    #endregion

271
272    #region 删除
273    /// <summary>
274    /// 删除,用循环得到用户选择的CheckBox
275    /// </summary>

276    protected void btnDelete_Click(object sender, EventArgs e)
277    {
278        Message.Text = "";
279        string sID = "";
280        for (int i = 0; i < GridView1.Rows.Count; i++)
281        {
282            GridViewRow row = GridView1.Rows[i];
283            System.Web.UI.HtmlControls.HtmlInputCheckBox check = (System.Web.UI.HtmlControls.HtmlInputCheckBox)row.FindControl("check");
284            if (check.Checked)
285            {
286                sID += check.Value + ",";
287            }

288        }

289        if (sID.Length > 0)
290        {
291            //MX.Sys.DAL.Log log = new MX.Sys.DAL.Log(this.UserInfo.UserName, "删除数据表" + tableName + ",sID=" + sID);
292            myBiz.DeleteBase(tableName, sID);//截取结尾的逗号
293            Message.Text = "删除成功!";
294            GetData();
295            BindGrid();
296        }

297        else
298        {
299            Message.Text = "删除失败,请勾选要删除项!";
300        }

301    }

302    #endregion

303
304    #region 导出 打印
305    public override void VerifyRenderingInServerForm(Control control)
306    {
307        // 为转 excel 出问题而加上的过程(一定加!!)// Confirms that an HtmlForm control is rendered for
308    }

309
310    protected void btnToExcel_Click(object sender, EventArgs e)
311    {
312        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
313        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
314
315        GridView1.AllowPaging = false;//取消分页
316        BindGrid();
317
318        GridView1.RenderControl(htmlWrite);
319
320        GridView1.AllowPaging = true;//恢复分页
321        BindGrid();
322
323        //---专用导出页面
324        PrintInfo info = new PrintInfo();
325        info.Title = "工程列表";
326        info.Orientation = true;
327        info.ShowTime = true;
328        info.Text = stringWrite.ToString();
329        ToPrint(info);
330        //---
331    }

332    /// <summary>
333    /// 打印
334    /// </summary>

335    private void ToPrint(PrintInfo info)
336    {
337        Session["ToExcel"= info;//***用Session传递参数
338
339        string strURL = "../Tools/WebPrint";
340        string sFeatures = "height=600, width=800, top=0, left=50,toolbar=no, menubar=no, scrollbars=yes, resizable=no, location=no, status=1";
341        string js = "window.open('{0}','print','{1}');";
342        js = string.Format(js, strURL, sFeatures);
343        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "print", js, true);
344    }

345    #endregion

346    #endregion

347
348    #region 公共函数
349
350    #endregion

351
352}

你可能感兴趣的:(JavaScript,server,null,url,asp,sorting)