利用Adapter对象将数据填充到DataTable(或DataSet)的例子

前:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataAdapter对象.aspx.cs" Inherits="WebApplication1.DataAdapter对象" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table border="1" cellpadding="0" cellspacing="0">
    <tr><td>编号</td><td>账号</td><td>真实姓名</td><td>年龄</td><td>
      性别</td><td>手机</td><td>电话</td><td>电子邮件</td></tr>
      <%
         ShowData();   
      %>
  </table>
    </div>
    </form>
</body>
</html>

后台CS代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace WebApplication1
{
    public partial class DataAdapter对象 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public void ShowData()
        {
            SqlConnection connection = new SqlConnection(@"server=Rose-PC\SQLEXPRESS;Database=User;User Id=sa;password=");
            SqlCommand command = new SqlCommand(" Select * from UserInfo where Sex=0",connection);
            //conn.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            /* 下面被注释掉的代码与上面的代码是等效的
            SqlDataAdapter adapter = new SqlDataAdapter("Select * from UserInfo where Sex=0",connection);
             */
            DataTable data = new DataTable();
            adapter.Fill(data);
            /*下面被注释掉的代码与上面的填充DataTable效果是等效的
             DataSet ds=new DataSet();
             adapter.Fill(ds,"UserInfo");
             DataTable data=ds.Tables["UserInfo"] 
             */
            for (int i = 0; i < data.Rows.Count; i++)
            {
                Response.Write("<tr><td>"+data.Rows[i]
                    ["ID"].ToString()+"</td>");
                Response.Write("<td>" + data.Rows[i]
                   ["UserName"].ToString() + "</td>");
                Response.Write("<td>" + data.Rows[i]
                   ["RealName"].ToString() + "</td>");
                Response.Write("<td>" + data.Rows[i]
                   ["Age"].ToString() + "</td>");
                Response.Write("<td>" + (bool.Parse(data.Rows[i]
                    ["Sex"].ToString())==true?"":"") + "</td>");
                Response.Write("<td>" + data.Rows[i]
                   ["Mobile"].ToString() + "</td>");
                Response.Write("<td>" + data.Rows[i]
                   ["Phone"].ToString() + "</td>");
                Response.Write("<td>" + data.Rows[i]
                   ["Email"].ToString() + "</td></tr>\n");
            }
        }
    }
}

图片显示:

posted @ 2013-09-27 18:00  笨笨丫头~双  阅读(209)  评论(0编辑  收藏  举报