问题
I am adding columns on 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();
and add delete button automatically by
<asp:GridView ID="gv" runat="server">
<Columns>
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>
It shows the gridview like
| Delete | Item Title | Unit Pack | Pack |
Now i want to Show Delete button at the last column like
| Item Title | Unit Pack | Pack | Delete |
How can I do this? How to create delete button at last column?
回答1:
You are adding column dynamically thats why you need to add delete column dynamic. Or you can add linkButton in RowDataBound:
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);
}
}
in rowCommand you can write code for delete:
protected void gv_RowCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "delete":
//your code here
break;
default:
break;
}
}
回答2:
In the RowCreated-event of the gridview, you can push the CommandField to the right:
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);
}
Thanks to this blog
回答3:
<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>\
and code background is:
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();
Try this code
来源:https://stackoverflow.com/questions/16542092/add-delete-button-at-last-column-in-gridview