本文介绍了网格视图复选框删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过使用外部按钮选中gridview上的复选框来删除网格视图行:
在网格视图"中,我有4行,我选中了两行chekbox,而其他块仍在执行并打印Hello 4次.
I want to delete grid view row by checking a checkbox on gridview by a external button:
In Grid View I have 4 Rows I checked two rows chekbox and still else block is executing and printing Hello 4 Times.
int i;
for (i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
if (cb.Checked)
{
string x = "Delete from Persons where LastName='" + GridView1.Rows[i].Cells[0].Text + "'";
SqlCommand cmd = new SqlCommand(x, con);
cmd.ExecuteNonQuery();
}
else
{
Response.Write("hello<br>");
}
}
GridView代码:
GridView Code:
<asp:GridView ID="GridView1" runat="server" Height="44px" Width="292px">
<Columns>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
请帮助!!!
Please Help !!!
推荐答案
foreach(GridViewRow row in GridView1.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
CheckBox cb = row.FindControl("CheckBox1") as CheckBox;
if (cb.Checked)
{
string x = "Delete from Persons where LastName='" + GridView1.Rows[i].Cells[0].Text + "'";
SqlCommand cmd = new SqlCommand(x, con);
cmd.ExecuteNonQuery();
}
else
{
Response.Write("hello<br>");
}
}
}
--Amit
--Amit
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("server=Harshit-PC; database=Temp; uid=sa;pwd=india");
con.Open();
if (Page.IsPostBack == false)
{
string x = "select * from cus";
da = new SqlDataAdapter(x, con);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
谢谢大家..............
Thanks EveryOne........
unchecked
checked
unchecked
checked
unchecked
checked
protected void btn1_Click(object sender, EventArgs e)
{
int i;
for (i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
if (cb.Checked)
{
//string x = "Delete from Persons where LastName='" + GridView1.Rows[i].Cells[0].Text + "'";
//SqlCommand cmd = new SqlCommand(x, con);
//cmd.ExecuteNonQuery();
Response.Write("checked<br>");
}
else
{
Response.Write("unchecked<br>");
}
}
}</br></br>
在gridview中加载了6条记录,我检查了它的替代行.因此,无论何时打印选中,都应删除该记录.删除操作后重新绑定gridview以查看结果.
there are 6 records loaded in the gridview and I checked its alternative rows. hence whenever it prints checked it should delete the record. rebind the gridview after the delete operation to see it result.
这篇关于网格视图复选框删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!