Update database with values from textbox - c#

i m trying to edit the values in database through textboxes in ASP.
first i retrived the values from database and set those values to the value property of textboxes on the form so that user can see the old values.
now, i want him to enter new values in the same textboxes and when he click on update the new values should be updated in the database.
can any one tell what i have to do to get those new values????
when to submit the form????
the code:
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label2.Text = ("Please ensure all fields are entered");
Label2.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [MachineGroups] SET ([MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded) WHERE ([MachineGroupID]= #node)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}

You're not providing the #node parameter. so you should get an exception. Also change your sql statement like that without parenthesis :
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET [MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID";
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
EDIT : As you posted your insert page, your table should have an ID column to identify your record uniquely. As I see in your update SQL youe ID column's name is MachineGroupID. So to update your record, you should provide MachineGroupID as #node parameter. try to get this MachineGroupID value in your event and pass it into your Command.

long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET
[MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,
[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID",cn; //add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
example :
SqlCommand cmdup = new SqlCommand("UPDATE [port1] SET [prt1]=#prt1 WHERE [no]= 1", cn);
cmdup.Parameters.Add("#prt1", TextBox1.Text);
cmdup.ExecuteNonQuery();
I think this may help your case, mention Connection at the last of your update command

ok i have the insert page which is working fine with this code.......
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour+DateTime.Now.Minute+DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label1.Text = ("Please ensure all fields are entered");
Label1.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("INSERT [MachineGroups] ([MachineGroupName],[MachineGroupDesc],[TimeAdded]) VALUES (#MachineGroupName,#MachineGroupDesc,#TimeAdded)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}

Related

Update DataGridView Checked Record to the Database

So I have this DataGridView on which there are two columns which I am retrieving from my SQL Server database. Now, in the second column, we have a bit field which shows as a CheckBox in my Windows Application designer. So, I want to, on CellContentClick event be able to update the value that just got deselected into my database. But seems like I am going nowhere.
Here is my code below:
private void gvTurnOffNotifications_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow row in gvTurnOffNotifications.Rows)
{
DataGridViewCheckBoxCell cell = row.Cells[1] as DataGridViewCheckBoxCell;
//We don't want a null exception!
if (cell.Value != null)
{
bool result = Convert.ToBoolean(row.Cells[1].Value);
if (result == true)
{
//It's checked!
btnUpdateTurnOff.Enabled = true;
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
int temp = 1;
bool change = false;
string procedureName = "update UsersNotified Set AllowNotification='" + change + "' where AllowNotification='" + false+ "'";
mySQLCommand = new SqlCommand(procedureName, mySQLConnection);
mySQLCommand.CommandType = CommandType.Text;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
mySQLCommand.ExecuteNonQuery();
}
}
}
}
}
And then when I click on my "Update" button, I want to send the updated griddata for storing in my database as below:
private void btnUpdateTurnOff_Click(object sender, EventArgs e)
{
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
mySQLDataAdapter = new SqlDataAdapter("spGetAllUpdatedNotifications", mySQLConnection);
mySQLDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
DataSet ds = new DataSet();
mySQLDataAdapter.Fill(ds);
mySQLDataAdapter.UpdateCommand = mySQLCommand;
mySQLDataAdapter.Update(ds);
}
}
The spGetAllUpdatedNotifications object in my Update block is a stored procedure I am calling just to retrieve the records from the database so I can update them on the fly in my DataSet. Here is the definition below:
create proc spGetAllUpdatedNotifications
as
begin
SELECT UserName, AllowNotification FROM UsersNotified where AllowNotification=1
end
GO
For more context: When my form loads, I am selecting all the records from the database which have their AllowNotification field set to bit 1 (true in C#) and once a user unticks a specific user (in other words, that user would not be allowed to receive notifications anymore) and once I click on the Update button, it should set the property to false (bit 0 in the database).
Instead of updating the one record which I have deselected, it updates all of them. "All" in this case are the records which have AllowNotification=1. I only want to set AllowNotification=0 for the deselected/unchecked record only
Any suggestions on how I can go about achieving this?
I am not sure what logic makes you to loop thru all the rows of the DataGridView just to update one row in the database.
If you want to update AllowNotification value for the username for which checkbox is checked or unchecked the logic would be this.
Figure out the updated value of the checkbox which is clicked in the gridview.
Store the updated value (True or False) in a boolean variable.
Retrieve the corresponding username of from the other cell of the same row the gridview.
Execute update query with criteria "WHERE UserName = {userName}".
You need to write CellContentClick event of the DataGridView as following.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1) //Assuming Checkbox is displayed in 2nd column.
{
this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
var result = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value;
var userName = this.dataGridView1[0, e.RowIndex].Value; //Assumin username is displayed in fist column
var connectionString = "Your Connection String";
//Set value of your own connection string above.
var sqlQuery = "UPDATE UsersNotified SET AllowNotification = #allowNotification WHERE UserName = #userName";
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(sqlQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#allowNotification", SqlDbType.Bit).Value = result;
command.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = userName;
connection.Open();
command.ExecuteNonQuery();
}
}
}
}
This should help you resolve your issue.
I have a partial solution (It doesn't work a 100% but at least its a step in the right direction):
private void gvTurnOffNotifications_SelectionChanged(object sender, EventArgs e)
{
if (gvTurnOffNotifications.SelectedCells.Count > 0)
{
int selectedrowindex = gvTurnOffNotifications.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = gvTurnOffNotifications.Rows[selectedrowindex];
getUserSelected = Convert.ToString(selectedRow.Cells["UserName"].Value);
MessageBox.Show(getUserSelected);
foreach (DataGridViewRow row in gvTurnOffNotifications.Rows)
{
DataGridViewCheckBoxCell cell = row.Cells[1] as DataGridViewCheckBoxCell;
//We don't want a null exception!
if (cell.Value != null)
{
//It's checked!
btnUpdateTurnOff.Enabled = true;
myConnectionString = ConfigurationManager.ConnectionStrings["FSK_ServiceMonitor_Users_Management.Properties.Settings.FSK_ServiceMonitorConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
bool change = false;
string procedureName = "update UsersNotified Set AllowNotification='" + change + "' where UserName='" + getUserSelected + "'";
//MessageBox.Show(cell.Value.ToString());
mySQLCommand = new SqlCommand(procedureName, mySQLConnection);
mySQLCommand.CommandType = CommandType.Text;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
mySQLCommand.ExecuteNonQuery();
}
}
}
}
}
Problem is that it just takes the first row without me having selected the row I want to deselect.

SQL delete command advice using c#

On click button presents the following code,
For some reason it wont delete data from database, (the dropdownlist is valid) any advice or changes needed?
protected void deleteback_Click(object sender, EventArgs e)
{
// declare variables
String EditNewID = DropDownList3.SelectedItem.Value;
// set connection string to database
String connectionString = WebConfigurationManager.ConnectionStrings["ScrumString"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(connectionString);
// delete values to product backlog
myConnection2.Open();
String query = "DELETE * FROM product_backlog WHERE product_backlog.id = #id ";
SqlCommand commanddelete = new SqlCommand(query, myConnection2);
commanddelete.Parameters.AddWithValue("#id", EditNewID);
// refresh page
Page.Response.Redirect(Page.Request.Url.ToString(), true);
commanddelete.ExecuteNonQuery();
myConnection2.Close();
}
maybe you are creating one string ID instead an integer
Try something like
commanddelete.Parameters.Add("#id", SqlDbType.Int);
commanddelete.Parameters["#id"].Value = Int32.Parse(customerID);

How to AutoFill second TextBox according to first TextBox with the corresponding data in the DataBase

In my winform, there's a datatable with 2 column, 1st one is studentname & 2nd column is StudentAverage.
First txtbx is autosuggest(studentname).
How to make the second txtbx automaticaly fill according to 1st txtbx (2nd txtbx fill with the corresponding record of second column (studentsavrage)?
this is for the 1st txtbx; shows StudentNames
private void txtbxName_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
string StrCmd = "SELECT * FROM School";
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\School_Database.accdb";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
MyConn.Open();
OleDbCommand Cmd = new OleDbCommand(StrCmd, MyConn); ;
OleDbDataReader ObjReader = Cmd.ExecuteReader();
if (ObjReader != null)
{
while (ObjReader.Read())
namesCollection.Add(ObjReader["StudentName"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
ObjReader.Close();
MyConn.Close();
txtbxName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtbxName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtbxName.AutoCompleteCustomSource = namesCollection;
}
I assume you are developing with WinForms.
First out: since a where clause is missing from your query you are not filtering while user inputs text. You should move AutoCompleteStrinCollection fetching in another place if you don't want that.
Your problem: the simplier way here is to manually update the second textbox in your txtbxName_TextChanged method.
private void txtbxName_TextChanged(object sender, EventArgs e)
{
string StrCmd = String.Format( "SELECT AGE FROM School WHERE name '{0', txtbox1.Text");
//perform query as you already do and read result
textbox2.Text = cmd.ExecuteScalar()
}
P.S: in real world things are not done the way you are doing under many many aspects

Populating TextBox, The data type is not valid for the boolean operation

I got a ComboBox with a table as data source, ID as a value member and a name as a display member.
Selecting a name from the ComboBox should populate 6 TextBoxes with data.
Exception:
The data type is not valid for the boolean operation. [ Data type (if known) = int,Data type (if known) = nvarchar ]
Code:
void FillComboBox()
{
//Fill Combo Box
SqlCeDataAdapter da = new SqlCeDataAdapter(" SELECT CustomerID, Name FROM Customers", clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.ValueMember = "CustomerID";
cBox1.DisplayMember = "Name";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.ConnectionString = #"Data Source=|DataDirectory|\Database\Sales.sdf";
clsMain.con.Open();
FillComboBox();
}
private void btnSave_Click(object sender, EventArgs e)
{
//Save Button
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " INSERT INTO Customers (Name, Phone1, Phone2, Address, Notes) VALUES (#Name, #Phone1, #Phone2, #Address, #Notes) ";
cmd.Connection = clsMain.con;
cmd.Parameters.AddWithValue("#Name", txt2.Text.Trim());
if (txt3.Text != "")
{
cmd.Parameters.AddWithValue("#Phone1", Convert.ToInt32(txt3.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone1", Convert.DBNull);
}
if (txt4.Text != "")
{
cmd.Parameters.AddWithValue("#Phone2", Convert.ToInt32(txt4.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone2", Convert.DBNull);
}
cmd.Parameters.AddWithValue("#Address", txt5.Text.Trim());
cmd.Parameters.AddWithValue("#Notes", txt6.Text.Trim());
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (cBox1.SelectedIndex >= 0)
{
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue.ToString();
SqlCeDataAdapter da = new SqlCeDataAdapter(Code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
Table Details:
To follow up on my comment (with the caveat that I have never worked with SQL CE, but I'm pretty sure (99.9%) that this is correct).
In you SQL query string, you surround the customer id with single quotes ('). You use single quotes in SQL ("nomral" SQL at least) for character (char\varchar etc) and date values. You pass numeric values without single quotes.
You didn't indicate what line was giving you the exception, but based on the table structure and what you are doing (you gave good detail in your question, by the way), it seems that the error message is telling you that you're trying to compare an int to a varchar, and that's not allowed (because they are different data types, as the error indicates).
To resolve this, simply remove the single quotes from the value in your WHERE clause and construct your query as follows:
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue;
Thank you, Its working for me.
I am having some customers name in comboBox2. Based on the selected name textbox will return CustomerID and Date of Allocation values.
Following are the code for that:
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if(comboBox2.SelectedIndex>0)
{
con = new SqlCeConnection(s);
con.Open();
string code = "select CustomerID,Date_of_Allocation from lockerdetails
where CustomerName='" + comboBox2.SelectedValue.ToString() + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, con);
SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
textBox1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
textBox5.Text = ds.Tables[0].Rows[0]["Date_of_Allocation"].ToString();
}
}
catch(SystemException se)
{
MessageBox.Show(se.Message);
}

My program seems to be skipping my "If" statement

I have a C# application that submits information to an Access database. I fill in three required boxes , and click "Submit". The script should respond in the following manner when the use clicks the button:
Step 1. Look into database Table A, to see if the value in textBox1 exists in the database.
Step 2. If the value exists, add the values of textBox1, textBox2, and textBox3 into database Table B columns, respectively.
Step 3. If any one of the three text boxes are left blank, display a message.
Step 4. If the value in textBox1 is not in the database table, display a message. (eventually, I plan the replace the message with a default population of the database fields)
THE PROBLEM: When I run the program, in any of the above cases, the result is Step number 4 above. It seems to skip the first "if" statement, and jumping right to the "else" outcome.
Any help resolving this, would be greatly appreciated! The "Private Void "code is below.
Thanks in advance.
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand("select * from script_Orders where cust_Name = #UserID", vcon);
OleDbParameter param = new OleDbParameter();
param.ParameterName = "#UserID";
param.Value = textBox1.Text;
cmd.Parameters.Add(param);
OleDbDataReader reader = cmd.ExecuteReader();
{
if (reader.HasRows)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("You must fill in all fields.");
return;
}
else
{
OleDbCommand dbCommand;
OleDbDataReader dbReader;
new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Search\Database.accdb");
dbCommand = new OleDbCommand("select count(*) as Record_Count from script_received", vcon);
dbReader = dbCommand.ExecuteReader();
if (dbReader.Read() == true)
rowCount = dbReader["Record_Count"].ToString();
else
return;
var date = DateTime.Now.ToString("MM/dd/yyyy");
{
using (OleDbCommand command = new OleDbCommand("INSERT INTO script_Received (script, qty, emp_id, received_Date) VALUES (#script,#qty,#emp_Id,#rec_date)"))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#script", OleDbType.Integer).Value = textBox1.Text;
command.Parameters.Add("#qty", OleDbType.VarChar).Value = textBox2.Text;
command.Parameters.Add("#emp_id", OleDbType.VarChar).Value = textBox3.Text;
command.Parameters.Add("#rec_date", OleDbType.Date).Value = date;
command.Connection = vcon;
command.ExecuteNonQuery();
}
this.textBox1.Clear();
this.textBox2.Clear();
this.textBox1.Focus();
}
}
}
else
{
MessageBox.Show("The value of textBox1 is not in the orders table");
return;
}
}
}
If it jumps to the else of if(reader.HasRows) without throwing any exceptions, then reader must not be null, and it's HasRows property must be false. That means your query executed successfully but returned no rows.
You might try running the select statement by hand, which might help you understand what's wrong. Most likely, you're typing something in the textbox that doesn't match any of the cust_name values.

Categories