一个完整的DataGrid分页及全选删除实例

前台HTML代码:

 

<HTML>
 <HEAD>
  <title></title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  <script language="javascript">
  function CheckAll(form)
    {
     for (var i=0;i<form.elements.length;i++)
     {
      var e = form.elements[i];
      e.checked = form.chkall.checked;
     }
    }
   
   function SelectAll()
   {
    var len=document.Form1.elements.length;
    var i;
    for (i=0;i<len;i++)
    {
     if (document.Form1.elements[i].type=="checkbox")
     {
      document.Form1.elements[i].checked=true;       
     }
    }
   }
   function UnSelectAll()
   {
    var len=document.Form1.elements.length;
    var i;
    for (i=0;i<len;i++)
    {
     if (document.Form1.elements[i].type=="checkbox")
     {
      document.Form1.elements[i].checked=false;       
     }
    }
   }
  </script>
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <table width="100%" align="center">
    <tr>
     <td>
      <asp:DataGrid id="DataGrid1" runat="server" PageSize="6" AllowPaging="True" AutoGenerateColumns="False"
       AllowSorting="True" DataKeyField="id">
       <Columns>
        <asp:TemplateColumn>
         <HeaderTemplate>
          <input type="checkbox" οnclick="CheckAll(this.form)" id="chkall" name="chkall" />
         </HeaderTemplate>
         <ItemTemplate>
          <asp:CheckBox id="cbFlag" runat="server"></asp:CheckBox>
         </ItemTemplate>
        </asp:TemplateColumn>
        <asp:BoundColumn DataField="id" HeaderText="记录号"></asp:BoundColumn>
        <asp:TemplateColumn HeaderText="序号">
         <ItemTemplate>
          <%# Container.ItemIndex+1%>
         </ItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="标题">
         <ItemTemplate>
          <%#DataBinder.Eval(Container.DataItem,"title")%>
         </ItemTemplate>
        </asp:TemplateColumn>
       </Columns>
       <PagerStyle Visible="False"></PagerStyle>
      </asp:DataGrid>
     </td>
    </tr>
    <tr>
     <td>
      <INPUT type="button" value="全部选择" οnclick="SelectAll()"><INPUT type="button" value="全部取消" οnclick="UnSelectAll()"><asp:Button id="btnDelete" runat="server" Text="删除"></asp:Button>
     </td>
    </tr>
    <tr>
     <td><asp:label id="lblCount" runat="server" Font-Name="verdana" Font-size="8pt"></asp:label>&nbsp;&nbsp;
      <asp:label id="lblpage" runat="server" Font-Name="verdana" Font-size="8pt"></asp:label>&nbsp;&nbsp;
      <asp:linkbutton id="btnFirst" οnclick="PagerButtonClick" runat="server" Font-Name="verdana" Font-size="8pt"
       CssClass="a1" BorderStyle="None" CommandArgument="0" ForeColor="navy">首页</asp:linkbutton>&nbsp;&nbsp;
      <asp:linkbutton id="btnPrev" οnclick="PagerButtonClick" runat="server" Font-Name="verdana" Font-size="8pt"
       CssClass="a1" CommandArgument="prev" ForeColor="navy">上一页</asp:linkbutton>&nbsp;&nbsp;
      <asp:linkbutton id="btnNext" οnclick="PagerButtonClick" runat="server" Font-Name="verdana" Font-size="8pt"
       CssClass="a1" CommandArgument="next" ForeColor="navy">下一页</asp:linkbutton>&nbsp;&nbsp;
      <asp:linkbutton id="btnLast" οnclick="PagerButtonClick" runat="server" Font-Name="verdana" Font-size="8pt"
       CssClass="a1" CommandArgument="last" ForeColor="navy">尾页</asp:linkbutton>&nbsp;&nbsp;
      <asp:label id="lblCurrentIndex" runat="server" Font-Name="verdana" Font-size="8pt"></asp:label>
      <asp:label id="lblPageCount" runat="server" Font-Name="verdana" Font-size="8pt"></asp:label>&nbsp;&nbsp;
      <asp:label id="LabTz" runat="server" Font-Name="verdana" Font-size="8pt">转到第</asp:label>&nbsp;
      <asp:dropdownlist id="DDLpage" runat="server" AutoPostBack="True"></asp:dropdownlist>
      <asp:label id="Laby" runat="server" Font-Name="verdana" Font-size="8pt"> 页</asp:label>
     </td>
    </tr>
   </table>
  </form>
  </FORM>
 </body>
</HTML>

 

后台C#代码:

 

private void Page_Load(object sender, System.EventArgs e)
  {
   if(!Page.IsPostBack)
   {
    BindData();
    this.btnDelete.Attributes.Add("onclick", "return confirm('您确认要删除吗?');");
   }
  }

  public void BindData()
  {
   string sql="select * from magfile order by id desc";
   DataSet ds=webAscx.DataBase.GetDatabase(sql);
   this.DataGrid1.DataSource=ds;
   this.DataGrid1.DataKeyField="id";
   this.DataGrid1.DataBind();
   if(ds==null || ds.Tables[0].Rows.Count<=0)
    lblCount.Text="共0条记录";
   else
   {
    int RecordsCount=ds.Tables[0].Rows.Count;
    lblCount.Text="共"+ RecordsCount+ "条记录";
   }
   lblpage.Text="每页"+DataGrid1.PageSize.ToString()+"条";
   lblCurrentIndex.Text = "页次: <font color=red>" + (DataGrid1.CurrentPageIndex + 1).ToString() + "</font> /";
   lblPageCount.Text = DataGrid1.PageCount.ToString() + " 页";

   // 添加页次列表框
   DDLpage.Items.Clear();
   for (int i=1;i<=DataGrid1.PageCount;i++)
   {
    DDLpage.Items.Add(new ListItem(i.ToString(),i.ToString()));
   }
   DDLpage.Items.FindByText((DataGrid1.CurrentPageIndex+1).ToString()).Selected=true;

   ShowStats();
  }

  private void ShowStats()
  {
   if (DataGrid1.CurrentPageIndex==0)
   {
    btnFirst.Enabled =false;
    btnPrev.Enabled =false;
   }
   else
   {
    btnFirst.Enabled =true;
    btnPrev.Enabled =true;

   };

   if (DataGrid1.CurrentPageIndex==DataGrid1.PageCount-1)
   {
    btnNext.Enabled =false;
    btnLast.Enabled =false;
   }
   else
   {
    btnNext.Enabled =true;
    btnLast.Enabled =true;
   };
  }
  public void PagerButtonClick(object sender, EventArgs e)
  {
   string arg = ((LinkButton)sender).CommandArgument.ToString();
   switch(arg)
   {
    case "next":
     if (DataGrid1.CurrentPageIndex < (DataGrid1.PageCount - 1))
     {
      DataGrid1.CurrentPageIndex += 1;
     }
     break;
    case "prev":
     if (DataGrid1.CurrentPageIndex > 0)
     {
      DataGrid1.CurrentPageIndex -= 1;
     }
     break;
    case "last":
     DataGrid1.CurrentPageIndex = (DataGrid1.PageCount - 1);
     break;
    default:
     DataGrid1.CurrentPageIndex = System.Convert.ToInt32(arg);
     break;
   }
   BindData();   
  }
  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
   this.DDLpage.SelectedIndexChanged += new System.EventHandler(this.DDLpage_SelectedIndexChanged);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void btnDelete_Click(object sender, System.EventArgs e)
  {
   string SelectedString = "";//定义一个变量

   foreach(System.Web.UI.WebControls.DataGridItem dl in this.DataGrid1.Items)
   {
    for(int i=0;i<dl.Cells[0].Controls.Count;i++)//循环DataGrid的第一个单元格
    {
     if(dl.Cells[0].Controls[i].GetType().ToString()=="System.Web.UI.WebControls.CheckBox")//判断类型是否为CheckBox
     {
      if(((CheckBox)dl.Cells[0].Controls[i]).Checked==true)//如果CheckBox被选中
      {
       SelectedString += DataGrid1.DataKeys[dl.ItemIndex].ToString() + ",";
       //因为设置了DataGrid的DataKeyField属性(编号),所以可以根据Datakeys得到选中CheckBox的那行所对应的那条记录的编号
       //以逗号分隔,加入同一个字符串中
      }
     }
    }
   }

   if(SelectedString!="")
   {
    string result="";
    SelectedString = SelectedString.Substring(0,SelectedString.Length-1);//截取最后一个逗号
    string[] Arr = SelectedString.Split(',');//分割字符串,放入数组中
    for(int i=0;i<Arr.Length;i++)//循环数组
    {
     if(Arr[i].Trim()!="")//如果值不为空
     {
      result += Arr[i].Trim();
      DeleteRecord(Int32.Parse(Arr[i].Trim()));//删除一条记录
     }
    }
   }
   BindData();
  }

  private void DeleteRecord(int i)
  {
   string strsql = "delete from magFile where id = "+ i;
   webAscx.DataBase.UpdateDatabase(strsql);
   BindData();
  }

  private void DDLpage_SelectedIndexChanged(object sender, System.EventArgs e)
  {
   DataGrid1.CurrentPageIndex=Convert.ToInt32(DDLpage.SelectedValue)-1;
   BindData();
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值