名为...的关系已属于此DataSet

时间:2014-04-08 06:21:03

标签: c#

我无法修复此错误,我得到A Relation named 'PlaneAirline' already belongs to this DataSet.我试图更改关系的名称,但我得到相同的错误 这是我的代码:

     private void getData()
    {
        SqlDataAdapter parentDataAdapter = new SqlDataAdapter("select * from Airline", connection);
        parentDataAdapter.Fill(ds, "Airline");
        SqlDataAdapter childDataAdapter = new SqlDataAdapter("select * from Plane", connection);
        childDataAdapter.Fill(ds, "Plane");

        DataColumn parentColumn = ds.Tables["Airline"].Columns["airline_id"];
        DataColumn childColumn = ds.Tables["Plane"].Columns["airline_id"];

        rel = new DataRelation("PlaneAirline", parentColumn, childColumn);
        ds.Relations.Add(rel);

        parentBindingSource.DataSource = ds;
        parentBindingSource.DataMember = "Airline";
        childBindingSource.DataSource = parentBindingSource;
        childBindingSource.DataMember = "PlaneAirline";
    }

    private void dg_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

   private void AirlineReservation_Load(object sender, EventArgs e)
        {
            parentDataGridView.DataSource = parentBindingSource;
            childDataGridView.DataSource = childBindingSource;
            getData();  
        }

你能帮我吗

2 个答案:

答案 0 :(得分:0)

在您的DataGrid中的每次点击(我假设dg_CellContentClick是数据网格单元格的点击处理程序)您正在调用getData,在那里您尝试添加关系PlaneAirline一遍又一遍。

尝试移动线

        rel = new DataRelation("PlaneAirline", parentColumn, childColumn);
        ds.Relations.Add(rel);

到最初创建或定义变量ds的位置(我认为它是一个数据集)。

答案 1 :(得分:0)

我认为您的问题是您在GetData()事件上调用了CellContentClick方法。此事件将被触发when the content within a cell is clicked.因此,无论何时单击单元格,您的代码都会尝试添加第一次单击单元格时已存在的关系。

您可能需要按照您提供的教程中的说明将GetData()电话移至Form Load

希望这有帮助。