简体   繁体   English

将按钮放在gridview中的最后一列

[英]Place button as LAST column in gridview

I have a grid view and I add columns to it by code: 我有一个网格视图,我通过代码添加列:

//Retrieve "Table" from database
gridOffers.DataSource = table;
gridOffers.DataBind();

The columns added by code are being added AFTER the button, which is not what I need: 按代码添加的列是在按钮之后添加的,这不是我需要的: 在此输入图像描述 How do I make sure the Add To Cart button the very last thing? 如何确保添加到购物车按钮最后一件事?

Source of gridView: gridView的来源:

<Columns>
             <asp:ImageField DataImageUrlField="ImageUrl" ControlStyle-Width="100"
                ControlStyle-Height = "100" HeaderText = "Preview Image"  
                 ItemStyle-HorizontalAlign="Center">
<ControlStyle Height="100px" Width="100px"></ControlStyle>

<ItemStyle HorizontalAlign="Center"></ItemStyle>
             </asp:ImageField>
             <asp:TemplateField ShowHeader="False">
                 <ItemTemplate>
                     <asp:Button ID="Button1" runat="server" CausesValidation="false" 
                         CommandName="btnAddToCart" Text="Add To Cart" />
                 </ItemTemplate>
             </asp:TemplateField>
        </Columns>

You're defining columns in the GridView source AND by databinding a data source to the GridView. 您正在通过将数据源数据绑定到GridView来定义GridView源中的列。 Therefore you have two sources of columns; 因此,您有两个列来源; there may or may not be a guaranteed order in which columns are added to the GridView. 可能有也可能没有保证的顺序,其中列被添加到GridView。

Instead, why not set AutoGenerateColumns for the GridView to False and then explicitly specify the column order by using BoundField for each field you want from the data source in your GridView source followed by your image and button columns? 相反,为什么不将GridView的AutoGenerateColumns设置为False ,然后使用BoundField为GridView源中的数据源所需的每个字段显示指定列顺序,然后是图像和按钮列?

I don't know if there's a less hacky way, but you could use RowDataBound to change the order, so that the AutoGenerated columns are followed by your other columns: 我不知道是否有更少的hacky方式,但您可以使用RowDataBound来更改顺序,以便AutoGenerated列跟随您的其他列:

protected void gridOffers_RowDataBound(object sender, GridViewRowEventArgs e)
{
    TableCell cell = e.Row.Cells[0];
    e.Row.Cells.RemoveAt(0);
    //Move first to the end
    e.Row.Cells.Add(cell);
    cell = e.Row.Cells[0];
    e.Row.Cells.RemoveAt(0);
    //Move second to the end
    e.Row.Cells.Add(cell);
}

Do you have AutoGenerateColumns set to true on the Gridview? 您是否在Gridview上将AutoGenerateColumns设置为true? If so set this to false and manually set the fields in the grid using asp:BoundField setting the DataField to the name of the field from the datasource. 如果是这样,则将其设置为false并使用asp:BoundField手动设置网格中的字段将DataField设置为数据源中字段的名称。

This way you can set the exact order of your columns. 这样您就可以设置列的确切顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM