[英]Asp.Net C# Delete row from dataTable gridview on button click
[英]Delete Row From asp GridView and From Datatable
我有與數據表綁定的asp gridview。 僅一個復選框復選框模板與源數據表列( sel
)綁定。
這是標記示例:
<asp:GridView ID="testGrid"
CssClass="ObjSelection"
AutoGenerateColumns="false"
OnRowDataBound="testGrid_RowDataBound"
runat="server">
<Columns>
<asp:TemplateField HeaderText=" ">
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" Enabled="true" AutoPostBack="true" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox AutoPostBack="true" ID="chkRow" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "sel")%>' OnCheckedChanged="ChkRow_OnCheckChange" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
如您所見,我沒有使用RowCommand刪除行。 我在單獨的div
有一個工具欄,其中顯示刪除按鈕。
您能指導我如何在另一個div
中存在的單擊按鈕時both from DataSource and GridView
刪除一行嗎?
使用以下代碼從ViewState或Session中的數據表中刪除所選行,並分配數據源
Aslo將數據鍵分配給GridView
<asp:GridView ID="testGrid" DataKeyNames="PrimaryKey"
CssClass="ObjSelection"
AutoGenerateColumns="false"
OnRowDataBound="testGrid_RowDataBound"
runat="server">
背后的代碼:
protected void btnRemove(object sender, EventArgs e)
{
// Check session exists
if (Session["Key"] != null)
{
// Opening / Retreiving DataTable.
DataTable dt = (DataTable)Session["Key"];
foreach (GridViewRow row in testGrid.Rows)
{
CheckBox chkRow= row.Cells[0].FindControl("chkRow") as CheckBox;
if (chkRow!= null && chkRow.Checked)
{
int Id = Convert.ToInt32(testGrid.DataKeys[row.RowIndex].Value);
DataRow[] drs = dt.Select("PrimaryKey = '" + Id + "'"); // replace with your criteria as appropriate
if (drs.Length > 0)
{
dt .Rows.Remove(drs[0]);
}
}
}
Session["Key"] = dt ;
testGrid.DataSource = dt ;
testGrid.DataBind();
}
}
您可以使用隱藏字段通過javascript和jQuery放置行ID
<asp:HiddenField runat="server" ID="IDField"/>
jQuery的
<script>
$(document).ready(function(){
$("#testGrid tr").click(function(){
$("#IDField").val($(this).children("td.IDColumn").text());
$(this).Index(); // will give you row index
});
});
</script>
點擊刪除按鈕
protected void delete_Click(object sender,EventArg e)
{
//delete from datasource use this.IDField.Value
//to refresh data in grid
this.testGrid.DataSource = dataTable;
this.testGrid.DataBind();
}
gridview_RowDataBound(Sender sender,eventArgs e)
{
CheckBox lblChkRow = (CheckBox)e.Row.FindControl("IDField");
if(lblChkRow.Checked)
{
// Delete Value here and bind with datasource
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.