62,046
社区成员
发帖
与我相关
我的任务
分享
<asp:TemplateField HeaderText="选择">
<HeaderTemplate>
<input type="checkbox" onclick="fun(this)" />全选
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
<asp:HiddenField ID="hid1" runat="server" Value='<%#Bind("BookID")%>' />
</ItemTemplate>
</asp:TemplateField>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridivew();
}
}
private void BindGridivew()
{
BLL.GuestbookBLL guestbookbll = new GuestbookBLL();
if ((guestbookbll.GetAllList().Tables[0].Rows.Count) == 0 )
{
this.Label1.Text = "目前没有留言,或留言已经被清除。";
}
else
{
this.GridView1.DataSource = guestbookbll.GetAllList();
this.GridView1.DataBind();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//分页
this.GridView1.PageIndex = e.NewPageIndex;
this.BindGridivew();
}
protected void Button1_Click(object sender, EventArgs e)
{
//删除按钮
foreach (GridViewRow gr in GridView1.Rows)
{
CheckBox chk = (CheckBox)gr.FindControl("chk");
if (chk.Checked == true)
{
int gid = Convert.ToInt32(this.GridView1.DataKeys[gr.RowIndex].Value);
BLL.GuestbookBLL bll = new GuestbookBLL();
bll.Delete(gid);
}
BindGridivew();
}
}
private void BindGridivew()
{
BLL.GuestbookBLL guestbookbll = new GuestbookBLL();
var q=guestbookbll.GetAllList();
if ((q.Tables[0].Rows.Count) == 0 )
{
this.Label1.Text = "目前没有留言,或留言已经被清除。";
this.GridView1.DataSource =null; //加上这一两句就没问题了
this.GridView1.DataBind();
}
else
{
this.GridView1.DataSource =q;
this.GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//删除按钮
foreach (GridViewRow gr in GridView1.Rows)
{
CheckBox chk = (CheckBox)gr.FindControl("chk");
if (chk.Checked == true)
{
int gid = Convert.ToInt32(this.GridView1.DataKeys[gr.RowIndex].Value);
BLL.GuestbookBLL bll = new GuestbookBLL();
bll.Delete(gid);
}
}
BindGridivew();
}
BLL.GuestbookBLL bll = new GuestbookBLL();//此句 也放在foreach外边,不要每次循环都实例化一次
foreach (GridViewRow gr in GridView1.Rows)
{
CheckBox chk = (CheckBox)gr.FindControl("chk");
if (chk.Checked == true)
{
int gid = Convert.ToInt32(this.GridView1.DataKeys[gr.RowIndex].Value);
bll.Delete(gid);
}
}
BindGridivew();//将此句放在foreach外边,你如果一次删除100条,就要访问数据库100次,累不累?
ps:
//此方法个人的一点修改小意见
//绑定数据一次为何要访问两次数据库?
private void BindGridivew()
{
BLL.GuestbookBLL guestbookbll = new GuestbookBLL();
var q=guestbookbll.GetAllList();
if ((q.Tables[0].Rows.Count) == 0 )
{
this.Label1.Text = "目前没有留言,或留言已经被清除。";
}
else
{
this.GridView1.DataSource =q;
this.GridView1.DataBind();
}
}