I am working on a SQL connection through C# but on the sqlCmd.ExecuteNonQuery(); line, when I run it and put information into the form it does not work. Crashing and giving me the error, the code for my program follows. Also include a screenshot of the form. I have been trying to fix this for a while but no luck, tried switching the code around and more but generally just didn't work.
https://i.stack.imgur.com/rpFGj.png
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormApp32
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
string connectionString = "Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True";
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
if (textBox5.Text + textBox6.Text == " ")
MessageBox.Show("Please fill mandatory fields");
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("UserAdd");
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#First_Name", textBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Last_Name", textBox2.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Email_ID", textBox3.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Contact", textBox4.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Address", richTextBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Gender", radioButton1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Gender", radioButton2.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Department", comboBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Username", textBox5.Text.Trim());
using (var connectionString = new SqlConnection("Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True"))
using (var cmd = new SqlDataAdapter())
using (var insertCommand = new SqlCommand("INSERT INTO Application VALUES (#First_Name, #Last_Name, #Email_ID, #Contact, #Address, #Gender, #Department, #Username, #Password) "))
{
insertCommand.Connection = connectionString;
cmd.InsertCommand = insertCommand;
connectionString.Open();
}
sqlCmd.ExecuteNonQuery();
MessageBox.Show("Registration successful");
}
}
}
}
I've fixed it up a little but it's still giving me a error for "sqlCmd.Connection = connectionString;" giving me a error on the connectionString part
The code shows following now
SqlCommand sqlCmd = new SqlCommand("UserAdd");
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#First_Name", textBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Last_Name", textBox2.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Email_ID", textBox3.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Contact", textBox4.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Address", richTextBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Gender", radioButton1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Gender", radioButton2.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Department", comboBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Username", textBox5.Text.Trim());
sqlCmd.Connection = connectionString;```
You add some code twice, it's redundant ...
So you have to do only this:
string connectionString = "Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True";
private void button1_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
if (textBox5.Text.Trim() + textBox6.Text.Trim() == "")
{
MessageBox.Show("Please fill mandatory fields");
return;
}
sqlCon.Open();
using (SqlCommand sqlCmd = new SqlCommand("UserAdd", sqlCon)) // you missed to pass connection to command
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#First_Name", textBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Last_Name", textBox2.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Email_ID", textBox3.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Contact", textBox4.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Address", richTextBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Gender", radioButton1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Department", comboBox1.Text.Trim()); // also I think here must be comboBox1.SelectedValue, not Text property
sqlCmd.Parameters.AddWithValue("#Username", textBox5.Text.Trim());
sqlCmd.ExecuteNonQuery();
}
}
MessageBox.Show("Registration successful");
}
catch(Exception e)
{
MessageBox.Show($"Error on SQL \"UserAdd\" procedure: {e.Message}");
}
}
You are mixing u everything here. You need to run the respective command in the respective connection. this line is also wrong connectionString.Open(); Also you have not provided Connection to sqlCmd.
Related
I have login issue authentication on windows form C# application. Once I register user it send user data to a SQL Server database. When I am trying to log in. Even if credentials match to data in data base message box showing up. Please see the code below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using travel_booking.UserControlers;
using System.Data.SqlClient;
namespace travel_booking
{
public partial class UserContrLogin : UserControl
{
internal Action<object, EventArgs> OnUserLogin;
UserContrRegister userContrRegister;
public UserContrLogin()
{
InitializeComponent();
}
public void setUserContrRegister(UserContrRegister userContrRegister)
{
this.userContrRegister = userContrRegister;
}
private void Exit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void LoginButton_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection(#"//Removed by me as it is sensitive data");
sqlConnection.Open();
string query = "Select * from tblUser Where Email = ' " + txtEmail.Text.Trim() + "' and Password = '" + txtPassword.Text.Trim() + "'";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count > 0)
this.Hide();
else
MessageBox.Show("Email or/and Password is/are invalid. Please try again");
sqlConnection.Close();
}
}
}
You can use this code to work much better
public void Login()
{
SqlConnection sqlConnection = new SqlConnection(#"//Removed by me as it is sensitive data");
sqlConnection.Open();
string query = "Select * from tblUser Where Email = #Email and Password = #Password";
SqlCommand command = new SqlCommand();
command.Connection = sqlConnection;
command.CommandType = CommandType.Text;
command.Text = query;
command.Parameters.AddWithValue("#Email", txtEmail.Text.Trim());
command.Parameters.AddWithValue("#Password", txtPassword.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if(reader.Read() == true)
{
this.Hide();
}
else
{
MessageBox.Show("Email or/and Password is/are invalid. Please try again");
}
}
I use the command.Parameters.AddWithValue() to avoid the concatenation of the string of your query that can cause an SQL INJECTION
This is my code behind for data update. But it is not updating in my database. Don't know why. Any suggestion pls.
I've check the database connection and it is working fine. I didn't declare the connection string using {..}.
Actually I didn't get any error message for the insert. I got an record update message. But in my database, it is not updating.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace StudentDataDisplay2
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=localhost;Initial Catalog=TestData;Integrated Security=True");
public Form1()
{
InitializeComponent();
this.Text = "Student Data Display Form";
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void display_data()
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "SELECT * from StudentDetails";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}
private void btnInsert_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "INSERT INTO StudentDetails VALUES (#Name,#Subject)";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.Parameters.Add("#Subject", SqlDbType.NVarChar).Value = textBox2.Text; //add values in textbox2 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record added");
}
private void btnDisplay_Click(object sender, EventArgs e)
{
display_data();
}
private void btnDelete_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "DELETE FROM StudentDetails WHERE Name= #Name";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record deleted");
}
private void btnUpdate_Click(object sender, EventArgs e)
{
//conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "UPDATE StudentDetails SET Name = #Name WHERE Subject = #Subject";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Subject", textBox2.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record updated!");
}
private void buttonSearch_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "DELETE FROM StudentDetails WHERE Name= #Name";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Search completed!");
}
}
}
It tells me the error "The connection was not closed. The connection's current state is open." whenever I click the add button. I am new at Visual Studio 2010 and Sql Server 2008, help or any advice will do.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace MRP.SupplierMaterial
{
public partial class Add : Form
{
SqlConnection con = new SqlConnection(Helper.GetCon());
public Add()
{
InitializeComponent();
}
void GetSuppliers()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT CompanyName, ContactPerson, Phone, Mobile, Status, DateAdded, DateModified FROM Suppliers";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new System.Data.DataSet();
da.Fill(ds, "Suppliers");
cmbSupplierID.DataSource = ds.Tables["Suppliers"];
cmbSupplierID.DisplayMember = "CompanyName";
cmbSupplierID.ValueMember = "SupplierID";
con.Close();
}
void GetMaterials()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Materials.MaterialID, " +
"Materials.Name + ' (' + UnitID.UnitMeasure + ')' AS MaterialName " +
"FROM Materials INNER JOIN UnitID ON Materials.UnitID = UnitID.UnitID";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new System.Data.DataSet();
da.Fill(ds, "Materials");
cmbMaterialID.DataSource = ds.Tables["Materials"];
cmbMaterialID.DisplayMember = "MaterialName";
cmbMaterialID.ValueMember = "MaterialID";
con.Close();
}
private void btnAdd_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO SupplierMaterials VALUES (#SupplierID, #MaterialID);";
cmd.Parameters.AddWithValue("#SupplierID", cmbSupplierID.SelectedValue);
cmd.Parameters.AddWithValue("#MaterialID", cmbMaterialID.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
}
private void Add_Load(object sender, EventArgs e)
{
GetMaterials();
GetSuppliers();
}
}
}
It seems one of GetSuppliers() ` is not executed till the part where you set
con.Close()
You have two alternatives:
1.Open the connection only once and use it in every method without closing it and close it on Application.Exit:
public Add()
{
InitializeComponent();
con.Open();
}
.........
private void Add_Closing(object sender, EventArgs e)
{
con.Close();
}
Set this check in every attempt to open con:
if (con.State == ConnectionState.Closed)
{
con.Open();
}
Using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
//Your rest of the code inside here.
}
This take care of closing your connection but you will have to manually open it. con.Open();
SqlConnection class implements IDisposable. So you use Dispose() method directly. The efficient way of doing is with the using block
To ensure that connections are always closed, open the connection inside
of a using block, as shown in the following code fragment. Doing so ensures that
the connection is automatically closed when the code exits the block
using(SqlConnection connection = new SqlConnection(Helper.GetCon()))
{
// Do something
}// Here it will automatically call Dispose()
You will still need to open the connection but don't need to close it because as I mentioned the Dispose() method will take care of the object at the end of the using block
Put below condition instead of con.open();
if (con.State == ConnectionState.Closed)
{
con.Open();
}
I'm new to C# so please check my code. It stops in cmd.ExecuteNonQuery(); here, but when I simply insert date it works but not inserting with combo box.
Is the SQL query right or not?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace newpro
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object sel = comboBox1.SelectedValue;
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES ('"+txtfname.Text+"','"+txtfname.Text+"', '"+txtuname.Text+"', '"+txtpass.Text+"', '"+txtemail.Text+"','"+comboBox1+"');",con);
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record inserted");
con.Close();
}
}
}
you have to get the selected value from your Combobox. combobox1 retuns only the class name System.Windows.Forms.ComboBox
Besides others, it is recommended to use parameter .. like this:
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES (#Name,#Fullname,#Password,#Email, #Gander)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#Name", txtfname.Text);
cmd.Parameters.Add("#Fullname", txtfname.Text);
cmd.Parameters.Add("#Password", txtpass.Text);
cmd.Parameters.Add("#Email", txtemail.Text);
cmd.Parameters.Add("#Gander", comboBox1.GetItemText(comboBox1.SelectedItem));
con.Open()
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception e)
{
MessageBox.Show("Error during insert: " + e.Message);
}
}
}
public void insertfunction()
{
string sqlconn = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
SqlConnection cn = new SqlConnection(sqlconn);
cn.Open();
String query = "insert into PatientRecords values(#Patient_Name,#Cnic,#Phone,#Address,#Age,#Doctor_Reference,#City)";
SqlCommand cmd = new SqlCommand(query,cn);
// cmd.Parameters.AddWithValue("#Patient_Id", pid.Text);
cmd.Parameters.AddWithValue("#Patient_Name", pname.Text);
cmd.Parameters.AddWithValue("#Cnic", pcnic.Text);
cmd.Parameters.AddWithValue("#Phone", pphone.Text);
cmd.Parameters.AddWithValue("#Address", paddress.Text);
cmd.Parameters.AddWithValue("#City", cmbopcity.GetItemText(cmbopcity.SelectedItem));
cmd.Parameters.AddWithValue("#Age", page.Text);
cmd.Parameters.AddWithValue("#Doctor_Reference", prefdoc.Text);
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record Successfully inserted");
}
else
{
MessageBox.Show("Record failed");
}
cn.Close();
}
I have text and a button and when on submit, I am checking whether the database has any rows-if not then insert rows or else update them, but on submit its throwing an error saying incorrect syntax at "cmd.ExecuteNonQuery" in the else condition
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class CM : System.Web.UI.Page
{
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlCommand cmd;
DataTable dt;
SqlConnection con = new SqlConnection("server =consulting76\\SQLEXPRESS; database = msdb; Integrated Security=True; MultipleActiveResultSets=True");
protected void Page_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Select * from NOTESMAKER", con);
da.Fill(ds);
//dt = ds.Tables["NOTESMAKER"];
}
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
if (ds.Tables[0].Rows.Count == 0)
{
cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(#text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
else
{
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.UpdateCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
}
}
You are closing a bracket on this line, which is never opened:
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
Also, setting the InsertCommand and UpdateCommand properties of the data adapter isn't neccessary.