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!");
}
}
}
Related
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.
I have a gridview does not update on pageload. If you insert a value into the table, the page posts back and the gridview remains the same. All tho the record is inserted into the database. I'm fairly new to ADO.NET, any suggestions would be much appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class Equip_DB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataBind();
}
string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand showAll = new SqlCommand("SELECT * FROM Equiptment", con);
SqlDataReader reads = showAll.ExecuteReader();
GridView1.DataSource = reads;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
//INSERT INTO Equiptment VALUES ('2', 'Hammers', '24')
string query = "INSERT INTO Equiptment VALUES ('"+
equipAmount.Text +"', '"+
equipType.Text + "', '" +
DropDownList1.SelectedValue +"')";
AddContract.Visible = true;
SqlCommand cmd = new SqlCommand(query, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch {
con.Close();
}
}
}
You are not binding gridview with updated content.
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
//INSERT INTO Equiptment VALUES ('2', 'Hammers', '24')
string query = "INSERT INTO Equiptment VALUES ('"+
equipAmount.Text +"', '"+
equipType.Text + "', '" +
DropDownList1.SelectedValue +"')";
AddContract.Visible = true;
SqlCommand cmd = new SqlCommand(query, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
//GRID LOAD CODE GOES HERE
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand showAll = new SqlCommand("SELECT * FROM Equiptment", con);
SqlDataReader reads = showAll.ExecuteReader();
GridView1.DataSource = reads;
GridView1.DataBind();
}
///////////////////////
}
catch {
con.Close();
}
}
}
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 am trying to update my database table ExpenseManagement. But it is not Updated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
public partial class UserProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtUserId.Text = Request.Cookies["txtUserName"].Value;
string con_string = #"data Source= 10.10.10.5; initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
SqlCommand cmd = new SqlCommand("select FirstName, LastName, Password, EmailId, MobileNumber from ExpenseManagement where UserId ='"+txtUserId.Text+"'", con);
cmd.Parameters.AddWithValue("#UserId", txtUserId.Text);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
txtFirstName.Text = dt.Rows[0]["FirstName"].ToString();
txtLastName.Text = dt.Rows[0]["LastName"].ToString();
txtPassword.Text= dt.Rows[0]["Password"].ToString();
txtEmailId.Text = dt.Rows[0]["EmailId"].ToString();
txtMobileNumber.Text = dt.Rows[0]["MobileNumber"].ToString();
con.Close();
txtUserId.Enabled = false;
txtFirstName.Enabled=false;
txtLastName.Enabled=false;
txtPassword.Enabled = false;
txtEmailId.Enabled = false;
txtMobileNumber.Enabled = false;
btnUpdate.Visible = false;
}
protected void Button1_Click1(object sender, EventArgs e)
{
txtUserId.Enabled = true;
txtUserId.ReadOnly = true;
txtFirstName.Enabled = true;
txtLastName.Enabled = true;
txtPassword.Enabled = true;
txtMobileNumber.Enabled = true;
txtEmailId.Enabled = true;
btnUpdate.Visible = true;
btnEdit.Visible = false;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string con_string = #"data Source= 10.10.10.5; initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
string qryUpdate = "Update ExpenseManagement set FirstName= #FirstName, LastName=#LastName, Password=#Password, EmailId=#EmailId,MobileNumber=#MobileNumber where UserId= #UserId";
SqlCommand cmd = new SqlCommand(qryUpdate, con);
cmd.Parameters.AddWithValue("#UserId", txtUserId.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#EmailId", txtEmailId.Text);
cmd.Parameters.AddWithValue("#MobileNumber", txtMobileNumber.Text);
con.Open();
if (Page.IsValid)
{
cmd.ExecuteNonQuery();
btnEdit.Visible = true;
}
con.Close();
}
}
I have next database fields:
UserId, FirstName, LastName, Password, EmailId, MobileNumber.
Missing the Page.IsPostBack check on the Page_Load event.
In ASP.NET, when you raise an event on a server side control, the Page_Load event is always executed before the code in the control event.
In your case, your user changes the textboxes, then presses the Update button. This raises the Page_Load event followed by the btnUpdate_Click event. Without a check on the property IsPostBack, the Page_Load event reloads the textboxes from the database with the original values effectively destroying the data typed by the user, then the button event code is called. But at this point the values in the textboxes are the original ones, so your code runs correctly, but doesn't change anything.
Change the Page_Load event adding
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
txtUserId.Text = Request.Cookies["txtUserName"].Value;
string con_string = #"data Source= 10.10.10.5; initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
SqlCommand cmd = new SqlCommand(#"select FirstName, LastName, Password,
EmailId, MobileNumber
from ExpenseManagement
where UserId =#usedId", con);
cmd.Parameters.AddWithValue("#UserId", txtUserId.Text);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
......
btnUpdate.Visible = false;
}
}
I could recommend for the command to be more readable to user # instead of concatenating strings with "+" sign as below:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string con_string = #"data Source= 10.10.10.5;initial catalog= test; user= xx; password= xxxxxxxxx;";
SqlConnection con = new SqlConnection(con_string);
string qryUpdate = #"Update ExpenseManagement
set FirstName= #FirstName,
LastName=#LastName,
Password=#Password,
EmailId=#EmailId,
MobileNumber=#MobileNumber
where UserId= #UserId";
SqlCommand cmd = new SqlCommand(qryUpdate, con);
cmd.Parameters.AddWithValue("#UserId", Convert.ToInt32(txtUserId.Text));
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#EmailId", txtEmailId.Text);
cmd.Parameters.AddWithValue("#MobileNumber", txtMobileNumber.Text);
con.Open();
if (Page.IsValid)
{
cmd.ExecuteNonQuery();
btnEdit.Visible = true;
}
con.Close();
}
Also I agree with RezaRahmati to convert the userId and other parameters to correct types you have defined in your database, table columns.
I think the problem is using cmd.Parameters.AddWithValue("#UserId", txtUserId.Text); because it add a parameter of type string (because txtUserId.Text is string) instead of int or long, so change it to cmd.Parameters.AddWithValue("#UserId", int.parse(txtUserId.Text)); or use cmd.Parameters.Add() which takes type as argument.
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.