c# and sql updating the dataset from a button click - c#

Hi guys i came stuck again. I am wanting to edit a selected row from my datagridview and replace the data from dgv with the new information in the text fields. I have managed to get it to change all the data in the dataset. So what i am asking is for guidance on how to code it so it only edits the selected row.
private void btnEdit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = new SqlCommand(String cmdUpdate = #"update Customer set firstName = #firstName, surname = #surname, email = #email, phonenumber = #phone, mobileNumber = #mobile";
, con);
da.UpdateCommand.Parameters.Add("#firstName", SqlDbType.VarChar).Value = textFirstName.Text;
da.UpdateCommand.Parameters.Add("#surname", SqlDbType.VarChar).Value = textSurname.Text;
da.UpdateCommand.Parameters.Add("#email", SqlDbType.VarChar).Value = textEmail.Text;
da.UpdateCommand.Parameters.Add("#phone", SqlDbType.VarChar).Value = textPhone.Text;
da.UpdateCommand.Parameters.Add("#mobile", SqlDbType.VarChar).Value = textMobile.Text;
da.UpdateCommand.Parameters.Add("#ID", SqlDbType.Int).Value = customerDataSet.Customer[0].ID;
con.Open();
da.UpdateCommand.ExecuteNonQuery();
MessageBox.Show("Customer Edited");
con.Close();
}

You UPDATE query updates whole table you should use WHERE statement in this query to update the row
with current ID
update Customer
set firstName = #firstName,
surname = #surname,
email = #email,
phonenumber = #phone,
mobileNumber = #mobile
WHERE ID=#ID

Related

Using Database Change Notification on multiple tables

I am developing an application in C# where I'm trying to use Oracle Database Change Notification.
When I'm using DCN for one table, everything is working as expected but when I am trying to use two tables, I get the following error: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt", on the line cmd.ExecuteNonQuery();
Here is the code:
string sql = "select rowid, first_name, last_name, salary from employees where employee_id = :1" +
"select country_id, country_name, region_id from countries where country_id = :2";
string constr = "User Id=hr;Password=Parola_007;Data Source=ORCL;Pooling=false";
con = new OracleConnection(constr);
con.Open();
OracleCommand cmd = new OracleCommand(sql, con);
OracleParameter p_id = new OracleParameter();
p_id.OracleDbType = OracleDbType.Decimal;
p_id.Value = 149;
OracleParameter p_id2 = new OracleParameter();
p_id2.OracleDbType = OracleDbType.Varchar2;
p_id2.Value = "BE";
cmd.BindByName = true;
cmd.Parameters.Add(p_id);
cmd.Parameters.Add(p_id2);
OracleDependency dep = new OracleDependency(cmd);
cmd.Notification.IsNotifiedOnce = false;
dep.OnChange += new OnChangeEventHandler(OnDatabaseNotification);
cmd.ExecuteNonQuery();
public static void OnDatabaseNotification(object src, OracleNotificationEventArgs args)
{
string sql = "select rowid, first_name, last_name, salary from employees where rowid = :1" +
"select rowid, country_id, country_name, region from countries where rowid = :2";
OracleParameter p_rowid = new OracleParameter();
p_rowid.Value = args.Details.Rows[0]["rowid"];
OracleParameter p_rowid2 = new OracleParameter();
p_rowid2.Value = args.Details.Rows[1]["rowid"];
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = sql;
cmd.BindByName = true;
cmd.Parameters.Add(p_rowid);
cmd.Parameters.Add(p_rowid2);
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
Console.WriteLine();
Console.WriteLine("Database Change Notification received!");
DataTable changeDetails = args.Details;
Console.WriteLine("Resource {0} has changed.", changeDetails.Rows[0]["ResourceName"]);
Console.WriteLine("Resource {1} has changed.", changeDetails.Rows[1]["ResourceName"]);
dr.Dispose();
cmd.Dispose();
p_rowid.Dispose();
}
Am I doing something wrong?
Thanks.
1: you cannot do 2 sql in 1 command.
2: You can use the table trigger in oracle to check the changed table data. All changes should be logged in a table and only need to be query from that table.
sorry for my english

How to exclude unchanged columns sql table c#

How do I exclude some columns from being modified using SQL Update statement? Here is the code, but I want to update only the columns that user enter data in. Using Windows Forms in C#.
EXAMPLE, I want to update only the Class using the Windows Form
var query="update UserRegistration Set FirstName= #FirstName, LastName=#LastName, Class=#Class, [Password]=#Password WHERE UserID=#UserID";
cmd.Parameters.AddWithValue("#UserID", SqlDbType.VarChar).Value = txtuserid.Text;
cmd.Parameters.AddWithValue("#FirstName", SqlDbType.VarChar).Value = txtfirstname.Text;
cmd.Parameters.AddWithValue("#LastName", SqlDbType.VarChar).Value = txtlastname.Text;
cmd.Parameters.AddWithValue("#Class", SqlDbType.VarChar).Value = txtclass.Text;
You can use ISNULL function. Or an analog in other RDBMS.
Change SQL query like this
update UserRegistration set
FirstName = isnull(#FirstName, FirstName),
LastName = isnull(#LastName, LastName),
Class = isnull(#Class, Class),
[Password] = isnull(#Password, [Password])
where UserID = #UserID;
Also change C# code like this
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value =
txtfirstname.Text == "" ? null : txtfirstname.Text;
Dynamically create a SQL command using only the the field names that are populated. (This is a brute force method, and could be simplified by using a dictionary, but shown like this to make it simpler to understand)
var fieldList = new List<string>();
cmd.Parameters.AddWithValue("#UserID", SqlDbType.VarChar).Value = txtuserid.Text;
if(!string.IsNullOrEmpty(txtfirstname.Text))
{
fieldList.Add("FirstName=#FirstName");
cmd.Parameters.AddWithValue("#FirstName", SqlDbType.VarChar).Value = txtfirstname.Text;
}
if(!string.IsNullOrEmpty(txtlastname.Text))
{
fieldList.Add("LastName=#LastName");
cmd.Parameters.AddWithValue("#LastName", SqlDbType.VarChar).Value = txtlastname.Text;
}
if(!string.IsNullOrEmpty(txtclass.Text))
{
fieldList.Add("Class=#Class");
cmd.Parameters.AddWithValue("#Class", SqlDbType.VarChar).Value = txtclass.Text;
}
var fields = string.Join(',', fieldNames);
var query=$"update UserRegistration SET {fields} WHERE UserId=#UserID";
This means that if you only want to update the first name, the query string becomes:
update UserRegistration SET FirstName=#FirstName WHERE UserId=#UserId

How to Delete rows in database based on Username in ASP.Net?

I am trying to delete few rows by Username. But my sql query apparently not working right. instead of reading the column username, it looks for the name as a column...
Edit: What im trying to achieve is to remove rows with the username John Rose... but insead it says its looking for the column name John Rose
System.Data.SqlClient.SqlException: 'Invalid column name 'Jack Rose'.'
This code is in the checkout button. Im showing the whole code just incase the cause might be outide of the delete query code.
protected void Button1_Click(object sender, EventArgs e)
{
string Username = Session["Username"].ToString();
con.Open();
string query = "INSERT INTO GuestOrder (Order_Id, Username, Order_Date, GrandTotal) values (#Order_Id, #Username, #Order_Date, #GrandTotal)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Order_Id", Label_OrderId.Text);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Order_Date", Label_OrderDate.Text);
cmd.Parameters.AddWithValue("#GrandTotal", Label_Grand.Text);
cmd.ExecuteNonQuery();
con.Close();
string sql = "DELETE FROM Cart WHERE Username =" + Username+"";
con.Open();
SqlCommand cmd1 = new SqlCommand(sql, con);
cmd1.ExecuteNonQuery();
con.Close();
con.Dispose();
string strSQL = "SELECT * FROM GuestOrder";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet("orderdetails");
dt.Fill(ds, "order");
ds.WriteXml(Server.MapPath(#".\xml\orders.xml"));
Response.Redirect("SuccessfulOrder.aspx");
con.Close();
}
You should use this as below:
string sql = "DELETE FROM Cart WHERE Username = #Username";
You need to put username in single quotes as below
string sql = "DELETE FROM Cart WHERE Username = '" + Username+"'";
or You can use parameterized version of this query to avoid the sql injection as
below:
string sql = "DELETE FROM Cart WHERE Username = #Username";

population of texboxes when combobox selected item is changed

Hello all I am trying to populate some textboxes automatically when I select an item from a combobox dropdown list using Microsoft sql server with a usercontrol form. I have written the codes below, however I am getting the items in the combox dropdown list but when I select an item in the combobox dropdown list, nothing happens in the text boxes. the values are in a table called competitors. the columns are Institution, Region, FirstName, LastName and I want the values to display in the respective textboxes when I select the combox dropdown. I seek your assistance in solving this problem. thanks in advance
private void RabbitCare_Load(object sender, EventArgs e)
{
CBoxParishDdlist.Items.Clear();
SqlConnection connect = new SqlConnection(#"Data Source=ITSPECIALIST\SQLPROJECTS;Initial Catalog=EXPRORESULTS;Integrated Security=True ");
connect.Open();
SqlCommand cmd = connect.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select ParishName FROM Competitors WHERE CompetitiveEventName = 'Care and Management of Bees'";
cmd.ExecuteNonQuery();
DataTable dat = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
SDA.Fill(dat);
foreach (DataRow DAR in dat.Rows)
{
CBoxParishDdlist.Items.Add(DAR["ParishName"].ToString());
}
connect.Close();
}
private void CBoxParishDdlist_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection(#"Data Source=ITSPECIALIST\SQLPROJECTS;Initial Catalog=EXPRORESULTS;Integrated Security=True ");
connect.Open();
cmd = new SqlCommand("SELECT * FROM Competitors WHERE ParishName = '" + CBoxParishDdlist.Text + "'", connect);
cmd.ExecuteNonQuery();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
string Institution = (string)dr["Institution"].ToString();
TxtBoxInstitution.Text = Institution;
string Region = (string)dr["Region"].ToString();
TxtBoxRegion.Text = Region;
string FirstName = (string)dr["FirstName"].ToString();
TxtBoxFname.Text = FirstName;
string LastName = (string)dr["LastName"].ToString();
TxtBoxLname.Text = LastName;
}
connect.Close();
I think this will solve your problem.
TxtBoxInstitution.Text = comboBoxName.SelectedItem.ToString();

Update data in SQL Server database

I have registration as my database table. I want to update my information that has key in by the user into my SQL Server database. But it won't work, it don't occur any errors but the data key in wouldn't update into my database. Someone please help me if anything wrong with my code? Thanks.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE registration SET username = #username, password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno", con);
con.Open();
cmd.Parameters.AddWithValue("#username", TextBoxUsername.Text);
cmd.Parameters.AddWithValue("#password", TextBoxPassword.Text);
cmd.Parameters.AddWithValue("#retypepassword", TextBoxRPassword.Text);
cmd.Parameters.AddWithValue("#gender", DropDownListGender.Text);
cmd.Parameters.AddWithValue("#birth", DropDownListDay.Text);
cmd.Parameters.AddWithValue("#address", TextBoxAddress.Text);
cmd.Parameters.AddWithValue("#city", TextBoxCity.Text);
cmd.Parameters.AddWithValue("#country", DropDownListCountry.Text);
cmd.Parameters.AddWithValue("#postcode", TextBoxPostcode.Text);
cmd.Parameters.AddWithValue("#email", TextBoxEmail.Text);
cmd.Parameters.AddWithValue("#carno", TextBoxCarno.Text);
cmd.ExecuteNonQuery();
con.Close();
if (IsPostBack)
{
Response.Redirect("UpdateSuccess.aspx");
}
After I click confirm it somehow only update my column gender which from male to female, others column of data it won't update.
It might be because the #username is used both in UPDATE and WHERE. If it changes, the WHERE will be wrong and if it does not change it can be left out of the query.
sql update
SqlCommand cmd = new SqlCommand("update[Testing].[dbo].[student] set name= '" + tb1.Text + "',age='" + tb2.Text + "',mobile='" + tb3.Text+ "' where id = '" + tb4.Text + "'", con);
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM registration WHERE username = " + TextBoxUsername.Text + "UPDATE registration SET username = #username, password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno", con);
con.Open();
cmd.Parameters.AddWithValue("#username", TextBoxUsername.Text);
cmd.Parameters.AddWithValue("#password", TextBoxPassword.Text);
cmd.Parameters.AddWithValue("#retypepassword", TextBoxRPassword.Text);
cmd.Parameters.AddWithValue("#gender", DropDownListGender.Text);
cmd.Parameters.AddWithValue("#birth", DropDownListDay.Text);
cmd.Parameters.AddWithValue("#address", TextBoxAddress.Text);
cmd.Parameters.AddWithValue("#city", TextBoxCity.Text);
cmd.Parameters.AddWithValue("#country", DropDownListCountry.Text);
cmd.Parameters.AddWithValue("#postcode", TextBoxPostcode.Text);
cmd.Parameters.AddWithValue("#email", TextBoxEmail.Text);
cmd.Parameters.AddWithValue("#carno", TextBoxCarno.Text);
cmd.ExecuteNonQuery();
con.Close();
if (IsPostBack)
{
Response.Redirect("UpdateSuccess.aspx");
}
I think in page load you are load again all data and Button1_Click run after page load and you lost are all data
you can try your code in page_load method
private void Page_Load()
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE registration SET username = #username, password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno " + "WHERE username = #username", con);
con.Open();
.
.
.
}
}
I have never seen that type of syntax. Usually if one is using parameters, one is using a stored proc (the best practice). If one is using inline SQL, one builds the SQL statement as a single text line and executes it. I would recommend recoding for one of those.
If you want to try what you've started, in your SQL, you probably need to declare all the variables first. For example
SqlCommand cmd = new SqlCommand("declare #username varchar(100), #password varchar(100),
#retypepassword varchar(100) #gender varchar(10), #birth date, #address varchar(100),
#city varchar(100) #country varchar(100), #postcode varchar(10), #email varchar(100),
#carno varchar(100) UPDATE registration SET username = #username, password = #password,
retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address,
city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno",
con);

Categories