Oh dear ! No need to write 720
if else conditions. Only a single line of code can do the same job. A small trick to be implemented using logical OR operator.
query="select * from table1 where ('"+txt1.Text+"'='' OR col1='"+txt1.Text+"') and ('"+txt2.Text+"'='' OR col2='"+txt2.Text+"') and ('"+txt3.Text+"'='' OR col3='"+txt3.Text+"') and ('"+txt4.Text+"'='' OR col4='"+txt4.Text+"') and ('"+txt5.Text+"'='' OR col5='"+txt5.Text+"') and ('"+txt6.Text+"'='' OR col6='"+txt6.Text+"')";
Don't put any
if else condition around this.
Hopefully, I have saved your time wasting in writing
if else conditions.
In case you want to use this in a stored procedure, you can check my blog post on
SQL Server: An optimal way to create procedure with multiple optional parameters[
^]
In case this doesn't help, please let me know :)
Update (Preventing SQL Injection)
As @CHill60 suggested, you should consider improving your querying method to prevent SQL Injection. Either convert it to a stored procedure or following parametrized query may help.
query="select * from table1 where (@txt1='' OR col1=@txt1) and (@txt2='' OR col2=@txt2) and (@txt3='' OR col3=@txt3) and (@txt4='' OR col4=@txt4) and (@txt5='' OR col5=@txt5) and (@txt6='' OR col6=@txt6)";
cmd.Parameters.AddWithValue("@txt1", txt1.Text.Trim());
cmd.Parameters.AddWithValue("@txt2", txt2.Text.Trim());
cmd.Parameters.AddWithValue("@txt3", txt3.Text.Trim());
cmd.Parameters.AddWithValue("@txt4", txt4.Text.Trim());
cmd.Parameters.AddWithValue("@txt5", txt5.Text.Trim());
cmd.Parameters.AddWithValue("@txt6", txt6.Text.Trim());
:)