sql search query in c# - c#

I'm trying to make a database search in my app where the user would choose the column and enter the search word and the result would come up in a dataviewgrid.
This is the code i've been working on, the problem is that nothing comes up and i'm pretty sure there are entries in the database. EDIT : it's a windows form application
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("Server = localhost; database = Clients; Integrated Security = SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From dbo.Tclients WHERE #choice = #input", conn);
cmd.Parameters.AddWithValue("#choice", comboBox1.Text);
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}

You cannot use a parameter to express the name of a column.
You should populate your combobox with the column names and set its DropDownStyle property to DropDownList (do not allow your user to type the name of the column) and then build your query
private void button1_Click(object sender, EventArgs e)
{
string cmdText = "SELECT * From dbo.Tclients WHERE " + comboBox1.Text + " = #input";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}

you forgot to bind the grid view with datasource
add this after data source
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();

private void bunifuThinButton21_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\albasheer\Desktop\games\my_school\my_school\school.mdf;Integrated Security=True;User Instance=True");
connection.Open();
string sql = "select name,id,stage,age,cost from STUDENT where stage like '%" + bunifuCustomLabel1.Text + "%' and name like '%" + bunifuMaterialTextbox1.Text + "%'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
SqlCommand command = new SqlCommand(sql, connection);
DataTable table = new DataTable();
adapter.Fill(table);
var dt = from t in table.AsEnumerable()
select new
{
id = t.Field<int>("id"),
Name = t.Field<string>("name"),
};
bunifuCustomDataGrid1.DataSource = dt.ToList();
}

Related

Searching Form Windows on C# with Data Set

private void textBox7_TextChanged(object sender, EventArgs e)
{
SqlConnection conn = Conn.GetConnection();
conn.Open();
cmd = new SqlCommand("select * from DATA_ITEMS where Items_Name like '" + textBox2.Text + "%'", conn);
ds = new DataSet();
adapter = new SqlDataAdapter (cmd);
adapter.Fill(ds);
dataGridView1.DataSource = ds;
}
I want to ask, why do you want to do a search, but when you type it in the search text box, the data in the grid view disappears (it doesn't appear).
I think you are missing databind in the gridview
private void textBox7_TextChanged(object sender, EventArgs e)
{
SqlConnection conn = Conn.GetConnection();
conn.Open();
cmd = new SqlCommand("select * from DATA_ITEMS where Items_Name like '" + textBox2.Text + "%'", conn);
ds = new DataSet();
adapter = new SqlDataAdapter (cmd);
adapter.Fill(ds);
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
}

Query single data from SQLite to C# textbox or label

I have a single SQlite query that returns "10" to me but I couldn't send it to c# textbox1.text area. I found datagrid examples which work just fine but single value for textbox I could not handle it.
I tried changing datagrid areas to textbox but really I have no idea how to get value with sqlite
private SQLiteConnection con = new SQLiteConnection();
private SQLiteCommand com = new SQLiteCommand();
private SQLiteDataAdapter adapt = new SQLiteDataAdapter();
private DataSet ds = new DataSet();
private DataTable dt = new DataTable();
//private SQLiteDataReader dr = new SQLiteDataReader();
public void set_connection()
{
con = new SQLiteConnection();
con.ConnectionString = ("Data Source=data/lastix_db.s3db");
}
public void execute_q(string txtQuery)
{
set_connection();
con.Open();
com = con.CreateCommand();
com.CommandText = txtQuery;
com.ExecuteNonQuery();
con.Close();
}
public void load_data()
{
set_connection();
con.Open();
com = con.CreateCommand();
string comtext = "SELECT * FROM stok";
adapt = new SQLiteDataAdapter(comtext, con);
ds.Reset();
adapt.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
con.Close();
}
private void Button2_Click(object sender, EventArgs e)
{
set_connection();
string stokout = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
execute_q(stokout);
label16.Text = Convert.ToString(stokout);
label16.Text = //must be read "10" from sqlite
Insert update delete and all other datagrid solutions are ok but I'm really stuck on read single data and type it to textbox.
SQLiteConnection connect = new SQLiteConnection();
connect.ConnectionString = ("Data Source=data/lastix_db.s3db");
connect.Open();
string sql = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
SQLiteCommand cmd = new SQLiteCommand(sql, connect);
Int32 totalp = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
baglan.Close();
//MessageBox.Show("Your Balance is: " + totalp);
label16.Text = Convert.ToString(totalp);

how to search data in db

This code is working fine but when i search id like 121452, so it will call all numbers that have "1" or "2" in db. so i want it show only the exact id what i search
private void btn_search_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acap\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Student where No_ic = " + boxSearch.Text, con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
//dataGridView1.Visible = true;
}
Try this :
Updated: (Previously i forgot to bind dataset.)
private void btn_search_Click(object sender, EventArgs e) {
String bResult = boxSearch.Text;
string connectionString = "Data Source=.;Initial Catalog=sacbase;Integrated Security=True"; // add your conncetion string here
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM Student where No_ic =#val", connection);
cmd.Parameters.AddWithValue("#val", bResult);
SqlDataAdapter dataadapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "student_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "student_table";
}

c# how to use Combobox.Value for a From Clause in a Sql query

Please can you assist me in a very weird request
I am building a form to represent a table in a datagridview.
I want to change the data that is bound to the datagridview when i select a different value in a combobox. I bound the event to a button.
i get an error when i run the code:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll Additional information: Syntax error in query. Incomplete query clause.
the code i have is as follows.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand("Select * From #name ", con);
cmd.Parameters.AddWithValue("#name", comboBox1.SelectedValue);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
This code will help you:
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.Text), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
you can not pass table name as parameter. you can build sql based on your value selection in your combobox. replace your code with this code and check.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.SelectedValue), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
If you use Data Bound Items then use comboBox1.SelectedValue. If you use Unbound Mode then use comboBox1.SelectedItem.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
//OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedValue.ToString(), con);
OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedItem.ToString(), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
But not advice this way. You can use stored Procedure.
Try This:
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
string tableName = comboBox1.SelectedValue;
var builder = new SqlCommandBuilder();
string escapedTableName = builder.QuoteIdentifier(tableName);
OleDbCommand cmd = new OleDbCommand("Select * From " + escapedTableName , con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}

Errors when retrieving values from database determined by combobox to gridview

I have a code to get all the values from database determined by a combobox to a datagridview.
But whenever i run it , i get invalid column name for ListU.SelectedValue , and the multi-part identifier "System.Data.DataRowView" could not be bound if i am using ListU.SelectedItem.
where did i go wrong? i am guessing it is either my code or it is my table.
private void User_Load(object sender, EventArgs e)
{
SqlDataAdapter daSearch = new SqlDataAdapter("SELECT cName FROM ComDet", conn);
DataTable dt1 = new DataTable();
ListU.DataSource = dt1;
daSearch.Fill(dt1);
ListU.ValueMember = "cName";
ListU.DisplayMember = "cName";
ListU.DropDownStyle = ComboBoxStyle.DropDownList;
ListU.Enabled = true;
}
and the button code -
private void searchBtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daS = new SqlDataAdapter("select cName, cDetails, cDetails2 from ComDet where cName =" + ListU.SelectedValue, conn);
DataTable dts3 = new DataTable();
daS.Fill(dts3);
dataGridView1.DataSource = dts3.DefaultView;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
conn.Close();
}
you should use SqlParameter ... helps against sql injection problems and also against missing quotes ... like this:
SqlDataAdapter daS = new SqlDataAdapter("select cName, cDetails, cDetails2 from ComDet where cName = #name", conn);
daS.SelectCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = ListU.SelectedValue;
this assumes that cName is a string ... if not you'll have to change the SqlDbType ...

Categories

Resources