删除技巧

private void dgShow_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   if(dgShow.Items.Count==1)
   {
    if(dgShow.CurrentPageIndex!=0)
     dgShow.CurrentPageIndex = dgShow.CurrentPageIndex-1;
   }
   string strSql = "delete from tbStudentinfo where studentid="+e.Item.Cells[0].Text+"";
   ExecuteSql(strSql);
   BindData();

  }

 

改变控件宽度

private void dgShow_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   if (e.Item.ItemType == ListItemType.EditItem)
   {
    for (int i=0;i<e.Item.Cells.Count;i++)
    {
     if(e.Item.Cells[i].Controls.Count>0)
     {
      try
      {
       TextBox t =(TextBox)e.Item.Cells[i].Controls[0];
       t.Width=130;
      }
      catch(Exception ee)
      {
      }
     }
    }
   }
  }

绑定技巧

<EditItemTemplate>
        <asp:RadioButton id=cbSex runat="server" Text="男" Checked='<%# DataBinder.Eval(Container, "DataItem.Sex") %>' GroupName="Sex">
        </asp:RadioButton>
        <asp:RadioButton id=RadioButton4 runat="server" Text="女" Checked='<%# !(bool)DataBinder.Eval(Container, "DataItem.Sex") %>' GroupName="Sex">
        </asp:RadioButton>
       </EditItemTemplate>

排序

 AllowPaging="True">

 private void dgShow_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
  {
   dgShow.CurrentPageIndex = e.NewPageIndex;
   BindData();
  }

excel 导出

private void btnMIME_Click(object sender, System.EventArgs e)
  {
   Response.ContentType = "application/vnd.ms-excel";
            Response.Charset = "";
   this.EnableViewState = false;
   System.IO.StringWriter sw = new System.IO.StringWriter();
   System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
   int nCur = dgShow.CurrentPageIndex;
   int nSize = dgShow.PageSize;
   
   dgShow.AllowPaging = false;
   BindData();
    
   dgShow.Columns[7].Visible =false;
   dgShow.RenderControl(hw);
   dgShow.Columns[7].Visible =true;
   
   //以下恢复分页
   dgShow.AllowPaging = true;
   dgShow.CurrentPageIndex = nCur;
   dgShow.PageSize = nSize;
   BindData();
   Response.Write(sw.ToString());
   Response.End();
  }

全选

<asp:TemplateColumn HeaderText="选择">
       <HeaderTemplate>
        <asp:CheckBox id="cbAll" runat="server" OnCheckedChanged="CheckAll" Text="全选" AutoPostBack="True"></asp:CheckBox>
       </HeaderTemplate>
       <ItemTemplate>
        <asp:CheckBox id="cbSelect" runat="server" AutoPostBack="True"></asp:CheckBox>
       </ItemTemplate>
      </asp:TemplateColumn>

btnDelete.Attributes.Add("onclick", "return confirm('您真的要删除所选项吗?');");

private void btnDelete_Click(object sender, System.EventArgs e)
  {
   foreach(DataGridItem dgi in dgShow.Items)
   {
    CheckBox cb = (CheckBox)dgi.FindControl("cbSelect");
    if(cb.Checked)
    {
     //以下执行删除操作
     int nID = int.Parse(dgi.Cells[0].Text);
     string strSql = "delete from tbStudentinfo where studentid="+nID;
     ExecuteSql(strSql);
    }
   }
   dgShow.CurrentPageIndex = 0;
   BindData();
  }

删除确认

 private void dgShow_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   switch(e.Item.ItemType)
   {
    case ListItemType.Item:
    case ListItemType.EditItem:
    case ListItemType.AlternatingItem:
     Button    myDeleteButton = (Button)e.Item.FindControl("btnDelete");
     myDeleteButton.Text = "删除此行";
     myDeleteButton.Attributes.Add("onclick", "return confirm('您真的要删除第 " + e.Item.ItemIndex.ToString() + " 行吗?');");
     break;
   }
  }

  private void dgShow_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   if(e.CommandName=="UserDelete")
    dgShow_DeleteCommand(source,e);
  }

 

下拉列表绑定

private void BindData()
  {
   string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
   SqlConnection con = new SqlConnection(strCon);
   SqlDataAdapter da = new SqlDataAdapter("Select * from tbStudentinfo",con);
   DataSet ds = new DataSet();
   da.Fill(ds,"studentinfo");
   dgShow.DataSource = ds.Tables["studentinfo"].DefaultView;
   dgShow.DataBind();
   foreach(DataGridItem dgi in dgShow.Items)
   {
    //以下绑定非编辑状态下拉列表
    DropDownList ddI = (DropDownList)dgi.FindControl("ddlSexI");
    if(ddI!=null)
    {
     bool bSex = (bool)ds.Tables["studentinfo"].Rows[dgi.ItemIndex]["Sex"];
     if(bSex)
      ddI.SelectedIndex = 0;
     else
      ddI.SelectedIndex = 1;
    }
    //以下绑定编辑状态下拉列表
    DropDownList ddE = (DropDownList)dgi.FindControl("ddlSexE");
    if(ddE!=null)
    {
     bool bSex = (bool)ds.Tables["studentinfo"].Rows[dgi.ItemIndex]["Sex"];
     if(bSex)
      ddE.SelectedIndex = 0;
     else
      ddE.SelectedIndex = 1;
    }
    
   }
   
  }

private void dgShow_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   string strStudentID = e.Item.Cells[0].Text;//处于非编辑状态
   string strName = ((TextBox)(e.Item.Cells[1].Controls[0])).Text;//处于编辑状态
   string strPass =((TextBox)(e.Item.Cells[2].Controls[0])).Text;
   string strSex = ((DropDownList)(e.Item.FindControl("ddlSexE"))).SelectedItem.Value;
   string strBirthday =((TextBox)(e.Item.Cells[4].Controls[0])).Text;
   string strEmail =((TextBox)(e.Item.Cells[5].Controls[0])).Text;
   string strSql = "update tbStudentinfo set StudentName='"+strName+"',StudentPass='"+strPass+"'";
   strSql +=",Sex="+strSex+",Birthday='"+strBirthday+"',Email='"+strEmail+"' where studentid="+strStudentID+"";
   ExecuteSql(strSql);
   dgShow.EditItemIndex = -1;
   BindData();

  }

统计

<asp:DataGrid id="dgShow" style="Z-INDEX: 101; LEFT: 31px; POSITION: absolute; TOP: 93px" runat="server" Width="842px" Height="172px" BorderColor="Tan" BorderWidth="1px" BackColor="LightGoldenrodYellow" CellPadding="2" GridLines="None" ForeColor="Black" PageSize="1" AutoGenerateColumns="False" ShowFooter="True">
     <SelectedItemStyle ForeColor="GhostWhite" BackColor="DarkSlateBlue"></SelectedItemStyle>
     <AlternatingItemStyle BackColor="PaleGoldenrod"></AlternatingItemStyle>
     <HeaderStyle Font-Bold="True" BackColor="Tan"></HeaderStyle>
     <FooterStyle BackColor="Tan"></FooterStyle>
     <Columns>
      <asp:BoundColumn DataField="StudentID" ReadOnly="True" HeaderText="学生ID"></asp:BoundColumn>
      <asp:BoundColumn DataField="StudentName" HeaderText="学生姓名"></asp:BoundColumn>
      <asp:BoundColumn DataField="StudentPass" HeaderText="密码"></asp:BoundColumn>
      <asp:BoundColumn DataField="Sex" HeaderText="性别"></asp:BoundColumn>
      <asp:BoundColumn DataField="Birthday" HeaderText="生日" DataFormatString="{0:yyyy-M-d}"></asp:BoundColumn>
      <asp:BoundColumn DataField="Email" HeaderText="邮件地址"></asp:BoundColumn>
      <asp:BoundColumn DataField="Score" HeaderText="分数"></asp:BoundColumn>
     </Columns>
     <PagerStyle HorizontalAlign="Center" ForeColor="DarkSlateBlue" BackColor="PaleGoldenrod"></PagerStyle>
    </asp:DataGrid>

 private void BindData()
  {
   string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
   SqlConnection con = new SqlConnection(strCon);
   SqlDataAdapter da = new SqlDataAdapter("Select * from tbStudentinfo",con);
   DataSet ds = new DataSet();
   da.Fill(ds,"studentinfo");
   dgShow.DataSource = ds.Tables["studentinfo"].DefaultView;
   dgShow.DataBind();
   //以下作分数和的统计
   int count=0;
   for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
   {
    count += int.Parse(ds.Tables[0].Rows[i]["Score"].ToString());
   }
   int nAv = count/ds.Tables[0].Rows.Count;
   foreach(DataGridItem dgi in dgShow.Controls[0].Controls)
   {
    if (dgi.ItemType == ListItemType.Footer)
     dgi.Cells[6].Text = "平均:"+nAv.ToString();
   }
   
  }

 

 

DataGrid使用心得(附大量代码)

    1. 为 DataGrid 控件设计样式
   
    在<asp:datagrid id="DataGrid1" runat="server">之后添加如下代码
   
    <FooterStyle ForeColor="Black" BackColor="#CCCCCC"></FooterStyle>
    <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#008A8C"></SelectedItemStyle>
    <AlternatingItemStyle BackColor="Gainsboro"></AlternatingItemStyle>
    <ItemStyle ForeColor="Black" BackColor="#EEEEEE"></ItemStyle>
    <HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#000084"></HeaderStyle>
   
    说明:
    (1) 在每个标签内主要是  ForeColor   BackColor  Font-Bold 这几个属性值
   
    2. 为 DataGrid 控件添加绑定列
   
    <asp:BoundColumn DataField="" ReadOnly="True" HeaderText=""></asp:BoundColumn>
    说明:
    (1) 在标签内的基本属性是 DataField / HeaderText
    (2) DataFormatString 用于 获取或设置指定列中各项的显示格式的字符串。
     形式为 { A: Bxx }。例如,格式化字符串 {0:F2} 将显示带两位小数的定点数。
     其中A值只能设置为 0,因为每个单元格中只有一个值。
     冒号后的字符(常规示例中为 B)指定值的显示格式
     C  以货币格式显示数值。
        D  以十进制格式显示数值。
        E  以科学记数法(指数)格式显示数值。
        F  以固定格式显示数值。
        G  以常规格式显示数值。
        N  以数字格式显示数值。
        X  以十六进制格式显示数值。
    (3) Visible 获取或设置一个值,该值指示此列在 DataGrid 控件中是否可见。
    (4) ReadOnly 设置些列是否只读,若是只读的话,则不能修改.
    (5) SortExpression 获取或设置选择进行排序的列时传递到 OnSortCommand 方法的字段或表达式的名称。
  

  3. 为 DataGrid 控件添加模板列
    <asp:TemplateColumn HeaderText="类别">
     <ItemTemplate>
      <asp:Label Text='<%# DataBinder.Eval(Container.DataItem, "actorclassname") %>' runat="server" ID="Label1"/>
     </ItemTemplate>
     <EditItemTemplate>
      <select name="sltclassname">
       <% = ActorClass.GetParentClass(0) %>
      </select>
     </EditItemTemplate>
    </asp:TemplateColumn>
    说明:
    (1) 基本框架是
      <asp:TemplateColumn HeaderText="类别">
    <ItemTemplate></ItemTemplate>
     </asp:TemplateColumn>
    (2) 全面的模板列
     <asp:TemplateColumn>

               <HeaderTemplate>
                  <b> Tax </b>
               </HeaderTemplate>

               <ItemTemplate>
                  <asp:Label
                       Text='<%# DataBinder.Eval(Container.DataItem, "Tax") %>'
                       runat="server"/>
               </ItemTemplate>

               <EditItemTemplate>

                  <asp:CheckBox
                       Text="Taxable"
                       runat="server"/>

               </EditItemTemplate>

               <FooterTemplate>
                  <asp:HyperLink id="HyperLink1"
                       Text="Microsoft"
                       NavigateUrl="http://www.microsoft.com"
                       runat="server"/>
               </FooterTemplate>

            </asp:TemplateColumn>
 (3) 为布尔型列应用模板列
  <asp:TemplateColumn>
         <ItemTemplate>
             <asp:Label
                  Text='<%# DataBinder.Eval(Container.DataItem, "Tax") %>'
                     runat="server"/>
            </ItemTemplate>
            <EditItemTemplate>
             <asp:CheckBox
                  Text="Taxable"
                     runat="server"/>

            </EditItemTemplate>
        </asp:TemplateColumn>
        在正常状态,用 Label控件显示
        在编辑状态,用 CheckBox控件显示
   
 (4) 为枚举类型列应用模板列,如业务地区(全网/广东/云南等等)
  <asp:TemplateColumn HeaderText="处理方式">
   <ItemTemplate>
    <asp:Label ID="lbStatus">
     <%# DataBinder.Eval(Container, "DataItem.DealWith") %>
    </asp:Label>
   </ItemTemplate>
   <EditItemTemplate>
    <asp:DropDownList id="dpStatus2" runat="server" DataTextField="status">
     <asp:ListItem Value="Log">Log(日志)</asp:ListItem>
     <asp:ListItem Value="SendSms">SendSms(短信)</asp:ListItem>
    </asp:DropDownList>
   </EditItemTemplate>
  </asp:TemplateColumn>
  在正常状态,用 Label控件显示
  在编辑状态,用 DropDownList控件显示
 
 (5) 为长字符串应用模板列,如一篇文章的内容
  还未做过
  
 4. 为 DataGrid 控件添加按钮列
 
 <asp:ButtonColumn
        HeaderText="Remove from cart"
        ButtonType="PushButton"
        Text="Remove"
        CommandName="RemoveFromCart" />
    (1) 要使用按钮列,必须在 DataGrid 控件中添加 OnItemCommand 属性,并为该事件添加处理方法.
    (2) 模板列可以实现按钮列能实现的任何功能.
   
    5. 为 DataGrid 控件添加编辑列
    <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="更新" HeaderText="编辑" CancelText="取消" EditText="编辑"></asp:EditCommandColumn>
    (1) ButtonType 有两个值: LinkButton 超级链接样式按钮的列 | PushButton 普通按钮的列。

 6. 为 DataGrid 控件添加超链接列
 <asp:HyperLinkColumn Text="添加子类" DataNavigateUrlField="ActorclassID" DataNavigateUrlFormatString="addActorClass.aspx?classID={0}"></asp:HyperLinkColumn>
 (1) 为每一行设置相同的文字及跳转的URL地址
  设置 Text 和 NavigateUrl 属性,则列中的所有超级链接将共享同一标题和 URL
 (2) 为每一行设置不同的文字及不同跳转的URL地址
  A.  用 DataTextField 设置数据源字段,若还想在原数据的基础上加工一下(如字段值为300,想显示为300元)
   则再设置 DataTextFormatString 字段
  B. 用DataNavigateUrlField 及 DataNavigateUrlFormatString 来设置URL地址
   用DataTextField = "money" DataTextFormatString = "{0}元"
  C.  举例
   DataNavigateUrlField="ActorclassID" DataNavigateUrlFormatString="addActorClass.aspx?classID={0}"
   
 7. 为 DataGrid 控件添加"编辑"代码
  在 DataGrid 标签中加入
  OnUpdateCommand="DataGrid1_Update" OnCancelCommand="DataGrid1_Cancel" OnEditCommand="DataGrid1_Edit"代码
  在codeBehind页面加入如下代码
  ///响应编辑按钮
  public void DataGrid1_Edit(Object sender, DataGridCommandEventArgs e)
  {
   DataGrid1.EditItemIndex = e.Item.ItemIndex;
   if (Request.QueryString.Get("classID") != null)
    Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where parentID=" + Request.QueryString.Get("classID") + " order by depth,orderID desc"));
   else
    Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where depth=1 order by depth,orderID desc"));
  }
  
  ///响应取消按钮
  public void DataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)
  {
   DataGrid1.EditItemIndex = -1;
   if (Request.QueryString.Get("classID") != null)
    Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where parentID=" + Request.QueryString.Get("classID") + " order by depth,orderID desc"));
   else
    Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where depth=1 order by depth,orderID desc"));

  }
  
  ///响应更新按钮  
  public void DataGrid1_Update(Object sender, DataGridCommandEventArgs e)
  {
   TextBox ClassNameText = (TextBox)e.Item.Cells[1].Controls[0];
   string className = ClassNameText.Text;
   int classID = Int32.Parse((e.Item.Cells[0].Text).ToString());
   TextBox orderID2 = (TextBox)e.Item.Cells[5].Controls[0];
   int orderID = Int32.Parse(orderID2.Text);
   ActorClass.ModifyActorClass(className,classID,orderID);

   DataGrid1.EditItemIndex = -1;
   if (Request.QueryString.Get("classID") != null)
    Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where parentID=" + Request.QueryString.Get("classID") + " order by depth,orderID desc"));
   else
    Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where depth=1 order by depth,orderID desc"));
  }
  说明
  (1) DataGrid 事件处理程序的格式
   MethodName(Object sender, DataGridCommandEventArgs e)
  (2) 更新按钮的说明
   A. 获取编辑状态中的文本框
    TextBox ClassNameText = (TextBox)e.Item.Cells[1].Controls[0];
    string className = ClassNameText.Text;
   B. 获取编辑状态中的下拉列表框
    方法一
    int classID;
    classID = Int32.Parse(Request.Form.Get("sltclassname"));
    方法二
    DropDownList bbb = (DropDownList)e.Item.Cells[10].FindControl("dpStatus2");
    string ddpValue = bbb.SelectedValue
   C. 获取编辑状态中的复选框
    bool boolEnabled = ((CheckBox)e.Item.FindControl("chk_enabled")).Checked;
    String str2;
    if (boolEnabled)
    {
     str2="1";
    }
    else 
    {
     str2="0";
    }
    赋值给 str2 ,原因是插入到数据库的布尔型值只能是 1 或者 0
   D. 获取编辑状态中的文本值,即该列是只读的.
    string storyID = (e.Item.Cells[0].Text).ToString();
 
 8. 为 DataGrid 控件添加分页事件
  在 DataGrid 控件标签中加入如下代码
  OnPageIndexChanged="DataGrid1_PageIndexChanged"
  在后台中加入如下代码
  /// <summary>
  /// 响应分页事件
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  public void DataGrid1_Page(Object sender, DataGridPageChangedEventArgs e)
  {
   DataGrid1.CurrentPageIndex = e.NewPageIndex;
   DataBind();
  }
 
 9. 为 DataGrid 控件添加绑定事件,即在 DataGrid绑定时发生的事件处理
  一般用些事件来,做一些页面上的效果.如更改背景色,文本框大小等.
  OnItemDataBound="DataGrid1_ItemDataBound"
  /// <summary>
  /// 响应DataGrid绑定事件
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  public void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   if (e.Item.ItemType == ListItemType.Item)
   {
    e.Item.Attributes.Add("onmouseover","this.style.backgroundColor='#c8dafa'");
    e.Item.Attributes.Add("onmouseout","this.style.backgroundColor='white'");

   }
   else if (e.Item.ItemType == ListItemType.AlternatingItem)
   {
    e.Item.Attributes.Add("onmouseover","this.style.backgroundColor='#c8dafa'");
    e.Item.Attributes.Add("onmouseout","this.style.backgroundColor='#f6f6f6'");
   }
  }
  
 10. 为 DataGrid 控件添加接钮处理事件程序
  在 DataGrid 控件标签中加入如下代码
  OnItemCommand="ItemsGrid_Command"
  在后台中加入如下代码
  public void ItemsGrid_Command(Object sender, DataGridCommandEventArgs e)
  {
   switch(((LinkButton)e.CommandSource).CommandName)
   {

    case "Delete":
     int classID = Int32.Parse((e.Item.Cells[0].Text).ToString());
     ActorClass.DeleteActorClass(classID);
     if (Request.QueryString.Get("classID") != null)
      Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where parentID=" + Request.QueryString.Get("classID") + " order by depth,orderID desc"));
     else
      Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where depth=1 order by depth,orderID desc"));
     break;

     // Add other cases here, if there are multiple ButtonColumns in
     // the DataGrid control.
    case "hidden":
     int actorID = Int32.Parse((e.Item.Cells[0].Text).ToString());
     ActorClass.HiddenActorClass(actorID);
     if (Request.QueryString.Get("classID") != null)
      Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where parentID=" + Request.QueryString.Get("classID") + " order by depth,orderID desc"));
     else
      Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where depth=1 order by depth,orderID desc"));
     break;
    case "MoveUp":
     int actorclassID = Int32.Parse((e.Item.Cells[0].Text).ToString());
     string orderID = (e.Item.Cells[5].Text).ToString();
     ActorClass.MoveUp(orderID,actorclassID);
     if (Request.QueryString.Get("classID") != null)
      Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where parentID=" + Request.QueryString.Get("classID") + " order by depth,orderID desc"));
     else
      Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where depth=1 order by depth,orderID desc"));
     break;
    case "MoveDown":
     actorclassID = Int32.Parse((e.Item.Cells[0].Text).ToString());
     orderID = (e.Item.Cells[5].Text).ToString();
     ActorClass.MoveDown(orderID,actorclassID);
     if (Request.QueryString.Get("classID") != null)
      Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where parentID=" + Request.QueryString.Get("classID") + " order by depth,orderID desc"));
     else
      Common.BindData(DataGrid1,Common.GetSource("select * from ActorClass where depth=1 order by orderID"));
     break;
    

    default:
     // Do nothing.
     break;

   }
  }

 11. 为 DataGrid添加模板列,但是内容根据字段值来显示"链接",还是文本
  以下三个都是,根据字段列不同,而显示内容及显示控件不同的处理代码.
  <asp:TemplateColumn HeaderText="子菜单">
   <ItemTemplate>
    <%# ActorClassManage.hasLeaf(DataBinder.Eval(Container.DataItem,"ActorClassID").ToString(),DataBinder.Eval(Container.DataItem,"child").ToString())%>
   </ItemTemplate>
  </asp:TemplateColumn>
  public static string hasLeaf(string id,string child)
  {
   string lRtn = "";
   if (Int32.Parse(child) > 0)
    lRtn="<a href='Actorclassmanage.aspx?classID="+id+"'><font color=blue>子菜单(" + child + ")</font></a>";
   else
    lRtn = "无子菜单";

   return lRtn;
  }
  <asp:TemplateColumn HeaderText="属性">
   <ItemTemplate>
    <asp:LinkButton Text='<%# IsHidden(DataBinder.Eval(Container.DataItem,"ActorClassID").ToString(),(bool)DataBinder.Eval(Container.DataItem,"Enabled")) %>' runat="server" CommandName="hidden" ID="Linkbutton1"></asp:LinkButton>
   </ItemTemplate>
  </asp:TemplateColumn>
  public static string IsHidden(string id,bool enabled)
  {
   string lRtn = "";
   if (enabled == true)
   {
    lRtn = "[显示]";
   }
   else
   {
    lRtn = "隐藏";
   }
   return lRtn;
  }
  public static void Sort(string actorclassID, string orderID)
  {
   string temp = "";
   if (Int32.Parse(BgPicManage.GetMaxCode("actorclass","orderID")) == Int32.Parse(orderID))
   {
    temp += "<ipnut type='submit' value='向下移'>";
   }
   if (Int32.Parse(orderID) == 0)
   {
    temp += "<ipnut type='submit' value='向上移'>";
   }
  }
  
 12. DataGrid 控件自定义分页代码
 
  将下列代码放于包含<DataGrid>的form中去,
  <p style="FONT-SIZE:9pt" align="center">
          <asp:label id="lblPageCount" runat="server"></asp:label>
          <asp:label id="lblCurrentIndex" runat="server"></asp:label>
          <asp:linkbutton id="btnFirst" onclick="PagerButtonClick" runat="server" Font-Name="verdana"
           Font-size="8pt" ForeColor="navy" CommandArgument="0"></asp:linkbutton>
          <asp:linkbutton id="btnPrev" onclick="PagerButtonClick" runat="server" Font-Name="verdana"
           Font-size="8pt" ForeColor="navy" CommandArgument="prev"></asp:linkbutton>
          <asp:linkbutton id="btnNext" onclick="PagerButtonClick" runat="server" Font-Name="verdana"
           Font-size="8pt" ForeColor="navy" CommandArgument="next"></asp:linkbutton>
          <asp:linkbutton id="btnLast" onclick="PagerButtonClick" runat="server" Font-Name="verdana"
           Font-size="8pt" ForeColor="navy" CommandArgument="last"></asp:linkbutton>
        </p>
       
        后台代码
       
        private void Page_Load(object sender, System.EventArgs e)
        {
          // 在此处放置用户代码以初始化页面
          btnFirst.Text = "最首页";
          btnPrev.Text = "前一页";
          btnNext.Text = "下一页";
          btnLast.Text = "最后页";
          //绑定数据源
          if (!Page.IsPostBack)
          {
           OpenDatabase();
           BindGrid();
          }
        }
       
        //用于显示"第几页,总*页"
        private void ShowStats()
  {
    lblCurrentIndex.Text = "第 " + (MyDataGrid.CurrentPageIndex + 1).ToString() + " 页";
    lblPageCount.Text = "总共 " + MyDataGrid.PageCount.ToString() + " 页";
  }
  
  //响应分页按钮
  public void PagerButtonClick(object sender, EventArgs e)
        {
         string arg = ((LinkButton)sender).CommandArgument.ToString();
          switch(arg)
          {
            case "next":
              if (MyDataGrid.CurrentPageIndex < (MyDataGrid.PageCount - 1))
              {
               MyDataGrid.CurrentPageIndex += 1;
              }
              break;
            case "prev":
              if (MyDataGrid.CurrentPageIndex > 0)
              {
               MyDataGrid.CurrentPageIndex -= 1;
              }
              break;
            case "last":
              MyDataGrid.CurrentPageIndex = (MyDataGrid.PageCount - 1);
              break;
            default:
              MyDataGrid.CurrentPageIndex = System.Convert.ToInt32(arg);
              break;
          }
          BindGrid();
          ShowStats();
        }

 


 

posted on 2006-05-30 09:31  公木子  阅读(462)  评论(0编辑  收藏  举报