I have beginner question, how to "reduce" multiple if statements
using whlie or foreach or any other means, i have like 10 if statements.
Example

Boolean bolres = true;
 if (client_name == "")  //testing for empty string
            {
                bolres = false;  //if its empty set the bolres variable to false 
             }
                if (clientlastname == "")
                {
                    bolres = false;
                }

                 if (clientage =="")
                 {
                        bolres = false;
                 }

If client_name, clientlastname, and clientage are all locally declared variables then you don't really have much of a choice. If you stored them in a class you have a lot more options. You could do something like...

string s1 = string.Empty;
      string s2 = string.Empty;
      string s3 = string.Empty;
      bool bRes = string.IsNullOrEmpty(s1) || string.IsNullOrEmpty(s2) || string.IsNullOrEmpty(s3);

This is part of my BLL(Business logic layer) class and is rule-check to find if that field is empty or not.

Can i use arraylist or something like that?

This is actually a very similar question to one I answered earlier:
http://www.daniweb.com/forums/thread203538.html

I would use reflection for this. I had to remove a lot of code to get this to compile and change around the methods but here is an example. Here are the base classes to make this work:

Stuff this in one file named SqlObject.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;

namespace daniweb
{
  public enum RecordState { New, Existing, Deleted }


  public sealed class DataParameter
  {
    public string ParamName { get; set; }
    public object ParamType { get; set; }
    public object ParamValue { get; set; }

    public DataParameter()
      : this(string.Empty, default(object), default(object))
    {
    }

    public DataParameter(string ParameterName, object ParameterType, object ParameterValue)
    {
      ParamName = ParameterName;
      ParamType = ParameterType;
      ParamValue = ParameterValue;
    }
  }






  public abstract class SqlObject
  {
    /* -------------------------------------------------------------------- */
    protected SqlObject() { }
    private RecordState _recordState = RecordState.New;
    public RecordState RecordState { get { return _recordState; } }
    /* -------------------------------------------------------------------- */
    internal const BindingFlags SqlObjectBindingFlags = BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic;
    internal static DBFieldInfo GetDBFieldInfo(FieldInfo Field)
    {
      Attribute[] attrs = System.Attribute.GetCustomAttributes(Field);
      foreach (Attribute at in attrs)
      {
        DBFieldInfo fieldInfo = (at as DBFieldInfo);
        if (fieldInfo != null)
          return fieldInfo;
      }
      return null;
    }
    internal DBTableInfo GetDBTableInfo()
    {
      AttributeCollection attrs = TypeDescriptor.GetAttributes(this);
      foreach (Attribute at in attrs)
      {
        DBTableInfo tableInfo = (at as DBTableInfo);
        if (tableInfo != null)
        {
          return tableInfo;
        }
      }
      throw new InvalidOperationException("Table not defined");
    }
    internal List<DBChildTableInfo> GetDBChildTableInfo()
    {
      List<DBChildTableInfo> result = new List<DBChildTableInfo>();
      AttributeCollection attrs = TypeDescriptor.GetAttributes(this);
      foreach (Attribute at in attrs)
      {
        DBChildTableInfo childTableInfo = (at as DBChildTableInfo);
        if (childTableInfo != null)
        {
          result.Add(childTableInfo);
        }
      }
      return result;
    }
    internal DataParameter GetParameter(FieldInfo Field, DBFieldInfo FieldInfo)
    {
      object value = Field.GetValue(this);
      if (value == null)
        value = DBNull.Value;
      return new DataParameter("@" + FieldInfo.FieldName, FieldInfo.DataType, value);
    }
    internal List<DataParameter> GetParameters()
    {
      List<DataParameter> result = new List<DataParameter>();
      foreach (FieldPair fp in GetFieldPairs())
      {
        result.Add(GetParameter(fp.FI, fp.DbFi));
      }
      return result;
    }
    internal FieldPair GetPrimaryKeyFieldPair()
    {
      foreach (FieldPair fp in GetFieldPairs())
      {
        if (fp.DbFi.PrimaryKey)
          return fp;
      }
      throw new InvalidOperationException("No primary key defined");
    }
    internal void Deserialize(DataTable dt)
    {
      if ((dt == null) || (dt.Rows.Count == 0) || (dt.Columns.Count == 0))
      {
        //If you have arrive here then your INSERT/UPDATE queries probably do not have a trailing SELECT statement.
        throw new InvalidOperationException(string.Format("{0} cannot deserialze from an empty DataTable.", this.GetType()));
      }

      DataRow row = dt.Rows[0];
      foreach (FieldPair fp in GetFieldPairs())
      {
        foreach (DataColumn dc in dt.Columns)
        {
          if (string.Compare(fp.DbFi.FieldName, dc.ColumnName, true) == 0)
          {
            if (row[dc.ColumnName] == DBNull.Value)
              break;

            if ((fp.FI.FieldType != null) && (fp.FI.FieldType.BaseType != null) && (fp.FI.FieldType.BaseType == typeof(Enum))) //Handling ENUM
            {
              try
              {
                /*
                 * If an ENUM fails to parse it will default to the first value.
                 * I hope whatever enum this is has an UNKNOWN defined in the first ordinal position :)
                 * 
                 * Audit: This should probably use GetEnumFromDescription() so ENUM's could be 
                 * abbreviated in to the DB, f.ex. CHAR(1)
                 */
                fp.FI.SetValue(this, Enum.Parse(fp.FI.FieldType, Convert.ToString(row[dc.ColumnName])));
              }
              catch
              {
#if (DEBUG)
                throw;
#endif
              }
            }
            else
            {
              fp.FI.SetValue(this, row[dc.ColumnName]);
            }

          }
        }
      }
      _recordState = RecordState.Existing;
    }
    internal DataTable Serialize()
    {
      string query = null;
      switch (RecordState)
      {
        case RecordState.New:
          query = InsertQuery;
          break;
        case RecordState.Existing:
          query = UpdateQuery;
          break;
        default:
          throw new InvalidEnumArgumentException("RecordState", (int)RecordState, RecordState.GetType());
      }
      List<DataParameter> Parameters = GetParameters();
      //DataTable result = SQL.Main.QueryDataTable(query, Parameters);
      //return result;
      return new DataTable(); //to make it compile
    }
    internal void Delete(DataParameter dp)
    {
      string query = DeleteQuery;
      //SQL.Main.Execute(query, dp);
      _recordState = RecordState.Deleted;
    }
    internal List<FieldPair> GetFieldPairs()
    {
      List<FieldPair> result = new List<FieldPair>();
      FieldInfo[] fields = this.GetType().GetFields(SqlObjectBindingFlags);
      foreach (FieldInfo field in fields)
      {
        DBFieldInfo fieldInfo = GetDBFieldInfo(field);
        if (fieldInfo != null)
        {
          result.Add(new FieldPair(field, fieldInfo));
        }
      }
      return result;
    }
    /* -------------------------------------------------------------------- */
    protected virtual void Delete(object PrimaryKeyValue)
    {
      DataParameter dp = GetPrimaryKey();
      dp.ParamValue = PrimaryKeyValue;
      Delete(dp);
    }
    protected bool Fetch(object Identifier)
    {
      bool result = false;
      string query = SelectQuery;
      DataParameter dp = GetPrimaryKey();
      if (dp == null)
        throw new InvalidConstraintException(string.Format("No primary key exists for {0}", this.GetType()));
      dp.ParamValue = Identifier; //this is a constructor, have to use the identifier provided
      //using (DataTable dt = SQL.Main.QueryDataTable(query, dp))
      using (DataTable dt = new DataTable()) //to make it compile
      {
        if ((dt == null) || (dt.Rows.Count == 0) || (dt.Columns.Count == 0))
        {
          result = false;
        }
        else
        {
          Deserialize(dt);
          result = true;
        }
        dt.Clear();
        dt.Dispose();
      }
      return result;
    }
    public DataParameter GetPrimaryKey()
    {
      FieldPair fp = GetPrimaryKeyFieldPair();
      return GetParameter(fp.FI, fp.DbFi);
    }
    public void Save()
    {
      DataTable dt = Serialize();
      Deserialize(dt);
    }
    public virtual VerificationResult CanSave()
    {
      VerificationResult result = null;
      foreach (FieldPair fp in GetFieldPairs())
      {
        if (IsStringDataType(fp.DbFi))
        {
          result = VerifyStringField(fp.FI, fp.DbFi);
        }
        else if (IsDateTimeDataType(fp.DbFi))
        {
          result = VerifyDateTimeField(fp.FI, fp.DbFi);
        }

        if ((result == null) && (fp.DbFi.Unique))
          result = IsUnique(fp.FI, fp.DbFi);

        if (result != null)
          break;
      }
      return result;
    }
    /// <summary>
    /// Returns the number of records in the underlying SQL table
    /// </summary>
    /// <returns></returns>
    public virtual int GetSqlTableRecordCount()
    {
      const string baseQuery = "Select Count(*) As Cnt From {0} (NOLOCK)";
      string query = string.Format(baseQuery, GetDBTableInfo().TableName);
      //return SQL.Main.QueryInt(query);
      return default(int); //to make it compile
    }
    /* -------------------------------------------------------------------- */
    #region verification stuff
    internal VerificationResult IsUnique(FieldInfo field, DBFieldInfo fieldInfo)
    {
      DBTableInfo tableInfo = GetDBTableInfo();
      if (tableInfo == null)
        throw new InvalidOperationException(this.GetType().Name + " is not configured with DBTableInfo");
      DataParameter dpKey = GetPrimaryKey();
      if (dpKey == null)
        throw new InvalidOperationException(this.GetType().Name + " is not configured with primary key");

      string keyName = dpKey.ParamName.Replace("@", string.Empty);

      string searchCol = fieldInfo.FieldName;
      DataParameter searchValue = GetParameter(field, fieldInfo);

      string query = string.Format("Select Count(*) As Count From {0} (NOLOCK) Where {1} <> {2} and {3} = {4}",
        tableInfo.TableName, // 0 - table name
        keyName,             // 1 - key column name
        dpKey.ParamName,     // 2 - key param name
        searchCol,           // 3 - col name
        searchValue.ParamName);  //4 col param  

      List<DataParameter> lst = new List<DataParameter>();
      lst.Add(dpKey);
      lst.Add(searchValue);

      VerificationResult result = null;
      //int cnt = SQL.Main.QueryInt(query, lst);
      int cnt = default(int);
      if (cnt > 0)
      {
        result = new VerificationResult();
        result.FieldName = fieldInfo.FieldName;
        result.FieldValue = Convert.ToString(searchValue.ParamValue);
        result.Message = string.Format("{0} '{1}' is already in use.", result.FieldName, result.FieldValue);
      }

      return result;
    }
    /* -------------------------------------------------------------------- */
    #region string field verification
    internal static bool IsStringDataType(FieldInfo Field)
    {
      DBFieldInfo info = GetDBFieldInfo(Field);
      return IsStringDataType(info);
    }
    internal static bool IsStringDataType(DBFieldInfo Info)
    {
      if (Info == null)
        return false;
      else
        return ((Info.DataType == SqlDbType.Char) || (Info.DataType == SqlDbType.NChar) ||
                (Info.DataType == SqlDbType.NVarChar) || (Info.DataType == SqlDbType.VarChar));
    }
    internal VerificationResult VerifyStringField(FieldInfo Field, DBFieldInfo Info)
    {
      if (Info == null)
        Info = GetDBFieldInfo(Field);
      if (Info == null)
        return null; //Does not have a DBFieldInfo attribute. NULL means OK
      if (!IsStringDataType(Info))
        throw new InvalidOperationException(string.Format("{0} is not a string field.", Info.FieldName));
      if (Info.Size == 0)
        return null;
      VerificationResult result = null;

      string value = Convert.ToString(Field.GetValue(this));
      if (value == null)
        value = string.Empty;

      if (Info.Required && (string.IsNullOrEmpty(value.Trim())))
      {
        result = new VerificationResult();
        result.FieldName = Info.FieldName;
        result.FieldValue = value;
        result.MaxLength = Info.Size;
        result.Message = string.Format("{0} is a required field", result.FieldName);
      }
      else if (value.Length > Info.Size)
      {
        if (string.Compare(Info.FieldName, "password", true) == 0)
        {
          result = new VerificationResult();
          result.FieldName = Info.FieldName;
          result.FieldValue = value;
          result.MaxLength = Info.Size;
          result.Message = "Password is too long.";
        }
        else
        {
          result = new VerificationResult();
          result.FieldName = Info.FieldName;
          result.FieldValue = value;
          result.MaxLength = Info.Size;
          result.Message = string.Format("Field {0} exceeds the maximum length of {1} characters: '{2}'.", result.FieldName,
            result.MaxLength, value);
        }
      }
      return result;
    }
    internal VerificationResult VerifyStringField(FieldInfo Field)
    {
      return VerifyStringField(Field, null);
    }
    #endregion
    /* -------------------------------------------------------------------- */
    #region date field verification
    internal static bool IsDateTimeDataType(DBFieldInfo Info)
    {
      if (Info == null)
        return false;
      else
        return ((Info.DataType == SqlDbType.DateTime));
    }
    internal VerificationResult VerifyDateTimeField(FieldInfo Field, DBFieldInfo Info)
    {
      if (Info == null)
        Info = GetDBFieldInfo(Field);
      if (Info == null)
        return null; //Does not have a DBFieldInfo attribute. NULL means OK
      if (!IsDateTimeDataType(Info))
        throw new InvalidOperationException(string.Format("{0} is not a DateTime field.", Field.Name));

      VerificationResult result = null;

      DateTime value = (DateTime)Field.GetValue(this);

      if (Info.Required && ((value == DateTime.MinValue) || (value == DateTime.MaxValue)))
      {
        result = new VerificationResult();
        result.FieldName = Info.FieldName;
        result.FieldValue = value.ToString();
        result.Message = string.Format("{0} is a required field", result.FieldName);
      }
      else if ((value < System.Data.SqlTypes.SqlDateTime.MinValue.Value) ||
          (value > System.Data.SqlTypes.SqlDateTime.MaxValue.Value))
      {
        result = new VerificationResult();
        result.FieldName = Info.FieldName;
        result.FieldValue = value.ToString();
        result.Message = string.Format("Field {0} is out of the valid range for date/time values: {1}",
          result.FieldName, result.FieldValue);
      }

      return result;
    }
    protected VerificationResult VerifyDateTimeField(FieldInfo Field)
    {
      return VerifyDateTimeField(Field, null);
    }
    #endregion
    #endregion
    /* -------------------------------------------------------------------- */
    #region query stuff
    private bool _selectQueryGenerated = false;
    private bool _insertQueryGenerated = false;
    private bool _deleteQueryGenerated = false;
    private bool _updateQueryGenerated = false;
    private string _selectQuery;
    private string _insertQuery;
    private string _deleteQuery;
    private string _updateQuery;
    protected virtual string SelectQuery
    {
      //FYI this is a bad idea. If you hold your cursor over the
      //property in design time before the query is generated then it
      //will generate the query but not set the value so it will break
      //until you re-run the application.
      get
      {
        if (!_selectQueryGenerated)
        {
          _selectQuery = GenerateSelectQuery();
          _selectQueryGenerated = true;
        }
        return _selectQuery;
      }
    }
    protected virtual string InsertQuery
    {
      //FYI this is a bad idea. If you hold your cursor over the
      //property in design time before the query is generated then it
      //will generate the query but not set the value so it will break
      //until you re-run the application.
      get
      {
        if (!_insertQueryGenerated)
        {
          _insertQuery = GenerateInsertQuery();
          _insertQueryGenerated = true;
        }
        return _insertQuery;
      }
    }
    protected virtual string UpdateQuery
    {
      //FYI this is a bad idea. If you hold your cursor over the
      //property in design time before the query is generated then it
      //will generate the query but not set the value so it will break
      //until you re-run the application.
      get
      {
        if (!_updateQueryGenerated)
        {
          _updateQuery = GenerateUpdateQuery();
          _insertQueryGenerated = true;
        }
        return _updateQuery;
      }
    }
    protected virtual string DeleteQuery
    {
      //FYI this is a bad idea. If you hold your cursor over the
      //property in design time before the query is generated then it
      //will generate the query but not set the value so it will break
      //until you re-run the application.
      get
      {
        if (!_deleteQueryGenerated)
        {
          _deleteQuery = GenerateDeleteQuery();
          _deleteQueryGenerated = true;
        }
        return _deleteQuery;
      }
    }
    private string GenerateInsertQuery()
    {
      return string.Empty;
    }
    private string GenerateSelectQuery()
    {
      return string.Empty;
    }
    private string GenerateDeleteQuery()
    {
      return string.Empty;
    }
    private string GenerateUpdateQuery()
    {
      return string.Empty;
    }
    #endregion
    /* -------------------------------------------------------------------- */
  }

















  [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
  internal sealed class DBFieldInfo : Attribute
  {
    private string _fieldName;
    private bool _primaryKey;
    private SqlDbType _dataType;
    private int _size;
    private bool _required = false;
    private bool _unique = false;
    private bool _identity = false;
    public DBFieldInfo(string FieldName, SqlDbType DataType)
    {
      _fieldName = FieldName;
      _dataType = DataType;
      _primaryKey = false;
      _size = 0;
      _required = false;
      _identity = false;
    }
    public string FieldName
    {
      get { return _fieldName; }
    }
    public bool PrimaryKey
    {
      get { return _primaryKey; }
      set { _primaryKey = value; }
    }
    public SqlDbType DataType
    {
      get { return _dataType; }
    }
    public int Size
    {
      get { return _size; }
      set { _size = value; }
    }
    public bool Required
    {
      get { return (_required || _unique); }
      set { _required = value; }
    }
    public bool Unique
    {
      get { return _unique; }
      set { _unique = value; }
    }
    public bool Identity
    {
      get { return _identity; }
      set { _identity = value; }
    }
  }

  [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
  internal sealed class DBTableInfo : Attribute
  {
    private string _tableName;
    /// <summary>
    /// Marks the SQL table a business object serializes with
    /// </summary>
    /// <param name="TableName">SQL Table Name</param>
    public DBTableInfo(string TableName)
    {
      _tableName = TableName;
    }
    /// <summary>
    /// SQL Table Name
    /// </summary>
    public string TableName
    {
      get { return _tableName; }
    }
  }

  [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
  internal sealed class DBChildTableInfo : Attribute
  {
    //Required for AllowMultiple=True
    public override object TypeId { get { return this; } }
    private string _tableName;
    private string _columnName;
    /// <summary>
    /// Marks the SQL table a business object serializes with
    /// </summary>
    /// <param name="TableName">SQL Table Name</param>
    public DBChildTableInfo(string TableName)
    {
      _tableName = TableName;
      _columnName = string.Empty;
    }
    /// <summary>
    /// Marks the SQL table a business object serializes with
    /// </summary>
    /// <param name="TableName">SQL Table Name</param>
    public DBChildTableInfo(string TableName, string ColumnName)
      : this(TableName)
    {
      _columnName = ColumnName;
    }
    /// <summary>
    /// SQL Table Name
    /// </summary>
    public string TableName
    {
      get { return _tableName; }
    }
    public string ColumnName
    {
      get { return _columnName; }
    }
  }

  public sealed class VerificationResult
  {
    public VerificationResult() { }
    public string FieldName { get; set; }
    public string FieldValue { get; set; }
    public int MaxLength { get; set; }
    public string Message { get; set; }
  }

  internal sealed class FieldPair
  {
    private FieldInfo _fi;
    private DBFieldInfo _dbfi;
    private FieldPair()
    {
    }
    public FieldPair(FieldInfo fi, DBFieldInfo dbfi)
      : this()
    {
      _fi = fi;
      _dbfi = dbfi;
    }
    public FieldInfo FI { get { return _fi; } }
    public DBFieldInfo DbFi { get { return _dbfi; } }
  }




}

Now your BLL item would look like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace daniweb
{
  [DBTableInfo("MyTable")]
  public sealed class BLL : SqlObject
  {
    
    [DBFieldInfo("NonEmptyField", System.Data.SqlDbType.VarChar, Size = 15, Required=true)]
    private string _NonEmptyField;

    public string NonEmptyField
    {
      get { return _NonEmptyField; }
      set { _NonEmptyField = value; }
    }
  }
}

And you would call it doing:

private void button3_Click(object sender, EventArgs e)
    {
      BLL bll = new BLL();
      bll.NonEmptyField = string.Empty;
      VerificationResult res = bll.CanSave();
      if (res != null)
        MessageBox.Show(res.Message);
      else
      {
        //normally you could save here
      }
    }

This handles making sure fields are unique in MSSQL, getting back auto increment values, and a variety of other things. I would just use this as an example since a lot of the required code has been deleted it would be unstable.

Thanks for the effort.

Is that not what you are looking for? Attributes and reflection give you a lot more power/flexibility in a BLL than having plain old fields where you can iterate values.

commented: Did you got that word? - Thanks for the effort. +7
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.