Search code examples
c#worksheet

I want to find the column index using Column data


I'm trying to get the column index using the column name, but if I enter a column name which is not in the dataset then I get an exception. How do I handle this?

string columnName ="ABC";

int ColumnNumber-0;

if(ws.Cells["1:1"].First(c => c.Value.ToString() == columnName ).Start.Column!=Undefined)
{
    ColumnNumber=ws.Cells["1:1"].First(c => c.Value.ToString() == columnName ).Start.Column;
}

Solution

  • The most likely candidate for the exception is your call to First. It is not finding any items that match Value == columnName and throwing an exception. I would suggest breaking up your if statement so you can handle this case. I would also suggest using FirstOrDefault instead since it will just return null instead of throwing an exception.

    var myCell = ws.Cells["1:1"].FirstOrDefault(c => c.Value.ToString() == columnName );
    if (myCell != null && myCell.Start.Column != Undefined)
    {
        ColumnNumber = myCell.Start.Column;
    }