DataAdapter 를 사용 하여 여러 표(DataRelation 이용)의 인 스 턴 스 코드 를 채 웁 니 다.

3469 단어 DataAdapter충전 표

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();//
    }

}

좋은 웹페이지 즐겨찾기