漫漫技术人生路

C#

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
给DataGrid添加Number列的简单方法
<asp:TemplateColumn HeaderText="No.">
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    <ItemTemplate>
        <asp:Label runat="server" Text='<%# dgCustomize.CurrentPageIndex*dgCustomize.PageSize+dgCustomize.Items.Count+1 %>'>
        </asp:Label>
    </ItemTemplate>
</asp:TemplateColumn>
实际上CurrentPageIndex是从0开始的,所以在第一爷的时候CurrentPageIndex*PageSize总是0
 datagrid.Items.Count也是从0 开始的,所以第一条记录的index 是0,这也说明了在编辑时当editIndexItem=-1时就处于不可编辑状态,而不是0
此外执行以下代码
protected void grid_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        if (e.CommandName == "bt1")
        {
           Response.Write( e.Item.ID);
        }
    }
结果对于没有数据绑定列而是统计行的那行对应的e.CommandName == "bt1")将会显示行号
 #region  Summary Rows in DataGrid Controls  very good
    /// <summary>
    /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndive/html/data01102002.asp
    /// </summary>
    /// <returns></returns>
    private DataSet PhysicalDataRead()
    {
        string strCnn = "SERVER=localhost;DATABASE=northwind;Integrated Security=SSPI;";
        SqlConnection conn = new SqlConnection(strCnn);
        // Command text using WITH ROLLUP
        StringBuilder sb = new StringBuilder("");
        sb.Append("SELECT ");
        sb.Append("  CASE GROUPING(o.customerid) WHEN 0 ");
        sb.Append("    THEN o.customerid ELSE '(Total)' END AS MyCustID, ");
        sb.Append("  CASE GROUPING(od.orderid) WHEN 0 ");
        sb.Append("    THEN od.orderid ELSE -1 END AS MyOrderID, ");
        sb.Append("  SUM(od.quantity*od.unitprice) AS price ");
        sb.Append("FROM Orders o, [Order Details] od ");
        sb.Append("WHERE Year(orderdate)=@nYear AND od.orderid=o.orderid ");
        sb.Append("GROUP BY o.customerid, od.orderid WITH ROLLUP ");
        sb.Append("ORDER BY o.customerid, price");
        String strCmd = sb.ToString();
        sb = null;
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = strCmd;
        cmd.Connection = conn;
        SqlDataAdapter da = new SqlDataAdapter(strCmd, strCnn);
        da.SelectCommand = cmd;
        // Set the "year" parameter
        SqlParameter p1 = new SqlParameter("@nYear", SqlDbType.Int);
        p1.Direction = ParameterDirection.Input;
        p1.Value = Convert.ToInt32(txtYear.Text);
        cmd.Parameters.Add(p1);
        DataSet ds = new DataSet();
        da.Fill(ds, "Orders");
        return ds;
    }
    /// <summary>
    /// //e.Item.Cells.RemoveAt(0);      // remove CustID
    //e.Item.Cells.RemoveAt(0);      // remove Order #, now the first
    //           利用语句e.Item.ItemType = ListItemType.Header来找到DataGrid的Header;
    //2、 清除Header中的缺省控件;
    //     e.Item.Controls.Clear();

    //// Span and right-align the cell left
    //e.Item.Cells[0].ColumnSpan = 3;
    //e.Item.Cells[0].HorizontalAlign = HorizontalAlign.Right;
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void ItemCreated(Object sender, DataGridItemEventArgs e)
{
      
        //foreach(DataGridItem e in grid.Items)
        //{
   // Get the type of the newly created item
   ListItemType itemType = e.Item.ItemType;
   if (itemType == ListItemType.Item ||itemType == ListItemType.AlternatingItem)
   {
       try
       {
           // Get the data bound to the current row
           DataRowView drv = (DataRowView)e.Item.DataItem;
           if (drv != null)
           {
               // Check here the app-specific way to detect whether the
               // current row is a summary row
           }
           if ((int)drv["MyOrderID"] == -1)
           {
               // Modify style and layout here.
               e.Item.BackColor = Color.White;
               e.Item.Font.Bold = true;
               e.Item.Cells.RemoveAt(1);         // remove the order # cell
               e.Item.Cells[0].ColumnSpan = 2;      // span the custID cell
               e.Item.Cells[1].HorizontalAlign = HorizontalAlign.Right;
               e.Item.Cells[0].Text = "Total is";
               e.Item.Cells[0].Attributes["onmouseover"] = "javascript:this.style.backgroundcolor='#aaaadd';";
           }
       }
       catch
       {
       }
   }
   //}
}
    /// <summary>
    ///
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    //public void ItemDataBound(Object sender,DataGridItemEventArgs e)
    //{
    //    //foreach (DataGridItem e in grid.Items)
    //    //{
    //        DataRowView drv = (DataRowView)e.Item.DataItem;
    //        if (drv == null)
    //            return;
    //        if ((int)drv["MyOrderID"] == -1)
    //        {
    //            if (drv["MyCustomerID"].ToString() == "(Total)")
    //            {
    //                e.Item.BackColor = Color.Yellow;
    //                e.Item.Cells[0].Text = "Orders total";
    //            }
    //            else
    //                e.Item.Cells[0].Text = "Customer subtotal";
    //        }
    //    //}
    //}
    protected void grid_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        DataRowView drv = (DataRowView)e.Item.DataItem;
        if (drv == null)
            return;
        if ((int)drv["MyOrderID"] == -1)
        {
            if (drv["MyCustID"].ToString() == "(Total)")
            {
                e.Item.BackColor = Color.Yellow;
                e.Item.Cells[0].Text = "Orders total";
                e.Item.Cells[0].Attributes["onmouseover"] = "javascript:this.style.backgroundcolor='#aaaadd';";
               
            }
            else
                e.Item.Cells[0].Text = "Customer subtotal";
        }
    }
    protected void PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
    }
    #endregion
  <asp:DataGrid id="grid" runat="server"  style ="table-layout:fixed"
   AutoGenerateColumns="False"
   AllowPaging="True" PageSize="15"
   Font-Size="XX-Small" CellPadding="4"
   BorderStyle="Solid" BorderColor="SkyBlue" BorderWidth="1px"
   OnItemCreated="ItemCreated"
   OnPageIndexChanged="PageIndexChanged" OnItemDataBound="grid_ItemDataBound" OnItemCommand="grid_ItemCommand">
  
   <headerstyle backcolor="SkyBlue" font-size="9pt" font-bold="True" />
   <itemstyle backcolor="#EEEEEE" />
   <pagerstyle backcolor="SkyBlue" Font-Names="webbings"
font-size="10pt" PrevPageText="3" NextPageText="4" />
  
   <Columns>
     <asp:BoundColumn DataField="MyCustId" HeaderText="Customer" >
         <%--<ItemStyle Width="50px" />--%>
     </asp:BoundColumn>
        <asp:BoundColumn DataField="MyOrderId" HeaderText="Order #" >
           <%-- <ItemStyle Width="50px" />--%>
        </asp:BoundColumn>
     <asp:BoundColumn DataField="price" HeaderText="Amount"
DataFormatString="{0:c}">
     <%-- <itemstyle horizontalalign="Right" Width="50px" />--%>
      </asp:BoundColumn>
       <asp:TemplateColumn HeaderText="取行号">
           <ItemTemplate>
               <asp:Button ID="Button1" runat="server" CommandName="bt1" Text="取行号" />
           </ItemTemplate>
       </asp:TemplateColumn>
      
       <asp:TemplateColumn HeaderText="No.">
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# grid.Items.Count+1 %>'>
        </asp:Label>
    </ItemTemplate>
</asp:TemplateColumn>
   </Columns>
</asp:DataGrid>
posted on 2006-09-22 09:33  javaca88  阅读(267)  评论(0编辑  收藏  举报