[英]Delete Row From Gridview with CommandName
我正在嘗試使用CommandName
從我的Gridview
刪除行,但它不起作用。 我正在使用 get RowIndex
來做到這一點。
我沒有收到任何錯誤,當我單擊ImageButton
時它什么也沒做。
這是我的代碼:
<asp:GridView ID="GridView1" runat="server" Width="538px" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" onselectedindexchanged="DropDownList5_SelectedIndexChanged" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt" Font-Size="Small" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" Height="16px" ImageUrl="~/images/delete.png" Width="16px" CommandName="DeleteRow" />
</ItemTemplate>
<HeaderStyle Width="30px" />
<ItemStyle Height="10px" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
這是cs代碼:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (Page.IsPostBack)
{
if (e.CommandName.Equals("DeleteRow"))
{
GridViewRow oItem = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int RowIndex = oItem.RowIndex;
GridView1.DeleteRow(RowIndex);
DataBind();
}
}
}
試試這個
而不是做你所做的,我會建議你從數據庫中刪除並再次綁定 GridView
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("DeleteRow"))
{
GridViewRow oItem = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int RowIndex = oItem.RowIndex;
girdivewBind(); // Bind your gridview again.
}
}
public void deleteRecord(string ID)
{
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "delete from Mytable where ID=@id";
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", ID);
con.Open();
var temp = cmd.ExecuteNonQuery();
con.Close();
}
}
}
試試這個:
網格視圖:
<ItemTemplate>
<asp:ImageButton CommandName="DeleteProduct" ID="ImageButton1" runat="server" CausesValidation="false" " ImageUrl="~/Admin/Images/SendToShop.png"/>
</ItemTemplate>
C#
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteProduct")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = grdCart.Rows[index];
int productId = int.Parse(((Label)GridView1.Rows[row.RowIndex].FindControl("lbProdId")).Text);
DeleteProduct(productId);
}
}
private void DeleteProduct (int productID)
{
//delete the product
}
如果您還想從數據庫中刪除該行並在頁面上反映更改,請使用GridViewID_RowCommand
aspx
<asp:GridView ID="GridView1" runat="server"
onselectedindexchanged="DropDownList5_SelectedIndexChanged"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server"
Height="16px" ImageUrl="~/images/delete.png"
CommandName="DeleteRow" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
string id = selectedRow.Cells[0].Text; //assuming your ID is the first column of your grid
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString); //assuming your connection string is in web.config
con.Open();
SqlCommand sq = new SqlCommand("DELETE FROM myTable where id='" + id + "'", con);
sq.ExecuteNonQuery();
con.Close();
}
}
如果您不記得ID
的列索引,您仍然可以通過Grid Header
的名稱獲取ID
值,請遵循此答案
在您的頁面加載中
protected void Page_Load(object sender, EventArgs e)
{
if(this.IsPostBack)
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString);
con.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT * FROM myTable",con);
SqlDataReader reader = sqlCommand.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
con.Close();
}
}
編輯:網格不應該綁定在PostBack
,我建議不要這樣做。 更新不在Page_Load
的 gridview ,而是將GridView
包裝在UpdatePanel
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gv1" ...> ... </asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
然后在您需要更新網格的任何地方調用UpdatePanel2.Update()
(在這種情況下,您需要在修改其源的地方Bind
網格,即RowCommand
並在綁定之后調用UpdatePanel2.Update()
)
請記住,無論您做什么,都無法停止PostBack
因為單擊是在按鈕上。
我在運行時在 Gridview 中完成了行刪除,而沒有刪除數據表中的記錄。 請在下面找到代碼。
我的網格視圖
<asp:GridView ID="grdAddEditDefectParameterDetails" runat="server" OnRowDataBound="grdAddEditDefectParameterDetails_RowDataBound" OnRowDeleting="grdAddEditDefectParameterDetails_RowDeleting" >
<Columns>
<asp:BoundField DataField="DEFECT_PARAM_CODE" HeaderStyle-CssClass="headTb4" Visible="false"
HeaderText="Defect No.">
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:TemplateField HeaderStyle-CssClass="headTb4" HeaderStyle-Width="5%" HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="ChkStatus" runat="server" AutoPostBack="true" DataTextField="ACTIVE"
onclick="javascript:return OnChange(this);" />
<asp:HiddenField ID="idDefectParam" runat="server" Value='<%# Eval("DEFECT_PARAM_CODE") %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="5%" />
</asp:TemplateField>
<asp:BoundField DataField="DEFECT_PARAM_DESCRIPTION" ItemStyle-Width="44%" HeaderStyle-CssClass="headTb4"
HeaderText="Defect Parameter Description" HtmlEncode="false">
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:TemplateField HeaderText="Penalty Applicable" HeaderStyle-Width="7%" HeaderStyle-CssClass="headTb4">
<ItemTemplate>
<asp:CheckBox ID="ChkPenalty" Enabled="false" runat="server" DataTextField="PENALTY_APPLICABLE"></asp:CheckBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="7%" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="headTb4" HeaderText="Defect Weightage" HeaderStyle-Width="7%">
<ItemTemplate>
<asp:TextBox ID="txtAddDefectWeightage" runat="server" CssClass="inputSmallGrid"
MaxLength="6" onkeypress="javascript:return isNumericKey(event);" Text="0.00"
AutoCompleteType="Disabled"></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="7%" />
</asp:TemplateField>
</Columns>
在您的 .cs 文件中添加以下功能
protected void grdAddEditDefectParameterDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
之后,使用以下代碼刪除該行
grdAddEditDefectParameterDetails.DeleteRow(grdAddEditDefectParameterDetails.Rows[i].RowIndex);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.