您的位置:首页 > 其它

datalist结合PagedDataSource 类进行分页

2007-11-24 11:54 281 查看
public void sel_callname()
{

PagedDataSource ps = new PagedDataSource();//用来给数据控件显示分页的类不能继承
int curpage = Convert.ToInt32(this.lblCurrentIndex.Text.Trim());
//获取数据源
string sqlstr = "select articleid,title,classname,username,dateandtime From db_article";
com = new SqlCommand(sqlstr, con);
com.CommandType = CommandType.Text;
da = new SqlDataAdapter();
da.SelectCommand = com;
ds = new DataSet();
da.Fill(ds);
ps.DataSource = ds.Tables[0].DefaultView;
ps.AllowPaging = true;//是否可以分业
ps.PageSize = 3;//每页显示数据的数量
ps.CurrentPageIndex = curpage - 1;//取得当前的页码
this.LinkButton2.Enabled = true;
this.Linkbutton3.Enabled = true;
this.Linkbutton4.Enabled = true;
this.lblCurrentIndex.Enabled = true;
//如果是当前第一页
if (curpage == 1)
{
this.btnFirst.Enabled = false;//不显示第一页按钮
this.LinkButton2.Enabled = false;//不显示上一页按钮
}
//如果是最后一页
if (curpage == ps.PageCount)
{
this.Linkbutton3.Enabled = false;//不显示下一页按钮
this.Linkbutton4.Enabled = false;//不显示最后一页按钮
}
this.lblPageCount.Text = Convert.ToString(ps.PageCount);//得到最后一页
for (int i = 1; i <= ps.PageCount; i++)//填充下拉列表值
{
DropDownList2.Items.Add("" + i);
}
try
{
GridView1.DataSource = ps;
GridView1.DataBind();
}
catch (SqlException ex)
{
myLabel.Text = "数据库错误!" + ex.Message;
}
finally
{
ds.Clone();
com.Clone();
con.Close();
}
}
//怎样获得给DataList中添加一个Bootn按钮进行删除的功能
//首先绑定datalist,str是传进来的任何有效的sql查询语句
protected void Data_x(string str)
{
con = new SqlConnection(ConfigurationSettings.AppSettings["dsn"]);
da = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
try
{
da.Fill(ds, "table");
DataList1.DataSource = ds;
DataList1.DataKeyField = "xid";//用来绑定主键这点很重要
DataList1.DataBind();
}
catch (SqlException ex)
{
throw (ex);
}
finally
{
ds.Clone();
con.Close();
}
}
//下面是通过DataList1的ItemCommand事件来获得添加到DataList中的按钮事件
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["dsn"]);
//DataList1.DataKeys[e.Item.ItemIndex].ToString();用来获得DataList1.DataKeyField = "xid";//用来绑定主键
string del_str = "delete from bbs_xinxi where xid=" + DataList1.DataKeys[e.Item.ItemIndex].ToString();
com = new SqlCommand(del_str, con);
try
{
con.Open();
if (com.ExecuteNonQuery() > 0)
{//下面是删除成功后从新绑定DataList
string _str = "select xid,xuname,xdate,xtext from bbs_xinxi where xjname='" + u_name +
"'and xyidu=1 order by xdate desc";
Data_x(_str);
}
else
{
Page.RegisterStartupScript("key","<script>此信息不能被删除!</script>");
}

}
catch (SqlException ex)
{
throw (ex);
}
finally
{
con.Close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: