Jason Hao
Jason Hao

Reputation: 217

How could I know the column name?

I have the code below, I was asked to use the column name instead of index in the foreach part. my question is, is that possible know the dtGDIrow table columns' name from the code below? Thanks!

private string UploadSummaryDatatoSQLTable(List<FinGrowthIndexSummary> lstGISum, string sqlTableName) {
        int _GDI_SUMMARY_COLS = 16;

        DataTable dtGDIrow = new DataTable();

        DataColumn idcol = new DataColumn();
        idcol.AllowDBNull = true;
        dtGDIrow.Columns.Add(idcol);

        DataColumn dateCol = new DataColumn();
        idcol.AllowDBNull = true;
        dtGDIrow.Columns.Add(dateCol);

        for (int i = 0; i < _GDI_SUMMARY_COLS; i++) {
            // GDI type
            DataColumn gdifield = new DataColumn();
            idcol.AllowDBNull = true;
            dtGDIrow.Columns.Add(gdifield);
        }

        foreach (var selcol in lstGISum) {
            DataRow row = dtGDIrow.NewRow();
            row[0] = 1;

            row[1] = selcol.SummaryDate;
            row[2] = selcol.Description;
            ....
            row[16] = selcol.CommodityExcess;
            row[17] = selcol.Overall;

            dtGDIrow.Rows.Add(row);
        }
    }

Upvotes: 0

Views: 81

Answers (1)

Nenad Zivkovic
Nenad Zivkovic

Reputation: 18559

Since you are creating dtGDIrow data table, you should assign column names while doing it, like:

DataColumn idcol = new DataColumn("idCol");
DataColumn dateCol = new DataColumn("dateCol");

and while you are at it, you might as well assign a proper data types to them, so not all columns would default to String:

DataColumn idcol = new DataColumn("idCol", System.Type.GetType("System.Int32"));
DataColumn dateCol = new DataColumn("dateCol", System.Type.GetType("System.DateTime"));

and when you come to use those columns, refer them by name:

row["idCol"] = 1; 
row["dateCol"] = selcol.SummaryDate;

In foreach part, you have to come with some naming logic on your own.

Upvotes: 1

Related Questions