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

c#中datalist如何调用数据库中数据,急!
大神们好,
本人半新手,会一点,textbox和gridview我可以从数据库中导入数据,我这里因为sql版本低 不方便装,因此不能导入数据只能写代码控制,


Datalist为DataList1
数据库我创建了个表叫consult  里面有2列Title 和Date

上代码:
HTML

 
    <div class="flexme">             
               <asp:DataList ID="DataList1" runat="server">
              <itemtemplate>
                <table width="700" border="0" align="center" cellpadding="0" cellspacing="0">
                  <tr>
                    <td><div align="center"><%# DataBinder.Eval(Container.DataItem,"Title") %></div></td>
                    <td><div align="center"><%# DataBinder.Eval(Container.DataItem,"Date") %></div></td>
                  </tr>
                </table>
              </itemtemplate>
            </asp:DataList>
          </div>

网页cs代码:

 public SqlConnection conn;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.DataList1.DataBind();
        }

        string sConnectionString = @"server=xxxxx;database=shhr;user id=sa;password=xxxx;";
        SqlConnection conn = new SqlConnection(sConnectionString);
        conn.Open();
        string sSql = "select Title,Date from consult";
        SqlCommand com = new SqlCommand(sSql,conn );
        SqlDataReader dr = com.ExecuteReader();
        if (dr.Read())
        {
            this.DataList1.DataSource = dr[0].ToString();
        }
        dr.Close();
        conn.Close();

    }

连接数据库使用DataReader,
不知道 问题出在哪?
是不是Datalist不能着么调用数据库中数据?

------解决方案--------------------
DataReader每次只读取一条,你要显示所有数据还是用其他的吧,把数据都读过来