简体   繁体   中英

C# - How can I check if it is Column 0 in the datatable?

I have a data table that I am creating from an excel file. This works fine. But, I recently had a spec change and need to substitute a value in column 0 of the table. I am having trouble getting my IF statement to fire. It is probably something simple I am overlooking.

Basically, if it is the first column in the row, I want to put a specific value I pulled elsewhere (I am pulling the color of the cell and putting in the RGB value). If it is any other column in the row, continue to read in the data as usual. Please see the below code:

DataTable tbl = new DataTable();

foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
    tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
    //var cellColor = ws.Cells[firstRowCell].Style.Fill.BackgroundColor.LookupColor();
}

//var startRow = hasHeader ? 2 : 1;
for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
    var currentRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
    DataRow row = tbl.Rows.Add();
    for (var i = 0; i < tbl.Columns.Count; i++)
    {
        //This is my problem. I am not seeing what needs to be in here.  
        if (tbl.Columns.????????)
        {
            row[i] = colorTable[rowNum];
        }
        else
        {
            row[i] = currentRow[rowNum, i + 1].Text;
        }
    }
}

You're in a for loop that starts at your first column to the last

for (var i = 0; i < tbl.Columns.Count; i++)

So the value you can use to know at what column you're at would be the i , you could have something like this

for (var i = 0; i < tbl.Columns.Count; i++)
{
    //If you're at the first column 
    if (i == 0)
    {
        row[i] = colorTable[rowNum];
    }
    else
    {
        row[i] = currentRow[rowNum, i + 1].Text;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM