none
how to use one column data and use it as columns of another table c# RRS feed

All replies

  • Hi NimzJay,

    You could create a loop for inserting the values of one column, like this:

    //first table
                DataTable dt_sn = new DataTable();
                //add columns
                dt_sn.Columns.Add("id");
                dt_sn.Columns.Add("name");
                //add rows
                DataRow dr_sn = dt_sn.NewRow();
                dr_sn["id"] = "1";
                dr_sn["name"] = "Test1";
                dt_sn.Rows.Add(dr_sn);
    
    
                //add rows
                DataRow dr2 = dt_sn.NewRow();
                dr2["id"] = "5";
                dr2["name"] = "Test2";
                dt_sn.Rows.Add(dr2);
    
                //table name
                dt_sn.TableName = "SN";
    
                //second talbe
                DataTable dt_te = new DataTable();
                //table
                dt_te.TableName = "Te";
                //add columns
                dt_te.Columns.Add("id");
                dt_te.Columns.Add("name");
    
                int i = 1;
                foreach (DataRow dr in dt_sn.Rows)
                {
                    DataRow dr_te = dt_te.NewRow();
                    dr_te["id"] = i;
                    dr_te["name"] = dr["name"];
                    dt_te.Rows.Add(dr_te);
                    i++;
                }

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, April 6, 2017 6:19 AM
    Moderator
  • Are you asking if you can use the value of a column as a column name in another table?

    If so, try something like this:

    // Say you have these two DataTables
    DataTable dtForColumnNames = new DataTable();
    DataTable dtToCreateNewColumns = new DataTable();
    
    // Code here to fill your first table, dtForColumnNames, with data
    // ...
    
    // Then create a new column in the second table from rows in the first table
    foreach (DataRow row in dtForColumnNames.Rows)
    {
        dtToCreateNewColumns.Columns.Add(row["NewColumnName"].ToString());
    }
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Saturday, April 8, 2017 1:39 AM