2011-08-02 61 views
8

这是我的GridView:如何在GridView自动生成列后插入一列 - ASP.NET

<asp:GridView ID="gridview" runat="server" AutoGenerateColumns="true"> 
    <Columns> 
     <asp:TemplateField HeaderText="TestColumn"> 
      <ItemTemplate> 
       <asp:LinkButton ID="lkbtn" runat="server" Text="Edit" 
        CommandName="Update" CausesValidation="False" ToolTip="Edit" /> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

TestColumn最终是第一列,但我想在汽车后,生成的。

+0

你可以使用jQuery来更改列的位置? – Sami

回答

0

您将AutoGenerateColumnProperty设置为false,然后根据需要对列进行排序。

如果你只是想添加一个编辑按钮,你应该使用:

<asp:CommandField ShowEditButton="True" /> 

下面是一个例子使用Northwind数据库

<asp:GridView ID="GridView1" runat="server" 
AutoGenerateColumns="False" 
DataKeyNames="ProductID" 
DataSourceID="SqlDataSource1"> 
<Columns> 
<asp:BoundField DataField="ProductID" HeaderText="ProductID" 
InsertVisible="False" ReadOnly="True" SortExpression="ProductID" /> 
<asp:BoundField DataField="ProductName" HeaderText="ProductName"/> 
<asp:BoundField DataField="SupplierID" HeaderText="SupplierID" /> 
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID"/> 
<asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit"/> 
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" /> 
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" /> 
<asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" /> 
<asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel" /> 
<asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued"/> 
<asp:CommandField ShowEditButton="True" /> 
</Columns> 
</asp:GridView> 
+0

OP明确指出他/她希望列自动生成。使用你的方式将会发挥自动生成列的优势。 – P5Coder

+0

我的错误。我太快读了这个问题。 – alexandrekow

0

恐怕也不太可能。阅读MS documentation

您还可以 自动生成的列字段结合显式声明的列字段。当两者都使用时,首先显式声明 声明的列字段,然后是 自动生成的列字段。自动生成的界限 列字段不会添加到Columns集合中。

1

RowDataBound事件处理程序,你可以从第一列的TemplateField细胞移动到该行的末尾:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    TableCell cell = e.Row.Cells[0]; 
    e.Row.Cells.RemoveAt(0); 
    e.Row.Cells.Add(cell); 
} 
相关问题