2011-01-22 58 views
7

我有一个网格视图。它有两个绑定列。我需要有一个序列号列作为第一列。要添加序列号作为GridView中的第一列

我该怎么做? 在前提前感谢

+0

如何从数据计算的序列号添加此代码? – 2011-01-22 09:08:43

+0

谢谢彼得。序列号不是从数据计算的。它只需要从1开始以1递增。 – Ananth 2011-01-22 09:11:23

回答

3

创建数据表有两列使用第一列的自动增量为真的和AutoIncrementStep = 1像

DataTable _test = new DataTable(); 
DataColumn c = new DataColumn("sno", typeof(int)); 
c.AutoIncrement = true; 
c.AutoIncrementSeed = 1; 
c.AutoIncrementStep = 1; 
_test.Columns.Add(c); 
_test.Columns.Add("description"); 
gvlisting.DataSource = _test; 
0

使用行索引绑定字段或行数据绑定您可以添加一个模板列,您可以使用该行的索引。

17
<asp:TemplateField HeaderText="S No"> 
       <ItemTemplate> 
        <%# Container.DataItemIndex + 1 %> 
       </ItemTemplate> 
       <ItemStyle Width="2%" /> 
      </asp:TemplateField> 
3

这更多的是一种辅助答案OP的原始问题。我有一个可怕的时间,弄清楚如何获得由R.Ilayaraja的答案创建的行的索引号(在OP中的序列号)(其工作很好)。

在页面背后的代码,如果你想获得该行的索引号,你可以用类似的代码如下:
Int32 idNumber = Convert.ToInt32(gvlisting.Rows[i].DataItemIndex.ToString()) + 1;

这是假设你正在使用的迭代器“我”来获得其他值从你的行,并且你需要添加一个数字,因为索引是序数(索引0是第一行)。如果你没有使用迭代器,只需要使用.Rows[0]

作为一个ASP.NET的金块,我努力解决这个问题,所以我想我会发布这个,希望它能帮助像我这样的其他noob。

2

添加一个名为Ser的列,并将其设置为ReadOnly=false

然后将此代码添加到您的应用程序:

if (GridSearch.Rows.Count > 1) 
{ 
    for (int i = 0; i < GridSearch.Rows.Count-1; i++) 
    { 
     GridSearch.Rows[i].Cells[0].Value = (i + 1).ToString(); 
    } 

}

2

就在GridView控件

<asp:TemplateField HeaderText="Serial No of Users"> 
       <ItemTemplate> 
        <%# ((GridViewRow)Container).RowIndex + 1%> 
       </ItemTemplate> 
       <FooterTemplate> 
        <asp:Label ID="lbltotalall" runat="server" /> 
       </FooterTemplate> 
      </asp:TemplateField> 
1
<asp:TemplateField HeaderText="SR No"> 
       <ItemTemplate> 
        <%# Container.DataItemIndex + 1 %> 
       </ItemTemplate> 
       <ItemStyle Width="5%" /> 
</asp:TemplateField>