Find a value in a DataTable and return an associated value.

public object LookUpData(Data.DataTable TheTable, string SearchColumnName, object TheValue, string ResultColumnName)
{
 object ReturnValue = null;
 string RowFilterString = string.Format("Convert([{0}], 'System.String') = '{1}'", SearchColumnName, TheValue.ToString);
 if (TheTable.Columns.Contains(SearchColumnName)) {
  if (TheTable.Columns.Contains(ResultColumnName)) {
   Data.DataView TheDataView = new Data.DataView(TheTable, RowFilterString, "", Data.DataViewRowState.CurrentRows);
   Data.DataTable NewTable = TheDataView.ToTable;
   //Only Return data when there is just 1 result.
   if (NewTable.Rows.Count == 1) {
    ReturnValue = NewTable.Rows(0).Item(ResultColumnName);
   }
   if (object.ReferenceEquals(ReturnValue, DBNull.Value)) {
    ReturnValue = null;
   }
  }
 }
 return ReturnValue;
}

No comments:

Post a Comment