none
在DataSet中创建DataRelations的问题 RRS feed

  • 问题

  • 最近做了个在DataSet中创建DataRelations的作业。但是出了点问题,未将对象引用设置到对象实例。以下是代码

    using System;
    using System.Configuration;
    using System.Data;
    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.Text;
    using System.Data.SqlClient;
    
    public partial class _Default : System.Web.UI.Page
    {
      protected void Page_Load(object sender, EventArgs e)
      {
        if (!IsPostBack)
        {
          UpdateDetailsGrid();
    
          DataSet ds = CreateDateSet();
          GridView1.DataSource = ds.Tables[0];
          GridView1.DataBind();
    
          DataView detailsView = new DataView(ds.Tables[1]);
          DetailsGridView.DataSource = detailsView;
          Session["DetailsView"] = detailsView;
          DetailsGridView.DataBind();
    
          OrderRelationsGridView.DataSource = ds.Relations;
          OrderRelationsGridView.DataBind();
        }
      }
      protected void OnSelectedIndexChangedHandler(object sender, EventArgs e)
      {
        UpdateDetailsGrid();
      }
      private void UpdateDetailsGrid()
      {
        int index = GridView1.SelectedIndex;
        if (index != -1)
        {
          DataKey key = GridView1.DataKeys[index];
          int orderID = (int)key.Value;
          DataView detailsView = (DataView)Session["detailsView"];
          detailsView.RowFilter = "OrderID=" + orderID;
          DetailsGridView.DataSource = detailsView;
          DetailsGridView.DataBind();
          OrderDetailsPanel.Visible = true;
        }
        else
        {
          OrderDetailsPanel.Visible = false;
        }
      }
      private DataSet CreateDateSet()
      {
        string connectionString = "Data Source=刹那芳华-PC\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connectionString);
    
        conn.Open();
    
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
    
        StringBuilder s = new StringBuilder("select OrderID, c.CompanyName, c.ContactName, ");
        s.Append(" c.ContactTitle, c.Phone, OrderDate");
        s.Append(" from Orders o");
        s.Append(" join Customers c on c.CustomerID = o.CustomerID");
    
        cmd.CommandText = s.ToString();
    
        SqlDataAdapter dataAdapter = new SqlDataAdapter();
        dataAdapter.SelectCommand = cmd;
        dataAdapter.TableMappings.Add("Table", "Orders");
    
        DataSet datas = new DataSet();
        dataAdapter.Fill(datas);
    
        SqlCommand cmd2 = new SqlCommand();
        cmd2.Connection = conn;
    
        StringBuilder s2 = new StringBuilder("select od.OrderID,OrderDate,p.ProductID");
        s2.Append("ProductName,od.UnitPrice,Quantity");
        s2.Append("from Orders o ");
        s2.Append("join [Order Details] od on o.OrderID=od.OrderID");
        s2.Append("join Products p on p.ProductID=od.pPrudoctID");
    
        cmd2.CommandText = s2.ToString();
    
        SqlDataAdapter dataAdapter2 = new SqlDataAdapter();
        dataAdapter2.SelectCommand = cmd2;
        dataAdapter2.TableMappings.Add("Table", "Order Details");
        dataAdapter.Fill(datas);
    
        SqlCommand cmd3 = new SqlCommand();
        cmd3.Connection = conn;
    
        StringBuilder s3 = new StringBuilder("select ProductID,ProductName from Products");
    
        cmd3.CommandText = s3.ToString();
    
        SqlDataAdapter dataAdapter3 = new SqlDataAdapter();
        dataAdapter3.SelectCommand = cmd3;
        dataAdapter3.TableMappings.Add("Table", "Pruducts");
        dataAdapter.Fill(datas);
    
    
        DataColumn dataColumn1 = new DataColumn();
        DataColumn dataColumn2 = new DataColumn();
    
        dataColumn1 = datas.Tables["Orders"].Columns["OrderID"];
        dataColumn2 = datas.Tables["Order Details"].Columns["OrderID"];
    
        DataRelation dataRelation = new DataRelation("OrderToDetails", dataColumn1, dataColumn2);
    
        datas.Relations.Add(dataRelation);
    
        dataColumn1 = datas.Tables["Products"].Columns["ProductID"];
        dataColumn2 = datas.Tables["Order Details"].Columns["ProductID"];
    
        dataRelation = new DataRelation("ProductIDToName", dataColumn1, dataColumn2);
    
        datas.Relations.Add(dataRelation);
    
        return datas;
      }
    
    }
    
    

    然后是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>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
          OnSelectedIndexChanged="OnSelectedIndexChangedHandler" PageSize="5">
          <Columns>
            <asp:ButtonField ButtonType="Button" CommandName="Select" Text="明细" />
            <asp:BoundField DataField="OrderID" HeaderText="Order ID" />
            <asp:BoundField DataField="OrderDate" HeaderText="Order Date" />
            <asp:BoundField DataField="CompanyName" HeaderText="Company" />
            <asp:BoundField DataField="ContactTitle" HeaderText="Contact" />
            <asp:BoundField DataField="Phone" HeaderText="Phone" />
          </Columns>
        </asp:GridView>
        <br />
        <asp:Panel ID="OrderDetailsPanel" runat="server" Height="50px" Width="125">
          <asp:GridView ID="DetailsGridView" runat="server" AutoGenerateColumns="False" GridLines="None">
            <Columns>
              <asp:BoundField DataField="OrderDate" HeaderText="Order Date" />
              <asp:BoundField DataField="ProductName" HeaderText="Product" />
              <asp:BoundField DataField="UnitPrice" HeaderText="Price" />
              <asp:BoundField DataField="Quantity" HeaderText="Quantity" />
            </Columns>
          </asp:GridView>
        </asp:Panel>
        <br />
        <asp:GridView ID="OrderRelationsGridView" runat="server">
        </asp:GridView>
        <br />
      </div>
      </form>
    </body>
    </html>
    
    
    哪位好心的大大有空帮我解决一下,感激不尽

    2011年1月27日 3:23

答案

  • 你好,湛蓝星空

    欢迎来到MSDN中文论坛。

    对于你的问题,很普遍。我想原因有以下几个:

    1、ViewState 对象为Unll。
    2、DateSet 空。
    3、sql语句或Datebase的原因导致DataReader空。
    4、声明字符串变量时未赋空值就应用变量。
    5、未用new初始化对象。
    6、Session对象为空。
    7.变量命名与系统命名冲突了。
     
    结合你的实际情况来看,我想你应该检查一下
        cmd.CommandText = s.ToString();
        cmd2.CommandText = s2.ToString();
        cmd3.CommandText = s3.ToString();
    如果s,s2,或s3有一个是null的话,调用ToString()方法就有可能出现这种错误。
    你可以加个Try...catch...捕捉一下,或者加个if判断。
    例如:
    if(cmd.CommandText != null)
    {
         cmd.CommandText = s.ToString();
    }
    希望可以帮到你!
     
    谢谢,周末愉快!

    Jackie Sun [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年1月28日 9:44
    版主

全部回复

  • 你好,湛蓝星空

    欢迎来到MSDN中文论坛。

    对于你的问题,很普遍。我想原因有以下几个:

    1、ViewState 对象为Unll。
    2、DateSet 空。
    3、sql语句或Datebase的原因导致DataReader空。
    4、声明字符串变量时未赋空值就应用变量。
    5、未用new初始化对象。
    6、Session对象为空。
    7.变量命名与系统命名冲突了。
     
    结合你的实际情况来看,我想你应该检查一下
        cmd.CommandText = s.ToString();
        cmd2.CommandText = s2.ToString();
        cmd3.CommandText = s3.ToString();
    如果s,s2,或s3有一个是null的话,调用ToString()方法就有可能出现这种错误。
    你可以加个Try...catch...捕捉一下,或者加个if判断。
    例如:
    if(cmd.CommandText != null)
    {
         cmd.CommandText = s.ToString();
    }
    希望可以帮到你!
     
    谢谢,周末愉快!

    Jackie Sun [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年1月28日 9:44
    版主
  • 谢谢斑竹,问题已解决
    2011年2月9日 11:15