Update SQL Server table columns with button click from gridview fields - c#

I have a gridview that displays all the fields from my table.
My problem is that I need to update my SQL Server table when I click the save button (onclick) because I added a new field that generates a unique ID to every Item I have in my table. And It will add the generated id to the database table whenever I click the save button.
I have tried this
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text +
"' , [prno], [itemaname], [specification], [qty], [uomid], [expenseid],
[statusid], [userid], [inserteddate], [withquotation], [potempid] WHERE
idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
But I get an error
Here is my complete code:
public void SaveTogrdPOTemp()
{
SqlConnection ConnString = new SqlConnection(ConfigurationManager.ConnectionStrings["MUCS2.0ConnectionString"].ConnectionString);
string strSql = string.Empty;
pextid = "TPID";
using (SqlCommand cmd = new SqlCommand("SELECT * FROM GenIDGen WHERE extid = '" + pextid + "'"))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = ConnString;
ConnString.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
var extid = sdr["extid"].ToString().Trim();
var genID = sdr["generatedid"].ToString().Trim();
var gentr = sdr["generator"].ToString();
var potempoid = extid + genID;
ConnString.Close();
}
}
strSql = "UPDATE [dbo].[GenIDGen] SET [generator] = generator + 1
WHERE extid = '" + pextid + "' ";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text + "' WHERE idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
}
For the generating of ID and the updating of the gridview. Thank you!

Related

How to update 2 tables in c#

I have 2 tables
tbl_employer(Emp_num,Designation,Fname,Lname,Phone_no)
tbl_system_users(Emp_num,User_name,Password)
those two tables are filled by using one c# form(employer.cs).Only few employers have permission to access the system called system users. there are 2 text boxes for username and password in employer.cs. username and password text box should not null to save data to tbl_system_users and if both text boxes are null, it means they are only employers and not system users.
Emp_num of tbl_employer is auto increment field and a foreign key to tbl_system_users.
how can I update a employer detail?
public void update_employers(DTOUsers Users)
{
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "UPDATE tbl_employer SET Designation = '" + Users.Designation
+ "',,Employer_first_name = '" + Users.EmpFirstName + "',Employer_last_name = '"
+ Users.EmpLastName + "',, Phone_Num = '" + Users.PhoneNum + "' WHERE Emp_Num ='" + Users.EmpNum + "'";
con.Open();
cmd.ExecuteNonQuery();
if (Users.Password != "" && Users.UserName != "")
{
cmd.CommandText = "UPDATE tbl_system_users set User_name='" + Users.UserName + "',Password='" + Users.Password + "' where Emp_Num ='" + Users.EmpNum + "'";
cmd.ExecuteNonQuery();
}
con.Close();
in employer.cs
private void btn_update_Click(object sender, EventArgs e)
{
string emp_num = txt_emp_num.Text;
string designation = cmb_designation.Text;
string fname = txt_emp_fname.Text;
string lname = txt_emp_lname.Text;
string user_name = txt_user_name.Text;
string pw = txt_pw.Text;
string phno = txt_phn_num.Text;
DTOUsers emp = new DTOUsers();
emp.EmpNum = Convert.ToInt16(emp_num);
emp.Designation = designation;
emp.EmpFirstName = fname;
emp.EmpLastName = lname;
emp.UserName = user_name;
emp.Password = strh.Encrypt(pw);
emp.PhoneNum = phno;
dbh.update_employers(emp);
}
public void update_employers(DTOUsers Users)
{
bool firstStep = true;
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(con);
cmd.CommandText = "UPDATE tbl_employer SET Designation = #Designation,Employer_first_name = #EmpFirstName,Employer_last_name = #EmpLastName,Phone_Num = #PhoneNum WHERE Emp_Num = #PhoneNum";
//SqlDbType.VarChar Adjust according to the database values
cmd.Parameters.Add("#Designation", SqlDbType.VarChar, 30).Value = Users.Designation;
cmd.Parameters.Add("#EmpFirstName", SqlDbType.VarChar, 30).Value = Users.EmpFirstName;
cmd.Parameters.Add("#EmpLastName", SqlDbType.VarChar, 30).Value = Users.EmpLastName;
cmd.Parameters.Add("#PhoneNum", SqlDbType.VarChar, 30).Value = Users.PhoneNum;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
firstStep = false;
}
if (firstStep)
{
if (!string.IsNullOrEmpty(Users.Password) && !string.IsNullOrEmpty(Users.UserName))
{
cmd = new SqlCommand(con);
cmd.CommandText = "UPDATE tbl_system_users set User_name = #UserName,Password = #Password where Emp_Num = #PhoneNum";
cmd.Parameters.Add("#UserName", SqlDbType.VarChar, 30).Value = Users.UserName;
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 30).Value = Users.Password;
cmd.Parameters.Add("#PhoneNum", SqlDbType.VarChar, 30).Value = Users.PhoneNum;
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
con.Close();
}
}
}
}

C# Updating excel database and inserting record while adding items

so I have this program which when I press a button inserts a record into an excel spreadsheet with, the columns, being , customer, product, weight, dateTime. Now I want to be able to update a record if the same customer, and product occurs, but I also want to add the previous weight field with the new field, and update the time.
The problem is i'm not sure how to modify my update statement to do this.
// Load data from database, and Update database if filed already exists
DataSet ds = new DataSet();
string insertquery = "SELECT * FROM [Sheet1$] where [Customer] = '" + lblcustomername + " ' ";
OleDbConnection myConnection = new OleDbConnection(OutputDatabaseConnectionString); //define new connection object
OleDbDataAdapter mydataadapter = new OleDbDataAdapter(insertquery, myConnection); //define data adaptor and select column data from spreadsheet
mydataadapter.Fill(ds);
int i = ds.Tables[0].Rows.Count;
// If item exists in database, update it
if (i > 0)
{
try
{
System.Data.OleDb.OleDbConnection myConnection2; //create new connection object
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
String sql = null;
myConnection2 = new System.Data.OleDb.OleDbConnection(OutputDatabaseConnectionString); //define connection string
myConnection2.Open();
myCommand.Connection = myConnection2;
sql = "UPDATE [Sheet1$] SET [Net Weight(Kg)]= '" + textBox1.Text + "' WHERE [Customer] = '" + lblcustomername + "'";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
myConnection2.Close();
myConnection2.Close(); //close connection
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// if it doesn't exist update database
try
{
System.Data.OleDb.OleDbConnection myConnection1; //create new connection object
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
String sql = null;
myConnection1 = new System.Data.OleDb.OleDbConnection(OutputDatabaseConnectionString); //define connection string
myConnection1.Open();
myCommand.Connection = myConnection1;
sql = sql = "INSERT INTO [Sheet1$] ([Customer],[Product],[Net Weight(Kg)], [DateTime]) VALUES('" + lblcustomername.Text + "','" + lblproductname.Text + "','" + textBox1.Text + "','" + (DateTime.Now).ToString() + "')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
myConnection1.Close();
myConnection1.Close(); //close connection
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

When i click the update button to update database values in SQL C# All Rows Are Affected by the same value

This is my screen shot
Bellow Is My Code For Update Button Click Event!
{
try
{
con = new SqlConnection(cs.ConDB);
con.Open();
string cb = "Update tblFees set Salutation= '" + cmbSalutation.Text + "' , Name= '" + tbName.Text + "',Sex = '" + cmbSex.Text + "', Date ='" + Date.Text + "',Fees_Amount='" + cmbFeesAmount.Text + "',Fees_Status='" + radioButton1.Checked + "'";
cmd = new SqlCommand(cb);
cmd.Connection = con;
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Successfully updated", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
btnUpdate.Enabled = false;
btnSave.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
try
{
con = new SqlConnection(cs.ConDB);
con.Open();
cmd = new SqlCommand("SELECT * From tblFees", con);
SqlDataAdapter myDA = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
myDA.Fill(myDataSet, "tblFees");
dataGridView1.DataSource = myDataSet.Tables["tblFees"].DefaultView;
con.Close();
}catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);}`
Please Solve my problem i am new in the programming world
any help would be greatly appreciated
you should specify the rows using where condition
For example you can modify your query something like the following. I assume cboUser is a combo box there you can select particular user, so that the data updated for that selected user only.
SqlConnection con = new SqlConnection();
con.Open();
string cb = "Update [tblFees] set Salutation=#Salutation, Name=#Name,Sex =#Sex where tblFeesPK=#pk'";
SqlCommand cmd = new SqlCommand(cb, con);
cmd.Parameters.AddWithValue("#Salutation", cmbSalutation.Text);
cmd.Parameters.AddWithValue("#Name", tbName.Text);
cmd.Parameters.AddWithValue("#Sex", cmbSex.Text);
cmd.Parameters.AddWithValue("#pk", cboUser.SelectedValue);
cmd.ExecuteNonQuery();
If you want to update details based on name means: you can give name
in where condition. but it's not a proper way. so use primary
key(since name may have duplicate values)
You need to change the statement as:
string cb = "Update tblFees set Salutation= '" + cmbSalutation.Text + "' , Name= '" + tbName.Text + "',Sex = '" + cmbSex.Text + "', Date ='" + Date.Text + "',Fees_Amount='" + cmbFeesAmount.Text + "',Fees_Status='" + radioButton1.Checked + "' where Name= '" + tbName.Text + "'";
You need to add where Name= '" + tbName.Text + "';
Now it will update those rows where Name matches
Also as un-lucky said u should use parameterized queries

Unable to insert contents into the database

I have created a sql server database in godaddy and created a table named property manually.i also successfuly connected my application to the database using connection string.But i am unable to insert any values to the table using my c# code
Below is my C# code
string strQuery = "INSERT INTO property(name,email,phone,heading,description,location,image1,image2,image3,image4) VALUES('" + name + "','" + email + "','" + phone + "','" + title + "','" + description + "','" + district + "',#data,#data2,#data3,#data4);";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("#data2", SqlDbType.Binary).Value = bytes2;
cmd.Parameters.Add("#data3", SqlDbType.Binary).Value = bytes3;
cmd.Parameters.Add("#data4", SqlDbType.Binary).Value = bytes4;
SqlConnection con = new SqlConnection(constr);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
Parameterize your query and clean it up a bit. Hope this helps.
using (SqlConnection con = new SqlConnection("Connection Info"))
{
// Create your parameterized command.
SqlCommand cmd = new SqlCommand("INSERT INTO [property] (name, email, phone, heading, description, location, " +
" image1, image2, image3, image4) VALUES " +
" (#name, #email, #phone, #heading, #description, #location, " +
" ,#image1,#image2,#image3,#image4)", con);
using (cmd)
{
// Set your command type.
cmd.CommandType = CommandType.Text;
// Add your parameters.
cmd.Parameters.AddWithValue("#name", "nameParamHere");
cmd.Parameters.AddWithValue("#email", "emailParamHere");
// and so on until you complete all params.
// Execute your command.
using (SqlDataReader dr = cmd.ExecuteReader()) { };
}
}
Try granting insert to your connection string "USER ID". See this link for more info...
http://beginner-sql-tutorial.com/sql-grant-revoke-privileges-roles.htm
GRANT INSERT
ON [property]
TO {user_name}
[WITH GRANT OPTION];

inserting or updating values into null textboxes

public void Updatecottonpurchase(int slipno, int basicprice, int premium, int totalamountpaid, int weight, int totalamountbasic, int totalamountpremium, int yeildestimates, int farmercode)
{
SqlConnection sqlConn = new SqlConnection(#"Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True");
try
{
string sqlQuery = "UPDATE cottonpurchse SET slipno = '" + slipno + "' , basic price = '" + basicprice + "' , premium = '" + premium + "' , totalamountpaid = '" + totalamountpaid + "' , weight = '" + weight + "' , totalamountbasic = '" + totalamountbasic + "' , totalamountpremium = '" + totalamountpremium + "' , yeildestimated = '" + yeildestimates + "' WHERE farmercode = '" + farmercode + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn);
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
sqlConn.Close();
}
finally
{
sqlConn.Close();
}
}
this is what ive done now yet nothing happens! i want to beable to update the null values but nothing happens! please help
This SQL code:
UPDATE TABLE cottonpurchase SET slipno= WHERE farmercode=
Does nothing, you need to add parameters,
see: http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx
You need to change the code into:
....
string queryString =
"UPDATE TABLE cottonpurchase SET slipno=#slipno WHERE farmercode=#farmercode";
try
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
//define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#slipno";
param.Value = inputfromsomewhere;
SqlParameter param = new SqlParameter();
param.ParameterName = "#farmercode";
param.Value = inputfromsomewhereelse;
//add new parameter to command object
command.Parameters.Add(param);
int result = command.ExecuteNonQuery();
//if result = 1 the update is performed
}
......
You need to add or choose a column for use as the primary key. The primary key should uniquely identify a row, and is used to locate the row to update.

Categories

Resources