在gridview的最后一列添加删除按钮

时间:2013-05-14 11:33:27

标签: asp.net gridview

我正在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>

它显示了像

的网格视图
| Delete | Item Title | Unit Pack | Pack |

现在我想在最后一栏显示删除按钮,如

| Item Title | Unit Pack | Pack | Delete |

我该怎么做?如何在最后一栏创建删除按钮?

3 个答案:

答案 0 :(得分: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;
}
}

答案 1 :(得分:2)

在gridview的RowCreated事件中,您可以将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);
}

感谢blog

答案 2 :(得分: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();

试试此代码