0

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;
}
DubDub
  • 1,277
  • 1
  • 10
  • 24
  • What kind of exception do you get ? – Eugene Oct 05 '18 at 14:08
  • _Some exception_?? Really, that is not a helpful problem description. And how would you expect to find a column from contetn to be reliable in the first place?? Also: Please post only real code, i.e. code without typos! – TaW Oct 05 '18 at 14:09
  • Have a feeling this is VBA and not C#. Depending on the exception of course, I think there is three possible problems you have. – DubDub Oct 05 '18 at 14:12
  • "Sequence contains no matching element"...This is the exception i'm getting – Chandrashekhar M Oct 05 '18 at 14:16
  • Instead of using `First` you should use [`FirstOrDefault`](https://stackoverflow.com/questions/1024559) (or check beforehand with `Any`). – Elaskanator Oct 05 '18 at 16:57
  • Thank You - Elaskanator . Any function is working – Chandrashekhar M Oct 11 '18 at 06:21

1 Answers1

0

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;
}
Jeff R.
  • 1,493
  • 1
  • 10
  • 14