日期:2014-05-17  浏览次数:20424 次

关于Datalist的几个问题,求坛友帮助。
在做一个新闻网站,遇见几个难点。
1.目的:DataList中放一个Label,显示文章评论数量.
(1)显示评论数量,存储过程我是这样写的:Select count(comment.cid) from comment,news where comment.nid=news.nid;
但取出来的东西,怎么给Label赋值,for循环??
2.目的:分页显示并控制每页Datalist显示的数量.
(2)
 int pageCount;//总页数
    int currentPage = 1;//第定义当前页
    void bind()
    {
        string str = @"Data Source=.\sqlexpress;Initial Catalog=News;Integrated Security=True";
        SqlConnection conn = new SqlConnection(str);
        string sqlStr = "select * from News";
        SqlDataAdapter sda = new SqlDataAdapter(sqlStr, conn);
        DataSet ds = new DataSet();
        sda.Fill(ds, "nid");
        //创建数据源
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = ds.Tables["nid"].DefaultView;
        //允许分页
        pds.AllowPaging = true;
        //设置每页显示记录数
        pds.PageSize = int.Parse(this.DropDownList1.SelectedItem.Value);
        //获取总页数
        pageCount = pds.PageCount;
        this.Label1.Text = pageCount.ToString();
        pds.CurrentPageIndex = currentPage - 1;
        //当前页
        this.Label2.Text = Convert.ToString(currentPage);
        this.DataList1.DataSource = pds;
        this.DataList1.DataBind();

这是我的代码,最后两行数据源绑定的代码报错,因为Datalist已经绑定了数据库里的News表,不允许在绑定pds。
datalist

------解决方案--------------------
1. 不需要用for循环

2. PagedDataSource是什么数据源,应该是分页用的吧,你应该返回一个List<T>
List<T> list=ds.Tables["nid"].DefaultView
this.DataList1.DataSource = list;         
this.DataList1.DataBind(); 


------解决方案--------------------
1、评论数直接用count()as NUM来统计就好了,然后label直接Text='<%#Eval("Num") %>'绑定
2、你是否前台绑定了SqlDataSource之类的控件,去掉一个
------解决方案--------------------
引用:
我在想,Eval是不是只能绑定数据库表中有的属性,我表中是没有评论数这个属性的。存储过程 count(nid) as NUM,是不是还需要在代码中给NUM取出来。

还是感觉很