DataGrid多行删除问题

tjxuemo 2005-12-30 08:41:36
我在DataGrid中加入了一列checkbox用来控制删除多行
可是发现了一个问题,就是假如我的分页为每页3行
当我把一页的所有记录行全部删除时,会出现当前索引错误
我想如果全部删除1.后面没有记录跳到前一个页面
2.后面有记录自动显示后面的记录
该如何解决?如果大虾们有这样的经验请赐教,或是给出相应代码
十分感谢!
...全文
573 22 打赏 收藏 转发到动态 举报
写回复
用AI写文章
22 条回复
切换为时间正序
请发表友善的回复…
发表回复
charmgjj 2006-03-02
  • 打赏
  • 举报
回复
学习
shengliqiang168 2006-03-02
  • 打赏
  • 举报
回复
学习
diablo1003 2006-01-14
  • 打赏
  • 举报
回复
mark
decfirst 2006-01-14
  • 打赏
  • 举报
回复
细心点,注意CurrentPage,PageSize,Count(总数),几个数据的处理就可以了,没什么难的,在DataGrid的几个事件中注意相应的数据改变就可以了。
yuelailiu 2006-01-13
  • 打赏
  • 举报
回复
删除信息后,刷新页面 的时候,再指定下页面索引 DataGrid1.CurrentPageIndex =0;
xiaostar007 2006-01-13
  • 打赏
  • 举报
回复
最简单的方案就是DataGrid1.CurrentPageIndex =0;
pangyong0221 2006-01-13
  • 打赏
  • 举报
回复
顶,学习
wuyq11 2006-01-13
  • 打赏
  • 举报
回复
datagrid上加一列checkbox.
mib23 2006-01-12
  • 打赏
  • 举报
回复
在删除按钮的时间中添加:
...
int count = 0;
//遍历myGrid.Item,执行删除操作
...
if( count == myGrid.Items.Count && myGrid.CurrentPageIndex > 0 )
{
-- myGrid.CurrentPageIndex;
}
//绑定myGrid
...
yundao2004 2006-01-12
  • 打赏
  • 举报
回复
//GetData()函数返回查询出的数据集
DataSet ds = GetData();
int MaxPageCount = (ds.Tables[0].Rows.Count % DataGrid1.PageSize)==0 ? ds.Tables[0].Rows.Count / DataGrid1.PageSize : ds.Tables[0].Rows.Count / DataGrid1.PageSize + 1;
DataGrid1.CurrentPageIndex = (DataGrid1.CurrentPageIndex<MaxPageCount && DataGrid1.CurrentPageIndex > -1)? DataGrid1.CurrentPageIndex : 0;
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
tjxuemo 2006-01-04
  • 打赏
  • 举报
回复
#region 显示详情
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if(e.CommandName=="Detail")
{
// if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
// {
// while(e.Item.ItemIndex>-1)
// {
SqlConnection con =new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
con.Open();
SqlCommand cmd=new SqlCommand("select * from ss where id=@id",con);
SqlParameter id=cmd.Parameters.Add("@id",SqlDbType.Int);
id.Value=this.DataGrid1.DataKeys[(int)e.Item.ItemIndex];
SqlDataReader sdr=cmd.ExecuteReader();


while(sdr.Read())
{
txbName.Text =sdr.GetString(1);
txbAge.Text =sdr.GetInt32(2).ToString();
txbAddress.Text =sdr.GetString(3);
txbPhone.Text =sdr.GetInt32(4).ToString();
txbbirthday.Text =sdr.GetDateTime(5).ToShortDateString();
txbid.Text =sdr.GetInt32(0).ToString();

}
sdr.Close();
con.Close();



// }
// }
}

}
#endregion

#region 分页
public void PageButtonClick(Object sender, EventArgs e)//分页
{
//获得LinkButton的参数值
string arg = ((LinkButton)sender).CommandArgument;

switch(arg)
{
case ("next"):
if (DataGrid1.CurrentPageIndex < (DataGrid1.PageCount - 1))
DataGrid1.CurrentPageIndex ++;
break;
case ("pre"):
if (DataGrid1.CurrentPageIndex > 0)
DataGrid1.CurrentPageIndex --;
break;
case ("last"):
DataGrid1.CurrentPageIndex = (DataGrid1.PageCount - 1);
break;
case("first"):
DataGrid1.CurrentPageIndex =0;
break;
}
Datagridbind();

}
#endregion

private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{

}



#region 添加信息

private void btn2_Click(object sender, System.EventArgs e)//添加信息
{
SqlConnection con =new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
con.Open();
SqlCommand cmd=new SqlCommand("insert_P",con);
cmd.CommandType=CommandType.StoredProcedure;
SqlParameter id =new SqlParameter("@id",SqlDbType.Int);
SqlParameter name =new SqlParameter("@name",SqlDbType.VarChar);
SqlParameter age =new SqlParameter("@age",SqlDbType.Int);
SqlParameter phone =new SqlParameter("@phone",SqlDbType.Int);
SqlParameter address =new SqlParameter("@address",SqlDbType.VarChar,50);
SqlParameter birthday=new SqlParameter("@birthday",SqlDbType.DateTime);
id.Value =txbid.Text;
name.Value =txbName.Text;
age.Value =txbAge.Text;
address.Value=txbAddress.Text;
phone.Value =txbPhone.Text;
birthday.Value=txbbirthday.Text;
cmd.Parameters.Add(id);
cmd.Parameters.Add(name);
cmd.Parameters.Add(age);
cmd.Parameters.Add(phone);
cmd.Parameters.Add(address);
cmd.Parameters.Add(birthday);
cmd.ExecuteNonQuery();
con.Close();
Datagridbind();
loadpage();



}
#endregion

private void btncx_Click(object sender, System.EventArgs e)//查询
{
if(ddlcx.SelectedItem.Text=="姓名")
searchByName();
else
if(ddlcx.SelectedItem.Text=="年龄")
searchByAge();
else
searchByAddress();
}

private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
Datagridbind();
}
/// <summary>
/// 跳转页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

private void btngo_Click(object sender, System.EventArgs e)//跳转分页
{
if(txtgo.Text.Trim()!="")
{
int Page=Int32.Parse(txtgo.Text.Trim())-1;
if (Page >=0 && Page < (DataGrid1.PageCount))
DataGrid1.CurrentPageIndex = Page;
}
Datagridbind();
loadpage();

}



#region 多行删除

private void btndel_Click(object sender, System.EventArgs e)
{
string myid = "";
for(int i=0;i<this.DataGrid1.Items.Count;i++)
{
CheckBox mychk = (CheckBox)this.DataGrid1.Items[i].FindControl("DeleteThis");
if(mychk.Checked == true)

{
myid = this.DataGrid1.DataKeys[i].ToString();
try
{
SqlConnection con=new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
con.Open();
SqlCommand cmd =new SqlCommand("delete from ss where id=@id",con);
SqlParameter id =cmd.Parameters.Add("@id",SqlDbType.BigInt);
id.Value =myid;
cmd.ExecuteNonQuery();
con.Close();

}
catch(SqlException ep)
{
Console.WriteLine("Exception in main:"+ep.Message);
}


}



}

Datagridbind();
if(DataGrid1.CurrentPageIndex<0 || DataGrid1.CurrentPageIndex>DataGrid1.PageCount)
{
DataGrid1.CurrentPageIndex=0;
}
loadpage();



}
#endregion









}
}
tjxuemo 2006-01-04
  • 打赏
  • 举报
回复
#region 按年龄查询

private void searchByAge()//通过年龄查询
{
try
{
SqlConnection con =new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
con.Open();
SqlDataAdapter cmd=new SqlDataAdapter();
cmd.SelectCommand =new SqlCommand("searchAge",con);
// cmd.SelectCommand =new SqlCommand("select * from ss where name=@name",con);
cmd.SelectCommand.CommandType=CommandType.StoredProcedure;
SqlParameter age =new SqlParameter("@age",SqlDbType.VarChar);
cmd.SelectCommand.Parameters.Add(age);
age.Value=txtcx.Text.ToString();
cmd.SelectCommand.ExecuteScalar();
DataSet ds=new DataSet();
cmd.Fill(ds);
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
con.Close();
}
catch(SqlException e)
{
Console.WriteLine("Exception in Main: " + e.Message); //出错处理
}

}
#endregion


// private void PageButtonClick(object sender, System.EventArgs e)
// {
// //获得LinkButton的参数值
// String arg = ((LinkButton)sender).CommandArgument;
//
// switch(arg)
// {
// case ("next"):
// if (DataGrid1.CurrentPageIndex < (DataGrid1.PageCount - 1))
// DataGrid1.CurrentPageIndex ++;
// break;
// case ("pre"):
// if (DataGrid1.CurrentPageIndex > 0)
// DataGrid1.CurrentPageIndex --;
// break;
// case ("fist"):
// DataGrid1.CurrentPageIndex=0;
// break;
// case ("last"):
// DataGrid1.CurrentPageIndex = (DataGrid1.PageCount - 1);
// break;
// default:
// //本页值
// DataGrid1.CurrentPageIndex = Convert.ToInt32(arg);
// break;
// }
// Datagridbind();
// }

#region 绑定DataGrid方法


private void Datagridbind()//绑定DataGrid
{
SqlConnection con =new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
con.Open();
DataSet ds=new DataSet();
SqlDataAdapter sda=new SqlDataAdapter("select * from ss",con);
sda.Fill(ds,"sss");
DataView dv=ds.Tables["sss"].DefaultView;
DataGrid1.DataSource=dv;


// int TotalPages=DataGrid1.PageCount;
// if( DataGrid1.CurrentPageIndex > TotalPages - 1 )
// {
// DataGrid1.CurrentPageIndex = TotalPages -1;
// }
//
// if( TotalPages <= 0 )
// {
// DataGrid1.CurrentPageIndex = 0;
// }
DataGrid1.DataBind();
// DataGrid.CurrentPageIndex = CurrrentPageIndex;
// if(DataGrid1.CurrentPageIndex<0 || DataGrid1.CurrentPageIndex>DataGrid1.PageCount)
// {
// DataGrid1.CurrentPageIndex=0;
// }

con.Close();
}
#endregion
//删除命令

private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
object b=this.DataGrid1.DataKeys[(int)e.Item.ItemIndex];
Delitem(b);
// if(e.Item.ItemIndex==0)
// DataGrid1.CurrentPageIndex=DataGrid1.CurrentPageIndex-1;
Datagridbind();
loadpage();
}

#region 修改
private void btn1_Click(object sender, System.EventArgs e)//修改
{
try
{
SqlConnection con =new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
con.Open();
SqlCommand cmd=new SqlCommand("update ss set name=@name,age=@age,address=@address,phone=@phone,birthday=@birthday where id=@id",con);
SqlParameter name =cmd.Parameters.Add("@name",SqlDbType.VarChar);
SqlParameter age =cmd.Parameters.Add("@age",SqlDbType.BigInt);
SqlParameter address =cmd.Parameters.Add("@address",SqlDbType.VarChar);
SqlParameter phone =cmd.Parameters.Add("@phone",SqlDbType.BigInt);
SqlParameter birthday =cmd.Parameters.Add("@birthday",SqlDbType.DateTime);
SqlParameter id =cmd.Parameters.Add("@id",SqlDbType.BigInt);

name.Value =txbName.Text;
age.Value =txbAge.Text;
address.Value =txbAddress.Text;
phone.Value =txbPhone.Text;
birthday.Value=txbbirthday.Text;
id.Value =txbid.Text;
cmd.ExecuteReader();
con.Close();
}
catch(SqlException ep)
{
Console.WriteLine("Exception in main:"+ep.Message);
}
Datagridbind();
}
#endregion

#region 删除行

private void Delitem(object a)//删除行
{
try
{
SqlConnection con=new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
con.Open();
SqlCommand cmd =new SqlCommand("delete from ss where id=@id",con);
SqlParameter id =cmd.Parameters.Add("@id",SqlDbType.BigInt);
id.Value =a;
int i =cmd.ExecuteNonQuery();
con.Close();

}
catch(SqlException e)
{
Console.WriteLine("Exception in main:"+e.Message);
}


}
#endregion
//显示详情

tjxuemo 2006-01-04
  • 打赏
  • 举报
回复
我靠,问题还没有解决,我把.cs代码贴出来,大家帮我看下那里错了,谢谢各位:


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;


namespace adddemo
{
/// <summary>
/// WebForm1 的摘要说明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox txbName;
protected System.Web.UI.WebControls.TextBox txbAge;
protected System.Web.UI.WebControls.TextBox txbPhone;
protected System.Web.UI.WebControls.TextBox txbAddress;
protected System.Web.UI.WebControls.Button btn1;
protected System.Web.UI.WebControls.TextBox txbbirthday;
protected System.Web.UI.WebControls.RangeValidator RangeValidator1;
protected System.Web.UI.WebControls.Button btnsee;
protected System.Web.UI.WebControls.LinkButton lbtnpre;
protected System.Web.UI.WebControls.LinkButton lbtnnext;
protected System.Web.UI.WebControls.LinkButton lbtnlast;
protected System.Web.UI.WebControls.LinkButton lbtnfirst;
protected System.Web.UI.WebControls.Button btn2;
protected System.Web.UI.WebControls.TextBox txtcx;
protected System.Web.UI.WebControls.DropDownList ddlcx;
protected System.Web.UI.WebControls.TextBox txbid;
protected System.Web.UI.WebControls.Button btncx;
protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
protected System.Web.UI.WebControls.TextBox txtgo;
protected System.Web.UI.WebControls.Button btngo;
protected System.Web.UI.WebControls.Label lblsum;
protected System.Web.UI.WebControls.Label lbldq;
protected System.Web.UI.WebControls.Button btndel;
protected System.Web.UI.WebControls.DataGrid DataGrid1;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!this.IsPostBack)
{

SqlConnection con =new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
con.Open();
SqlCommand cmd=new SqlCommand("sename",con);
cmd.CommandType=CommandType.StoredProcedure;
SqlDataReader sdr=cmd.ExecuteReader();
while(sdr.Read())
{

txbName.Text=sdr.GetString(1);
txbAge.Text=sdr.GetInt32(2).ToString();
txbAddress.Text=sdr.GetString(3);
txbPhone.Text=sdr.GetInt32(4).ToString();
txbbirthday.Text=sdr.GetDateTime(5).ToShortDateString();
txbid.Text=sdr.GetInt32(0).ToString();

}
sdr.Close();
Datagridbind();
con.Close();
loadpage();

}

}
private void loadpage()//载入第*共*页
{
lbldq.Text=Convert.ToString((int)DataGrid1.CurrentPageIndex+1);
lblsum.Text=DataGrid1.PageCount.ToString();
}

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btn2.Click += new System.EventHandler(this.btn2_Click);
this.btn1.Click += new System.EventHandler(this.btn1_Click);
this.btngo.Click += new System.EventHandler(this.btngo_Click);
this.btncx.Click += new System.EventHandler(this.btncx_Click);
this.btndel.Click += new System.EventHandler(this.btndel_Click);
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_DeleteCommand);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void DataGrid1_SelectedIndexChanged(object sender, System.EventArgs e)
{


}

#region 通过名字查询

private void searchByName()//通过名字查询
{
try
{
SqlConnection con =new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
con.Open();
SqlDataAdapter cmd=new SqlDataAdapter();
cmd.SelectCommand =new SqlCommand("searchbyname",con);
// cmd.SelectCommand =new SqlCommand("select * from ss where name=@name",con);
cmd.SelectCommand.CommandType=CommandType.StoredProcedure;
SqlParameter name =new SqlParameter("@name",SqlDbType.VarChar,50);
cmd.SelectCommand.Parameters.Add(name);
name.Value=txtcx.Text.ToString();
cmd.SelectCommand.ExecuteScalar();
DataSet ds=new DataSet();
cmd.Fill(ds);
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
// lbl1.Text=name.Value.ToString();
con.Close();
}
catch(SqlException e)
{
Console.WriteLine("Exception in Main: " + e.Message); //出错处理
}
}
#endregion

#region 地址查询
private void searchByAddress()//通过地址查询
{
try
{
SqlConnection con =new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
con.Open();
SqlDataAdapter cmd=new SqlDataAdapter();
cmd.SelectCommand =new SqlCommand("searchByAddress",con);
// cmd.SelectCommand =new SqlCommand("select * from ss where name=@name",con);
cmd.SelectCommand.CommandType=CommandType.StoredProcedure;
SqlParameter address =new SqlParameter("@address",SqlDbType.VarChar);
cmd.SelectCommand.Parameters.Add(address);
address.Value=txtcx.Text.ToString();
cmd.SelectCommand.ExecuteScalar();
DataSet ds=new DataSet();
cmd.Fill(ds);
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
con.Close();
}
catch(SqlException e)
{
Console.WriteLine("Exception in Main: " + e.Message); //出错处理
}
}
#endregion

mzg008 2006-01-04
  • 打赏
  • 举报
回复
收藏一下!!
sunnystar365 2005-12-30
  • 打赏
  • 举报
回复
做一下判断
if(DataGrid1.CurrentPageIndex<0 || DataGrid1.CurrentPageIndex>PageCount(总页数))
{
DataGrid1.CurrentPageIndex=0;
}
time_is_life 2005-12-30
  • 打赏
  • 举报
回复
谢谢老大,我是先执行删除操作,然后重新绑定数据
可是怎么还是报错:

无效的 CurrentPageIndex 值。它必须大于等于 0 且小于 PageCount。

-------------------------------------------------------

1.每次换页的时候都将CurrentPageIndex 储存在ViewState中
2.每次删除记录的时候都重新计算TotalPages
if( CurrentPageIndex > TotalPages - 1 )
{
CurrrentPageIndex = TotalPages -1;
}

if( TotalPages <= 0 )
{
CurrrentPageIndex = 0;
}

DataGrid.CurrentPageIndex = this.CurrrentPageIndex;
tjxuemo 2005-12-30
  • 打赏
  • 举报
回复
谢谢老大,我是先执行删除操作,然后重新绑定数据
可是怎么还是报错:

无效的 CurrentPageIndex 值。它必须大于等于 0 且小于 PageCount。
jxufewbt 2005-12-30
  • 打赏
  • 举报
回复
net_lover(孟子E章) 老大正解
孟子E章 2005-12-30
  • 打赏
  • 举报
回复
C# 版本

CheckBoxDataGrid.aspx

<%@ Page language=""c#"" enableViewState = ""true"" Codebehind=""DataGridCheckBox.aspx.cs""
AutoEventWireup=""false"" Inherits=""eMeng.Exam.DataGridCheckBox.DataGridCheckBox"" %>
<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">
<HTML>
<HEAD>
<title>为DataGrid添加CheckBox控件的例子</title>
</HEAD>
<body>
<form id=""frmMain"" method=""post"" runat=""server"">
<asp:DataGrid id=""dgMain"" runat=""server"" Width=""98%"" AutoGenerateColumns=""False"" Font-Size=""9pt"" Font-Names=""宋体"">
<AlternatingItemStyle ForeColor=""ControlText"" BackColor=""White"" />
<ItemStyle ForeColor=""ControlText"" BackColor=""WhiteSmoke"" />
<HeaderStyle Font-Bold=""True"" HorizontalAlign=""Center"" ForeColor=""Black"" VerticalAlign=""Middle""
BackColor=""Control""></HeaderStyle>
<Columns>
<asp:TemplateColumn HeaderText=""操作"">
<HeaderStyle HorizontalAlign=""Center"" Width=""50px""></HeaderStyle>
<ItemTemplate>
<input type=""hidden"" id=""SelectedID"" runat=""server""
value='<%# DataBinder.Eval(Container.DataItem, ""id"")%>'/>
<asp:CheckBox ID=""chkExport"" Runat=""server"" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField=""id"" ReadOnly=""True"" HeaderText=""序号"">
<HeaderStyle Width=""50px""></HeaderStyle>
</asp:BoundColumn>
<asp:TemplateColumn SortExpression=""demo"" HeaderText=""标题"">
<ItemTemplate>
<asp:Label Text='<%# Server.HtmlEncode((string)DataBinder.Eval(Container.DataItem, ""Title""))%>'
runat=""server"" Width=""80%"" ID=""lblColumn"" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:Button id=""cmdSelectAll"" runat=""server"" Text=""全部选中""></asp:Button>
<asp:Button id=""cmdFindSelected"" runat=""server"" Text=""查看选中的项目""></asp:Button>
<br>
<asp:Label id=""Label1"" runat=""server""></asp:Label>
<hr>
<asp:Label id=""Label2"" runat=""server""></asp:Label>
</form>
</body>
</HTML>

DataGridCheckBox.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace eMeng.Exam.DataGridCheckBox
{
/// <summary>
/// DataGridCheckBox 的摘要说明。
/// 【孟宪会之精彩世界】
/// </summary>
public class DataGridCheckBox : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button cmdSelectAll;
protected System.Web.UI.WebControls.Button cmdFindSelected;
protected System.Web.UI.WebControls.DataGrid dgMain;
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Label Label2;
DataView oDataView;
string sConnectionString = ""Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""
+ HttpContext.Current.Server.MapPath(""../../aspxWeb.mdb.ascx"");

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
dgMain.Columns[0].HeaderText = ""选项"";
dgMain.Columns[1].HeaderText = ""序号"";
dgMain.Columns[2].HeaderText = ""标题"";
cmdFindSelected.Text = ""查看选中的项目"";
RefreshGrid();
if( !this.IsPostBack)
{
cmdSelectAll.Text = ""全部选中"";
dgMain.DataBind();
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.cmdSelectAll.Click += new System.EventHandler(this.cmdSelectAll_Click);
this.cmdFindSelected.Click += new System.EventHandler(this.cmdFindSelected_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void cmdSelectAll_Click(object sender, System.EventArgs e)
{
selectAll();
}

private void selectAll()
{
System.Web.UI.WebControls.CheckBox chkExport ;
if( cmdSelectAll.Text == ""全部选中"")
{
foreach(DataGridItem oDataGridItem in dgMain.Items)
{
chkExport = (CheckBox)oDataGridItem.FindControl(""chkExport"");
chkExport.Checked = true;
}
cmdSelectAll.Text = ""全部不选"";
}
else
{
foreach(DataGridItem oDataGridItem in dgMain.Items)
{
chkExport = (CheckBox)oDataGridItem.FindControl(""chkExport"");
chkExport.Checked = false;
}
cmdSelectAll.Text = ""全部选中"";
}
}

private void RefreshGrid()
{
OleDbConnection oConnection;
OleDbDataAdapter oCommand ;
DataSet oDataSet = new DataSet();
try
{
string sSQL = ""Select top 10 * from Document order by CreateDate DESC"";
oConnection = new OleDbConnection(sConnectionString);
oCommand = new OleDbDataAdapter(sSQL.ToString(), oConnection);
oCommand.Fill(oDataSet, ""Document"");
oDataView = new DataView(oDataSet.Tables[""Document""]);
dgMain.DataSource = oDataView;
oConnection.Close();
}
catch(Exception ex)
{
Label1.Text = ex.Message.ToString();
}
}

private void cmdFindSelected_Click(object sender, System.EventArgs e)
{
System.Web.UI.WebControls.CheckBox chkExport;
System.Collections.ArrayList oExArgs = new System.Collections.ArrayList();
string sID;
Label1.Text = """";
Label2.Text = """";
foreach(DataGridItem oDataGridItem in dgMain.Items)
{
chkExport = (CheckBox)oDataGridItem.FindControl(""chkExport"");
if( chkExport.Checked)
{
//如果要进行删除,可以在这里构造sql语句进行删除
string sql = ""DELETE FROM Document WHERE id =""
+ ((HtmlInputHidden)oDataGridItem.FindControl(""SelectedID"")).Value;
Label2.Text += ""<li>"" + sql;
sID = ((HtmlInputHidden)oDataGridItem.FindControl(""SelectedID"")).Value;
oExArgs.Add(sID);
int i = 0;
Label1.Text = """";
for( i = 0;i<oExArgs.Count;i++)
{
Label1.Text += oExArgs[i] + ""<br>"";
}
}
}
Label2.Text += ""<br><font color=red>执行SQL语句即可删除,这里省略。</font>"";
}
}
}

孟子E章 2005-12-30
  • 打赏
  • 举报
回复
VB.NET 版本

CheckBoxDataGrid.aspx

<%@ Page Language=""vb"" AutoEventWireup=""false"" Codebehind=""CheckBoxDataGrid.aspx.vb""
Inherits=""aspxWeb.CheckBoxDataGrid"" %>
<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">
<HTML>
<HEAD>
<title>为DataGrid添加CheckBox控件的例子</title>
<meta name=""GENERATOR"" content=""Microsoft Visual Studio.NET 7.0"">
<meta name=""CODE_LANGUAGE"" content=""Visual Basic 7.0"">
<meta name=""vs_defaultClientScript"" content=""JavaScript"">
<meta name=""vs_targetSchema"" content=""http://schemas.microsoft.com/intellisense/ie5"">
</HEAD>
<body MS_POSITIONING=""GridLayout"">
<form id=""frmMain"" method=""post"" runat=""server"">
<asp:DataGrid id=""dgMain"" runat=""server"" Width=""98%"" AutoGenerateColumns=""False"">
<SelectedItemStyle Font-Size=""9pt"" Font-Names=""宋体""></SelectedItemStyle>
<EditItemStyle Font-Size=""9pt"" Font-Names=""宋体"" Font-Bold=""True"" ForeColor=""Red"" BackColor=""Info""/>
<AlternatingItemStyle Font-Size=""9pt"" Font-Names=""宋体"" ForeColor=""ControlText"" BackColor=""White""/>
<ItemStyle Font-Size=""9pt"" Font-Names=""宋体"" ForeColor=""ControlText"" BackColor=""WhiteSmoke""/>
<HeaderStyle Font-Bold=""True"" HorizontalAlign=""Center"" ForeColor=""Black""
VerticalAlign=""Middle"" BackColor=""Control"">
</HeaderStyle>
<Columns>
<asp:TemplateColumn HeaderText=""操作"">
<HeaderStyle HorizontalAlign=""Center"" Width=""50px""></HeaderStyle>
<ItemTemplate>
<asp:CheckBox ID=""chkExport"" Runat=""server"" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID=""chkExportON"" Runat=""server"" Enabled=""true"" />
</EditItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField=""id"" ReadOnly=""True"" HeaderText=""序号"">
<HeaderStyle Width=""50px""></HeaderStyle>
</asp:BoundColumn>
<asp:TemplateColumn SortExpression=""demo"" HeaderText=""标题"">
<ItemTemplate>
<asp:Label Text='<%# Server.HTMLEncode(DataBinder.Eval(Container.DataItem, ""Title""))%>'
runat=""server"" Width=""80%"" ID=""lblColumn""/>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:Button id=""cmdSelectAll"" runat=""server"" Text=""全部选中""></asp:Button>
<asp:Button id=""cmdFindSelected"" runat=""server"" Text=""查看选中的项目""></asp:Button>
<br>
<asp:Label id=""Label1"" runat=""server""></asp:Label>
</form>
</body>
</HTML>

后代码 CheckBoxDataGrid.aspx.vb

Imports System.Data
Imports System.Data.OleDb

Public Class CheckBoxDataGrid
Inherits System.Web.UI.Page
Protected WithEvents cmdSelectAll As System.Web.UI.WebControls.Button
Protected WithEvents dgMain As System.Web.UI.WebControls.DataGrid
Protected WithEvents cmdFindSelected As System.Web.UI.WebControls.Button

Dim oDataView As DataView
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Dim sConnectionString As String = ""Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""_
+ Server.MapPath(""Test.mdb"")


#Region "" Web Form Designer Generated Code ""

'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

End Sub

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
'Put user code to initialize the page here
dgMain.Columns(0).HeaderText = ""选项""
dgMain.Columns(1).HeaderText = ""序号""
dgMain.Columns(2).HeaderText = ""标题""
cmdFindSelected.Text = ""查看选中的项目""
RefreshGrid()
If Not Page.IsPostBack Then
cmdSelectAll.Text = ""全部选中""
dgMain.DataBind()
End If

End Sub


#Region ""处理多选""
Private Sub cmdSelectAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles cmdSelectAll.Click
selectAll()
End Sub

Private Sub selectAll()
Dim oDataGridItem As DataGridItem
Dim chkExport As System.Web.UI.WebControls.CheckBox

If cmdSelectAll.Text = ""全部选中"" Then
For Each oDataGridItem In dgMain.Items
chkExport = oDataGridItem.FindControl(""chkExport"")
chkExport.Checked = True
Next
cmdSelectAll.Text = ""全部不选""
Else
For Each oDataGridItem In dgMain.Items
chkExport = oDataGridItem.FindControl(""chkExport"")
chkExport.Checked = False
Next
cmdSelectAll.Text = ""全部选中""
End If
End Sub
#End Region

#Region ""更新DataGrid""

Private Sub RefreshGrid()
Dim oConnection As OleDbConnection
Dim oCommand As OleDbDataAdapter
Dim oDataSet As New DataSet()

Try
Dim sSQL As String = ""Select top 5 * from TestTable order by id""
oConnection = New OleDbConnection(sConnectionString)
oCommand = New OleDbDataAdapter(sSQL.ToString, oConnection)
oCommand.Fill(oDataSet, ""TestTable"")
oDataView = New DataView(oDataSet.Tables(""TestTable""))
dgMain.DataSource = oDataView
oConnection.Close()

Catch ex As Exception
'// Place Error Handling here
End Try
End Sub
#End Region

Private Sub cmdFindSelected_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles cmdFindSelected.Click
Dim oDataGridItem As DataGridItem
Dim chkExport As System.Web.UI.WebControls.CheckBox
Dim oExArgs As New System.Collections.ArrayList()
Dim sID As String
Label1.Text = """"
For Each oDataGridItem In dgMain.Items
chkExport = oDataGridItem.FindControl(""chkExport"")
If chkExport.Checked Then
Label1.Text = """"
sID = CType(oDataGridItem.FindControl(""lblColumn""), Label).Text
oExArgs.Add(sID)
Dim i As Integer = 0
For i = 0 To oExArgs.Count - 1
Label1.Text += oExArgs(i) + "",""
Next
End If
Next
End Sub

End Class

加载更多回复(2)

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧