friends
please if you have time to solve my problem
i have many textbox in my form with one button and one datagridview
i use this code to make the search
What if i want to perform a search using values from 2 or more text boxes. what if I typed in "r" in the Name text box then also typed "NY" in the city text box. I want to see the gridview give me the results of that.
that what i try to find and i didn't find anything
the code is working if i search in one textbox only
warm regards
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (txtCIVILIDD.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where CIVILIDD = '" + txtCIVILIDD.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (txtName_Arabic.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Name_Arabic like '%" + txtName_Arabic.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (txtusername.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where username = '" + txtusername.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBox1.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where status = '" + comboBox1.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBox2.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where confirmation = '" + comboBox2.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (CBgender.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where gender like '%" + CBgender.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (CBNATIONALITY.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where NATIONALITY like '" + CBNATIONALITY.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBoxGovernorate.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Governorate = '" + comboBoxGovernorate.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBoxCity.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where City = '" + comboBoxCity.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
dataGridView1.DataSource = dt;
i try to solve my problem with this code bout i find "SELECT * FROM tabl1 WHERE 1=1 ";
it return null to me
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
StringBuilder sqlcommand = "SELECT * FROM tabl1 WHERE 1=1 ";
if (!string.IsNullOrEmpty(CBgender.Text))
{
sqlcommand.Append(" and GENDER LIKE '%");
sqlcommand.Append(CBgender.Text);
sqlcommand.Append("%'");
}
// repeat for other textbox fields
dataGridView1.DataSource = dt;
}
my search form
Here are two possible approaches. The first uses #WelcomeOverflows's suggestion which is to use the RowFilter property of the DataTable. The advantage of doing so is that you only have to perform one database query and the filtering is handled client side. However, it isn't possible to protect RowFilter from SQL injection easily (but while you can still potentially subvert the filtering intention, the damage you can do on a disconnected data source is limited). Also if the dataset is enormous, it might not be desirable to pull back the entire dataset at once and keep it in memory.
// call upon startup to get all the data one time
private void GetData()
{
DataTable dataSource = new DataTable();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
{
connection.Open();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM tabl1", connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
// create a filter for the given field in the database and our control
private string CreateFilter(string fieldName, Control userInputControl, 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)
return String.Format("{0}='{1}'", fieldName, searchValue);
return String.Format("{0} LIKE '%{1}%'", fieldName, searchValue);
}
// set the filter on our data grid view
private void button1_Click(object sender, EventArgs e)
{
var filterConditions = new[] {
CreateFilter("Name_Arabic", txtName_Arabic, false),
CreateFilter("gender", CBgender, false),
CreateFilter("CIVILIDD", txtCIVILIDD, true),
CreateFilter("NATIONALITY", cbNationality, false)
// etc.
};
var dataSource = (DataTable)dataGridView1.DataSource;
if (!filterConditions.Any(a => a != null))
{
dataSource.DefaultView.RowFilter = null;
return;
}
dataSource.DefaultView.RowFilter = filterConditions
.Where(a => a != null)
.Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2));
}
Second approach is to filter directly in the database query, using SQL parameters to avoid SQL injection.
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;
}
}
private void button2_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("NATIONALITY", cbNationality, selectCommand, false)
// etc.
};
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["myDatabase"].ConnectionString))
{
selectCommand.Connection = connection;
selectCommand.CommandText = filterCondition == null ? "SELECT * FROM tabl1" : "SELECT * FROM tabl1 WHERE " + filterCondition;
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
DataTable dataSource = new DataTable();
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
Create StringBuilder object:
StringBuilder sqlcommand = new StringBuilder("SELECT * FROM tabl1 WHERE 1=1");
You can create a parametrized query which considers parameters having null values as neutral in search. For example:
SELECT * FROM Product WHERE
(Id = #Id OR Id IS NULL) AND
(Name LIKE '%' + #Name + '%' OR #Name IS NULL) AND
(Price = #Price OR #Price IS NULL)
This way, if you pass NULL for any of the parameters, that parameter will not be considered in search.
Also as a side note, it prevents SQL Injection, by using parameters.
Example
The following example assumes you have a table called Product, having a column named Id as INT, Name as NVARCHAR(100) and Price as INT.
Then to load data, create the following method:
public DataTable GetData(int? id, string name, int? price)
{
DataTable dt = new DataTable();
var commandText = "SELECT * FROM Products WHERE " +
"(Id = #Id OR #Id is NULL) AND " +
"(Name LIKE '%' + #Name + '%' OR #Name IS NULL) AND " +
"(Price = #Price OR #Price IS NULL)";
var connectionString = #"Data Source=.;Initial Catalog=SampleDb;Integrated Security=True";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#Id", SqlDbType.Int).Value =
(object)id ?? DBNull.Value;
command.Parameters.Add("#Name", SqlDbType.NVarChar, 100).Value =
(object)name ?? DBNull.Value;
command.Parameters.Add("#Price", SqlDbType.Int).Value =
(object)price ?? DBNull.Value;
using (var datAdapter = new SqlDataAdapter(command))
datAdapter.Fill(dt);
}
return dt;
}
To get values from TextBox controls and pass to GetData, you can use the following code:
var id = int.TryParse(idTextBox.Text, out var tempId) ? tempId : default(int?);
var name = string.IsNullOrEmpty(nameTextBox.Text)?null:nameTextBox.Text;
var price = int.TryParse(priceTextBox.Text, out var priceId) ? priceId : default(int?);
Then to get data:
var data = GetData(id, name, price);
I have code for deleting a row in C# using a SqlCommand. But I want to delete multiple rows. Can anyone help me with this? I am new to C#.
This is my code - please help. Thank you in advance.
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
You can build a comma separated userid list like -
string strUserIds = string.Empty();
for(int i=0; i<dataGrid.Count;i++)
{
strUserIds = strUserIds +","+ dataGrid.SelectedRows[0].Cells[0].Value;
}
--Remove last unwanted comma from strUserIds
then execute sql query as "DELETE FROM EmployeeTbl WHERE UserID in (" + strUserIds + ")"
This will delete multiple records from table.
Just Make some changes in Your Coding !
Delete All Selected Rows
Run Your select * from ActiveUser
public void deldata()
{
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
}
public void showdata()
{
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
You can use something like this; i didn't test the code but it should work if you create the parameters you need, before running code you have to create a type table, please see the link for details.
using (connection)
{
string sql ="Delete from YourTable t join #yourTypeTable i on t.id = i.Id:";
SqlCommand deleteCommand = new SqlCommand(sql, connection);
SqlParameter tvpParam = deleteCommand.Parameters.AddWithValue("#yourTypeTable", yourIdList);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.yourTypeTable";
deleteCommand.ExecuteNonQuery();
}
I have a tabcontrol, it has 9 tabpage collection each tabpage has a datagridview and a searchbox.
private void txtsrchesd_TextChanged(object sender, EventArgs e)
{
if (txtsrchesd.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM esd_view where department like '" + txtsrchesd.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgesd.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
private void txtsrchope_TextChanged(object sender, EventArgs e)
{
if (txtsrchope.Text == "")
{
}
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view where department like '" + txtsrchope.Text + "%' order by department ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
}
The output of the other datagridview appears on the other datagridview , how can I clear the output of the datagridview as I clear what I type on my searchbox
hope you understand , thank you for the help
When you are checking with:
{
if (txtsrchope.Text != "")
{}
.....
}
In the else part you don't need to fire the same query as when:
txtsrchop.text ==""
You can replace your else part by this code:
else
{
string constring = #"Data Source=JAY\J_SQLSERVER;Initial Catalog=FillingDatabase;User ID=jay;Password=pass1234";
string query = " SELECT * FROM operations_view ";
SqlConnection scon = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(query, scon);
SqlDataReader dr;
DataTable dt = new DataTable();
SqlDataAdapter sql = new SqlDataAdapter(query, scon);
sql.Fill(dt);
sql.Dispose();
dgoper.DataSource = dt;
memoDatabaseDataSetBindingSource.DataSource = dt.DefaultView;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.Open();
com.Connection = sc;
string sql;
{
sql = "SELECT FROM WolfAcademyForm WHERE [Forename] == 'txtSearch.Text';";
{
grdSearch.ItemsSource = sql;
sc.Close();
}
This is the code that I have, When I press the search button nothing shows up... Can someone please help me with this problem, I don't get any errors
Problems:
SQL query is not right:
It should be like SELECT * FROM TABLENAME.
In WHERE clause [Forename] == 'txtSearch.Text', == should = and Textbox value should be concatenated using +.
Fixed Code:
private void Button_Click(object sender, RoutedEventArgs e)
{
string sConn = #"Data Source=MYDS;Initial Catalog=MyCat;
User ID=MyUser;Password=MyPass;";
using(SqlConnection sc = new SqlConnection(sConn))
{
sc.Open();
string sql = "SELECT * FROM WolfAcademyForm WHERE [Forename]= #Forename";
SqlCommand com = new SqlCommand(sql, sc);
com.Parameters.AddWithValue("#Forename", txtSearch.Text);
using(SqlDataAdapter adapter = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}
}
}
Use this
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT FROM WolfAcademyForm WHERE [Forename] == " + txtSearch.Text + ";"
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Employee");
sda.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}
I have a main form (formMain) which loads a user control (classification) in its load event. And in the load event of the user control classification it displays a datagridview. Let me show you the code.
CLASSIFICATION
string serverstring = "user id = root; password=; server=localhost; database=purchase_order; connection timeout=3;";
private void load_data()
{
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataMember = dt.TableName;
}
catch (Exception)
{
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
Luckily it's working but when I click the search button located in another user control (search) it raises an event in the main form (formMain) wherein it must FILTER the datagridview in the user control (classification) but my code is not working.
Maybe I have a syntax error in my string query. Here is the code.
MAIN FORM
void SearchClicked(object sender, EventArgs e)
{
Search content = _searchbox;
classification control = new classification();
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification WHERE class_name LIKE '%#search'";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
//MessageBox.Show(content.txtboxSearch.Text);
cmd.Parameters.AddWithValue("#search", content.txtboxSearch.Text);
DataTable dt = new DataTable();
da.Fill(dt);
control.dataGridView1.DataSource = dt;
control.dataGridView1.DataMember = dt.TableName;
}
catch (Exception)
{
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
use CONCAT()
string query = #"SELECT *
FROM tblclassification
WHERE class_name LIKE CONCAT('%', #search)";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#search", content.txtboxSearch.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
try
"SELECT * FROM purchase_order.tblclassification WHERE class_name LIKE ('%#search%')";
or ..
"SELECT * FROM tblclassification WHERE (class_name LIKE '%#search%')"