Posted By

emregulcan on 05/11/11


Tagged

sql c exists SqlDataReader column datareader


Versions (?)

Check SqlDataReader Column Is Exists (extension method)


 / Published in: C#
 

This snippet is "extension method" for IDataReader. You can use this snippet below ; I assume you have datareader like that SqlDataReader dataReader = command.ExecuteReader();

if (dataReader.IsColumnExists("columnName")) { //do something }

and also you should validation null value control if you work critical datas

if (dataReader.IsColumnExists("columName")) { if (dataReader["columName"] != DBNull.Value) { //do something } }

  1. public static bool IsColumnExists(this IDataReader dataReader, string columnName)
  2. {
  3. bool retVal = false;
  4.  
  5. try
  6. {
  7. dataReader.GetSchemaTable().DefaultView.RowFilter = string.Format("ColumnName= '{0}'", columnName);
  8. if (dataReader.GetSchemaTable().DefaultView.Count > 0)
  9. {
  10. retVal = true;
  11. }
  12. }
  13.  
  14. catch (Exception ex)
  15. {
  16.  
  17. throw;
  18. }
  19.  
  20. return retVal;
  21. }

Report this snippet  

You need to login to post a comment.