2011-08-02 32 views
8

Đây là GridView của tôi:Làm thế nào để chèn một cột trong một GridView sau khi tự động tạo ra các cột - 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> 

Các TestColumn kết thúc lên được cột đầu tiên, nhưng tôi muốn nó sau khi tự động tạo ra.

+0

bạn có thể sử dụng jQuery để thay đổi vị trí các cột? – Sami

Trả lời

0

Bạn đặt AutoGenerateColumnProperty thành false và sau đó bạn đặt hàng các cột theo ý muốn.

Nếu bạn chỉ muốn thêm một nút chỉnh sửa, bạn nên sử dụng:

<asp:CommandField ShowEditButton="True" /> 

Dưới đây là một ví dụ bằng cách sử dụng cơ sở dữ liệu 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 xác định rõ ràng rằng anh/cô ấy muốn các cột được tạo tự động. Sử dụng theo cách của bạn sẽ đưa ra lợi thế của các cột tạo tự động. – P5Coder

+0

Sai lầm của tôi. Tôi đọc câu hỏi quá nhanh. – alexandrekow

0

tôi sợ nó có thể không thực hiện được. Đọc MS documentation:

Bạn cũng có thể kết hợp các lĩnh vực cột khai báo rõ ràng với lĩnh vực cột tự động tạo ra. Khi cả hai được sử dụng, rõ ràng là các trường cột được khai báo được hiển thị trước, sau đó là các trường cột được tạo tự động . Các trường cột được tạo tự động không được thêm vào bộ sưu tập Cột.

1

Trong xử lý sự kiện RowDataBound, bạn có thể di chuyển các tế bào TemplateField từ cột đầu tiên đến cuối dòng:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    TableCell cell = e.Row.Cells[0]; 
    e.Row.Cells.RemoveAt(0); 
    e.Row.Cells.Add(cell); 
} 
Các vấn đề liên quan