我有一个包含数据库数据的gridview。我为每一行动态创建了复选框。我想要的是当我点击"删除所选的"按钮,将删除选中的复选框。但是当我点击按钮时,行不会被删除。这是按钮的代码:
protected void btnDeleteSelectedServiceProvidersLocations_Click(object sender, EventArgs e)
{
int x = 102;
string delete;
foreach (GridViewRow grow in gvServiceProviders.Rows)
{
delete = Request.Form["gvServiceProviders$ct" + x + "$cbSelect"];
if (delete != null || delete == "on" || delete == "y")
{
bll.ServiceProviderLocationID = grow.Cells[1].Text;
bll.IsDeleted = "y";
bll.ServiceProviderLocationDelete();
}
x++;
}
gvServiceProviders.DataSource = bll.GetServiceProviderLocations();
gvServiceProviders.DataBind();
}
gridview位于更新面板内,如果有帮助的话。我使用的是三层方法。
ASPX代码:
<div ID="gridView">
<asp:GridView ID="gvServiceProviders" runat="server">
<Columns>
<asp:templatefield HeaderText="Select">
<itemtemplate>
<asp:CheckBox ID="cbSelect" runat="server"/>
</itemtemplate>
</asp:templatefield>
</Columns>
</asp:GridView>
</div>
答案 0 :(得分:2)
如果选中该复选框,则要删除数据,然后执行以下操作,
foreach (GridViewRow grow in gvServiceProviders.Rows)
{
//Make sure it is datarow
if(grow.RowType = RowType.DataControlRowType.DataRow)
{
//Finiding checkbox control in gridview for particular row
CheckBox chkdelete = (CheckBox)grow.FindControl("cbSelect");
//Make sure if checkbox is selected for the processing row
if(chkdelete.Checked)
{
//Getting your datakey value
bll.ServiceProviderLocationID = Convert.ToInt32(gvServiceProviders.DataKeys[grow.RowIndex].Value);
bll.IsDeleted = "y";
bll.ServiceProviderLocationDelete();
}
}
}
gvServiceProviders.DataSource = bll.GetServiceProviderLocations();
gvServiceProviders.DataBind();
由于这是使用gridview的datakey
,您需要使用LocationID设置gridview的DataKey
属性。
答案 1 :(得分:1)
Try this code:
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in gvDetails.Rows)
{
//Finiding checkbox control in gridview for particular row
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkSelect");
//Condition to check checkbox selected or not
if (chkdelete.Checked)
{
//Getting UserId of particular row using datakey value
int usrid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value);
using (SqlConnection con = new SqlConnection("Data Source=Test;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("delete from UserDetails where UserId=" + usrid, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}