2

我正在添加列grid-view dynamically

DataTable dt1 = new DataTable();
dt1.Columns.Add("Item Title", typeof(string));
dt1.Columns.Add("Unit Pack", typeof(string));
dt1.Columns.Add("Pack", typeof(string));
gv1.DataSource = dt1;
gv1.DataBind();

delete button automatically并添加

<asp:GridView ID="gv" runat="server">
    <Columns>
        <asp:CommandField ShowDeleteButton="true" />
    </Columns>
</asp:GridView>

它显示了gridview

| Delete | Item Title | Unit Pack | Pack |

现在我想在最后一列显示删除按钮

| Item Title | Unit Pack | Pack | Delete |

我怎样才能做到这一点?如何在最后一列创建删除按钮?

4

3 回答 3

3

您正在动态添加列,这就是您需要动态添加删除列的原因。或者您可以在 RowDataBound 中添加 linkBut​​ton:

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
    LinkButton lb = new LinkButton();
    lb.CommandArgument = e.Row.Cells[3].Text;
    lb.CommandName = "Delete";
    lb.Text = "Delete";

    e.Row.Cells[3].Controls.Add((Control)lb);
}
}

在 rowCommand 中,您可以编写删除代码:

protected void gv_RowCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
    case "delete":
//your code here
        break;
    default:
        break;
}
}
于 2013-05-14T12:14:02.190 回答
2

在gridview的RowCreated-event中,可以将CommandField推到右边:

protected void gv1_RowCreated(object sender, GridViewRowEventArgs e)
{
    GridViewRow row = e.Row;

    TableCell cell = row.Cells[0];
    row.Cells.Remove(cell);                
    row.Cells.Add(cell);
}

感谢这个博客

于 2013-05-14T13:08:31.173 回答
1
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="Item Title" HeaderText="Item Title" />
        <asp:BoundField DataField="Unit Pack" HeaderText="Unit Pack" />
        <asp:BoundField DataField="Pack" HeaderText="Pack" />
        <asp:CommandField ShowDeleteButton="true" />
    </Columns>
</asp:GridView>\

和代码背景是:

dt1.Columns.Add("Item Title", typeof(string));
dt1.Columns.Add("Unit Pack", typeof(string));
dt1.Columns.Add("Pack", typeof(string));
gv1.DataSource = dt1;
gv1.DataBind();

试试这个代码

于 2013-05-14T11:41:53.967 回答