SkylineGodzilla SkylineGodzilla - 28 days ago 13
C# Question

"Safely" Find row in data table with specific field value

I'm trying to get a row by using a value from an non pk field "safely"
I can get it to work however I wanted to do it using try and catch so that if the field names does not exist or it can not find any rows with the value it won't crash the app.

However this in turn stuffs up the method as it now states that all pathways don't return a value.

Here is my code:

private DataRow getRowByFieldVal(DataSet DtaSet, string sorceTable, string fieldName, string fieldValue)
{
try
{
DataRow[] foundRows = DtaSet.Tables[sorceTable].Select(fieldName + " = " + fieldValue);
return foundRows[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Answer

Compiler is asking What do you want to return if there is error in try block?

Imagine a use case.

There is some error in try block so catch starts executing, but since this function has to return something. So what to return in that case. Will it be null or throw exception using throw.

So you can do

catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
    return null; //Add this line.
}