这似乎是一个重复的问题,但我无法得到答案。
我有一个网格视图,当我点击gridview外面的按钮时,我需要删除一个特定的行。
protected void btnDelete_Click(object sender, EventArgs e)
{
dtable = (DataTable)Session["data"];
DataRow row = dtable.Rows[DataGV1.SelectedIndex];
dtable.Rows.Remove(row);
DataGV1.DataSource = dtable;
DataGV1.DataBind();
Session["data"] = dtable;
}
会话变量具有以前的数据表状态。
protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index
_selectedIndex = int.Parse(e.CommandArgument.ToString());
}
Gridview控件
onselectedindexchanged="DataGV1_SelectedIndexChanged"
OnRowCommand="DataGV1_RowCommand" OnRowDeleting="DataGV1_RowDeleting"
AutoGenerateSelectButton="False" DataKeyNames="Role,Last_name">
<Columns>
<asp:ButtonField DataTextField="last_name" HeaderText="Last_name" CommandName="SingleClick"
SortExpression="last_name" Text="Button" />
<asp:BoundField DataField="role" HeaderText="role" SortExpression="role" />
<asp:BoundField DataField="role" HeaderText="role" HeaderText="Frist_name"
SortExpression="first_name" Text="First_name" />
</Columns>
</asp:GridView>
这似乎不起作用。 你可以告诉我哪里出错了吗?
答案 0 :(得分:0)
您必须将_selectedIndex存储在ViewState中,然后在删除按钮上单击从Viewstate中检索_selectedIndex并使用它从数据集中删除该行,然后重新加载网格。
protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index
ViewState["SelIndex"] = e.CommandArgument.ToString();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if(ViewState["SelIndex"] == null)
return;
int selIndex = int.Parse(ViewState["SelIndex"]);
dtable = (DataTable)Session["data"];
DataRow row = dtable.Rows[selIndex ];
dtable.Rows.Remove(row);
DataGV1.DataSource = dtable;
DataGV1.DataBind();
Session["data"] = dtable;
}
答案 1 :(得分:0)
如果按钮在GridView
之外,则无需处理RowCommand
事件(实际上这是不合适的)。
建议:
您必须添加TemplateField
列,将CheckBox控件放在TemplateField的ItemTemplate中,然后在按钮的单击处理程序中编写代码以遍历GridView.Rows
集合,通过读取{的值来标识所选行{1}}如果选中CheckBox
,则控制并执行删除操作。
演示数据源(CheckBox
)
List<T>
标记:
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public static List<Item> Data()
{
List<Item> list = new List<Item>()
{
new Item(){ ID=11, Name="A"},
new Item(){ ID=12, Name="B"},
new Item(){ ID=13, Name="C"},
new Item(){ ID=14, Name="D"},
new Item(){ ID=15, Name="E"},
};
return list;
}
}
代码隐藏(Page_Load)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:ButtonField DataTextField="Name" HeaderText="Name" CommandName="SingleClick"
SortExpression="last_name" Text="Button" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Button" />
答案 2 :(得分:0)
看看这些可以解释从gridview中删除单个/多个行的文章。 http://technico.qnownow.com/2012/06/15/how-to-delete-multiple-rows-from-gridview-with-checkboxes/ http://technico.qnownow.com/2012/06/14/how-to-delete-a-row-from-gridview-with-client-side-confirmation/