如何将一个数据表中的某些列添加到另一个数据表?

时间:2016-08-10 08:33:45

标签: c# mysql winforms datatable

我有带有productID,productName和productPrice列的数据表dt1,带有orderID,productID,productName,productPrice和totalPrice的dt2。如何在输入productID时将dt1信息输入dt2?

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解正确,我怎么读它你想在c#datatable中使用JOIN函数。这是很久以前的事情所以我认为有更好的方法......

    /// <summary>
    /// Give a Table that contains the foreignkeys it returns a Table with a Description instead of the Key
    /// The ID in the source has to be Column[0]
    /// </summary>
    /// <param name="foreignkeys">Foreignkey in you Table</param>
    /// <param name="source">The Table the foreignkey refers to</param>
    /// <param name="_foreigncolumn">Header of Foreignkeycolumn</param>
    /// <param name="_sourcecolumn">Header description column in source Table</param>
    /// <returns></returns>
    public DataTable getDatabyForeignKey(DataTable foreignkeys, DataTable source, string _foreigncolumn, string _sourcecolumn)
    {
        try
        {
            DataTable displayname = new DataTable();
            displayname.Columns.Add("ID");
            //Maybe change that to a parameter as well (amount + header)
            displayname.Columns.Add("Description");

            for (int i = 0; i < foreignkeys.Rows.Count; i++)
            {
                for (int j = 0; j < source.Rows.Count; j++)
                {
                    string s = source.Rows[j][0].ToString();
                    string ss = foreignkeys.Rows[i][_foreigncolumn].ToString();
                    if (source.Rows[j][0].ToString() == foreignkeys.Rows[i][_foreigncolumn].ToString())
                    {
                        foreignkeys.Rows[i][_foreigncolumn] = source.Rows[j][_sourcecolumn];
                    }
                }

            }
        }
        catch (Exception)
        {
            MessageBox.Show(ex.Message);               
        }

        return foreignkeys;
    }