欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用DataAdapter填充多个表(利用DataRelation)的实例代码

程序员文章站 2024-03-02 23:08:40
default.aspx 复制代码 代码如下:view code <%@ page language="c#" autoeventwireup="true"...

使用DataAdapter填充多个表(利用DataRelation)的实例代码

default.aspx

复制代码 代码如下:

view code

<%@ page language="c#" autoeventwireup="true"  codefile="default.aspx.cs" inherits="_default" %>

<!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>

    </div>
    <asp:label id="lbtext" runat="server"></asp:label>
    </form>
</body>
</html>

default.aspx.cs

复制代码 代码如下:

using system;
using system.configuration;
using system.data;
using system.linq;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.htmlcontrols;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.xml.linq;

using system.data.sqlclient;
using system.text;

public partial class _default : system.web.ui.page
{
    protected void page_load(object sender, eventargs e)
    {
        string connectionstring = configurationsettings.appsettings["strcon"];
        sqlconnection mycon = new sqlconnection(connectionstring);//创建数据库连接
        string sqlcategory = "select id,c_name from photo_category";//查询相册分类表中信息
        string sqlphoto = "select categoryid,title from photo";//查询相册表中信息
        sqldataadapter da = new sqldataadapter(sqlcategory, mycon);//创建数据适配器
        dataset ds = new dataset();//创建数据集
        try
        {
            if (mycon.state.equals(connectionstate.closed))
            { mycon.open(); }//显式地打开数据库连接
            da.fill(ds, "photo_category");//填充相册分类表
            da.selectcommand.commandtext = sqlphoto;
            da.fill(ds, "photo");//填充相册信息表
        }
        finally
        {
            mycon.close();//显式地关闭数据库连接
        }
        //创建datarelation对象,关联表间关系
        datarelation relat = new datarelation("photo_category",  ds.tables["photo_category"].columns["id"],ds.tables["photo"].columns["categoryid"]);
        ds.relations.add(relat);//添加表间关系
        stringbuilder builder = new stringbuilder("");
        foreach (datarow row in ds.tables["photo_category"].rows)
        {
            builder.append("<b>");
            builder.append(row["c_name"].tostring());
            builder.append("</b><ul>");
            datarow[] childrows = row.getchildrows(relat);
            foreach (datarow childrow in childrows)
            {
                builder.append("<li>");
                builder.append(childrow["title"].tostring());
                builder.append("</li>");
            }
            builder.append("</ul>");
        }
        lbtext.text += builder.tostring();//将运行结果输出到页面中
    }

}