now i use thx code to make the filter in datagridview i want to add 2 textbox to make a filter between age like between 20 and 30 how i can do that i try muny thing bout it didn't work with me
private void Button1_Click(object sender, EventArgs e)
{
SqlCommand selectCommand = new SqlCommand();
var filterConditions = new[] {
CreateSqlFilter("Name_Arabic", txtName_Arabic, selectCommand, false),
CreateSqlFilter("gender", CBgender, selectCommand, false),
CreateSqlFilter("CIVILIDD", txtCIVILIDD, selectCommand, true),
CreateSqlFilter("status", comboBox1, selectCommand, false),
CreateSqlFilter("username", txtusername, selectCommand, false),
CreateSqlFilter("City", comboBoxCity, selectCommand, false),
CreateSqlFilter("Governorate", comboBoxGovernorate, selectCommand, false),
CreateSqlFilter("confirmation", comboBox2, selectCommand, false),
CreateSqlFilter("NATIONALITY", CBNATIONALITY, selectCommand, false)
};
string filterCondition = filterConditions.Any(a => a != null) ? filterConditions.Where(a => a != null).Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2)) : (string)null;
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["my"].ConnectionString))
{
selectCommand.Connection = connection;
selectCommand.CommandText = filterCondition == null ? "SELECT * FROM tabl2" : "SELECT * FROM tabl2 WHERE " + filterCondition;
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
DataTable dataSource = new DataTable();
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
private string CreateSqlFilter(string fieldName, Control userInputControl, SqlCommand command, bool exactMatch)
{
string searchValue = null;
if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
if (String.IsNullOrWhiteSpace(searchValue)) return null;
if (exactMatch)
{
command.Parameters.Add(new SqlParameter("@" + fieldName, searchValue));
return fieldName + " = @" + fieldName;
}
else
{
command.Parameters.Add(new SqlParameter("@" + fieldName, "%" + searchValue + "%"));
return fieldName + " LIKE @" + fieldName;
}
}
What I have tried:
look i try this and it work good bout what i want to i want to merge it with my frist code to make it work in one button
SqlConnection con = new SqlConnection("Data Source=DESKTOP-J7D5POF;Initial Catalog=ilswork;Persist Security Info=True;User ID=****;Password=*****;connect timeout=900");
SqlDataAdapter sdf = new SqlDataAdapter("select * from tabl2 where age between'" + txt1.text + "'and'" + txt2.text + "'", con);
DataTable sd = new DataTable();
sdf.Fill(sd);
dataGridView1.DataSource = sd;