脚本宝典收集整理的这篇文章主要介绍了使用DataAdapter填充多个表(利用DataRelation)的实例代码,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Default.aspx
<%@ 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();//将运行结果输出到页面中
}
}
以上是脚本宝典为你收集整理的使用DataAdapter填充多个表(利用DataRelation)的实例代码全部内容,希望文章能够帮你解决使用DataAdapter填充多个表(利用DataRelation)的实例代码所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。