SQL Requests. Working with text boxes - c#

Not working request. What could be the problem? Before that he wrote through CommandText, all worked well.
Code:
private void buttonSearch_Click(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\HomePC\Desktop\Lab2 DB\Lab2 DB\ResearchDB.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM '"+comboBox1.SelectedItem.ToString()+"' WHERE '"+ comboBox2.SelectedItem.ToString() +"' = '"+ textBox1.Text +"'", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}

It'd help if you provided an error, but one obvious issue is that you're not opening the connection.
You can open the connection right after you set the CommandType.
cmd.CommandType = CommandType.Text;
con.Open();
Also, I'd recommend parameterizing your query. It's more secure, and cuts down on potential typos.
using (var cmd = new SqlCommand(
"SELECT * FROM '" + comboBox1.SelectedItem.ToString() + "' WHERE '" + comboBox2.SelectedItem.ToString() + "' = #your_textbox_value", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#your_textbox_value", textBox1.Text);
con.Open();
...

Related

C# multi valued combo box value to SQL Server database

private void filljobid()
{
try
{
string jobid = "";
int newjobid, oldjobid;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("SELECT MAX(job_id) FROM job", con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
jobid = reader[0].ToString();
}
oldjobid = int.Parse(jobid.ToString());
newjobid = oldjobid + 1;
jobidtextbox.Text = newjobid.ToString();
}
catch (Exception)
{
MessageBox.Show("Error while connecting");
}
}
private void fillcustomercombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT customer_id,(first_name + ' ' + last_name + ' - ' + contact) AS CUSTOMERNAME FROM customer", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
customeridcombobox.DataSource = ds.Tables[0];
customeridcombobox.DisplayMember = "CUSTOMERNAME";
customeridcombobox.ValueMember = "customer_id";
cmd.ExecuteReader();
con.Close();
// CODE FOR DISPLAYING multiple values in another way, but not sure how to retrieve data from this function
// for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
// {
// customeridcombobox.Items.Add(ds.Tables[0].Rows[i][0] + " - " + ds.Tables[0].Rows[i][1] + " " + ds.Tables[0].Rows[i][2]);
// }
}
private void filldepotcombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT depot_id,(branch_name + ' - ' + region_name + ' - ' + location) AS DEPOTNAME FROM depot", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
depotidcombobox.DataSource = ds.Tables[0];
depotidcombobox.DisplayMember = "DEPOTNAME";
depotidcombobox.ValueMember = "depot_id";
cmd.ExecuteReader();
con.Close();
}
private void filljobtypecombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT job_type FROM jobtype", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
jobtypecombobox.DisplayMember = "job_type";
jobtypecombobox.ValueMember = "job_type";
jobtypecombobox.DataSource = ds.Tables[0];
cmd.ExecuteReader();
con.Close();
}
private void loadingcomboboxesdata_Load(object sender, EventArgs e)
{
fillcustomercombox();
filljobid();
filldepotcombox();
filljobtypecombox();
}
private void addnewjobbutton_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMoversDB;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into job (start_location, end_location, depot_id, job_type, customer_id,) values ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "','" + depotidcombobox.Text + "','" + jobtypecombobox.Text + "','" + customeridcombobox.Text + "')";
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Added new job");
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
What I'm trying to achieve is basically take the users selected value which is displayed in the combo box which is valuemember and then insert it into the database. Right now I get the error when I try to insert the data into the database. When I do the combo box with a single value it works fine but it doesn't work when I do it with multiple values.
Could someone close this question. I managed to solve my own question. I dont know if this solution is considered good but here you go.
private void addnewjobbutton_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO job(start_location, end_location, depot_id, job_type, customer_id) VALUES ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "',#3,#4, #5)"))
{
cmd.Connection = con;
//cmd.Parameters.AddWithValue("#1", startlocationtxtbox.SelectedText);
//cmd.Parameters.AddWithValue("#2", endlocationtxtbox.SelectedText);
cmd.Parameters.AddWithValue("#3", depotidcombobox.SelectedValue);
cmd.Parameters.AddWithValue("#4", jobtypecombobox.SelectedValue);
cmd.Parameters.AddWithValue("#5",customeridcombobox.SelectedValue);
con.Open();
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
}

delete and update the selected row

executenonquery is my problem, this code works on other button in different datagridview
here's my code at delete button
private void button4_Click_2(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=XXYZZ\SQLEXPRESS;Initial Catalog=rick_inventiory;Integrated Security=True");
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete from tbl_Orders where CustomersID2 = '" + dataGridView5.SelectedRows[0].Cells[0].Value.ToString() + "'";
con.Open();
cmd.Parameters.AddWithValue("#CustomerID2", txtCustomerID2.Text);
cmd.ExecuteNonQuery();
con.Close();
disp_data();
MessageBox.Show("Deleted Successfully");
}
the update code still execute sa code but did not update it
and heres my code for Update button
SqlConnection con = new SqlConnection(#"Data Source=XXYZZ\SQLEXPRESS;Initial Catalog=rick_inventiory;Integrated Security=True");
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Update tbl_Products SET ProductName='" + txtProName.Text +
"',Stocks='" + txtStocks.Text + "',Price='" + txtPrice.Text + "',Description='" +
txtDesc.Text + "',CategoryName='" + txtCat.Text + "' where ProductID ='" + txtProID.Text + "';";
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter("Select * from tbl_Products", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
MessageBox.Show("Successfuly Updated");
con.close();
In update there is a syntax problem remove inner side semi colon of update query
While in delete you want to change the line
from
cmd.Parameters.AddWithValue("#CustomerID2", txtCustomerID2.Text);
to
cmd.Parameters.AddWithValue("#CustomerID2", '" + dataGridView5.SelectedRows[0].Cells[0].Value.ToString() + "');

Populating SQL Server Datatable

My program will not update my SQL Server database after executing. When I run my program my DataGridView updates when I insert my information, but it will not update itself in the dataTable.
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES('" + idTextBox.Text + "','" + nameTextBox.Text + "','" + ageTextBox.Text + "')";
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
this.dataTableTableAdapter.Fill(this.employeeDataSet1.dataTable);
conn.Close();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataTable data = new DataTable();
conn.Open();
adapt.Update(data);
conn.Close();
dataTableDataGridView.DataSource = data;
}
If you created your DataGridView using the designer which added a dataset, bindingsource, and tableadapter, then your DataGridView should be configured correctly out of the box. Try commented out these lines:
//SqlDataAdapter adapt = new SqlDataAdapter(cmd);
//DataTable data = new DataTable();
//conn.Open();
//adapt.Update(data);
//conn.Close();
//dataGridView1.DataSource = data;
I replicated your button_click code and it works locally for me using Sql Express.
Based on your comment i assume the cause is the missing conversion. Using Int32.TryParse you can convert the string to int. Be aware that the ' have to go as well
int id, age;
bool idIsInt = false, ageIsInt = false;
idIsInt = Int32.TryParse(idTextBox.Text, out id);
ageIsInt = Int32.TryParse(ageTextBox.Text, out age);
if(idIsInt && ageIsInt)
{
string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES("
+ id + ",'" + nameTextBox.Text + "',"
+ age + ")";
SqlConnection conn =
new SqlConnection(#"Data Source(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf
;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
}

Can you help me to show datagridview and Refresh after update?

This is my code and error message when you running say:
An unhandled exception of type System.Data.SqlClient.SqlException
occurred in System.Data.dll
on this da.fill(dt);
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
public FormProduksi()
{
InitializeComponent();
showgridview();
}
private void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure; done :D
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
showgridview();
clear();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
that update successfully but cant refresh, so i do quit that form and open can see it
You are closing the connection
con.Close();
and then using
da.Fill(dt);
Just swap this lines:
showgridview();
con.Close();
For example with DbDataAdapter.Fill:
Notes:
1
Yoy should use parametrized queries so you avoid SQL Injection attacks:
var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con);
cmd.Parameters.AddWithValue("#id", id.Text);
2
Wrap SqlConnection and SqlCommand into using so any resources used by those would disposed:
string position;
using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
con.Open();
using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con))
{
cmd.Parameters.AddWithValue("#id", id.Text);
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
}
}
Credit
Just change the showgridview() function as below where connection is opened & closed properly.
Also check your sql query ,provide space and maintain syntax of query :
SELECT * FROM Produksi
Error screenshot clearly depicts that stored procedure with such name don't exist
comment out those lines as code below :
void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Then you wont be having connection issues and errors related .
Button Click code change the closing connection as below:
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try
{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Also, for further reading:
parameterized queries vs. SQL injection
Why do we always prefer using parameters in SQL statements?

Rework using parameterized queries C#

There is a lot of tutorials regarding parameterized queries but most of them involve using SqlCommand, the only thing my code accepts is SqlDataAdapter for my SQL command, anytime I try to instantiate it as a SqlCommand I get errors.
TL;DR
I either need guidance on how to rework this using parameterized queries or I need to know why my SqlDataAdapter line doesn't work as an SqlCommand line.
private void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jake\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From Login Where Username = '" + txtUsername.Text + "' and Password = '" + txtPassword.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
MessageBox.Show("LOGIN!");
}
else
{
MessageBox.Show("FAILED!");
}
}
You can use:
using (SqlDataAdapter sqlDA = new SqlDataAdapter("Select * from user where username = #username and password = #pass", sqlConnect))
{
sqlDA.SelectCommand.CommandType = CommandType.Text;
sqlDA.SelectCommand.Parameters.Add("#username", SqlDbType.Varchar).Value = username;
sqlDA.SelectCommand.Parameters.Add("#pass", SqlDbType.Varchar).Value = password;
sqlDA.Fill(dataTableVariable);
return dataTableVariable;
}
For your password remember to use a hash algorithm
This code is not tested. If you want the best performance you can explore execute scalar.
You can use Parameters.AddWithValue in SqlDataAdapter
sda.SelectCommand.Parameters.AddWithValue("#ParamName",value);
Check this: c# Using Parameters.AddWithValue in SqlDataAdapter
Try using parametrize query, it will avoids errors and sql injection
Once you have the reader you can use HasRow() to check if a record is returned
string conString = "xxxxxxxxxxxxxxxxxxxxxxxx";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (var cmd = new SqlCommand(
"SELECT * FROM Login Where Username=#Username AND Password=#Password",
con))
{
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRow())
{
if(reader.Read())
{
var username = reader["Username"].ToString();
}
}
else
{
//User does not exists
}
}
}
}
You will need to import some library:
using System;
using System.Data;
using System.Data.SqlClient;

Categories