Update is not working nor throwing an error - c#

I trying to update a record from ASP.Net page but there is no problem with the script and I am not receiving any error. Any suggestion are appreciated.
protected void update()
{
try
{
using (SqlConnection con = new SqlConnection(str))
{
string command = #"update dbo.Programs set ProgCode=#ProgCode,ProgTitle=#ProgTitle,ProgDescription=#ProgDescription,ProgBudget=#ProgBudget,ProgStartDate=#ProgStartDate,ProgEndDate=#ProgEndDate where ProgId=#ProgId";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#ProgId", Request.QueryString["UpdProg"]);
cmd.Parameters.AddWithValue("#ProgCode", Code.Text);
cmd.Parameters.AddWithValue("#ProgTitle", Titlebox.Text);
cmd.Parameters.AddWithValue("#ProgDescription", Description.Text);
cmd.Parameters.AddWithValue("#ProgBudget", Budget.Text);
cmd.Parameters.AddWithValue("#ProgStartDate", StartDate.Text);
cmd.Parameters.AddWithValue("#ProgEndDate", EndDate.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Status.Text = ex.ToString();
}
}
When the Update button is clicked this method is executed:
protected void UpdateRecord(object sender, EventArgs e)
{
update();
}
Thank you for your comments the problems is solved i was calling another method (UpdateSelector) on Page_Load that was making the problem

Related

Adding values of one table into another with INSERT INTO ... SELECT

I need to add value to table sales(acnum,scriptname,shares_bought) from transac(acnum,scriptname,Quantity,Price) using c# in visual studio 2008. I am using the code shown below, but it is not inserting value into sales database.
It is not showing any error or exception but its not updating sales table also.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
Con.Open();
string insertsale = "INSERT INTO sales(acnum, scriptname, shares_bought) select acnum,scriptname,Quantity from transac";
SqlCommand cmd = new SqlCommand(insertsale, Con);
cmd.ExecuteNonQuery();
Con.Close();
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
The problem was that I had used PostUrl for the button click . . so i think it was redirecting to the nextpage without processing the code. Now its fixed .

Datagridview cell value change update database

I have retrieved data from Mysql database into a DataGridView1. Let us suppose I am in Row 0. When I change the contents of Row 0, Cell 1 and press enter key or a button, the Update query should modify that row, but I am unable to modify the value of the cell. The cell maintains its previous value when i reload data and the database is not modified. For example, if I change the contents of a cell under column Client_Name from "Acs" to "Gmt", how can I change the value of the cell from "Acs" to "Gmt"? and to have it updated into Mysql database, I am using c# in Vs 2012. below is my code that retrieves my database into datagridview1 any help is welcomed thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data.SqlClient;
namespace PI.Gen
{
public partial class frmMain : Form
{
MySqlConnection Conn;
public frmMain()
{
InitializeComponent();
btnDisconnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
string strConnect = "server=" + txtServer.Text + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text + ";database=" + txtDatabase.Text;
try
{
if (txtServer.TextLength <= 0 || txtUsername.TextLength <= 0 || txtDatabase.TextLength <= 0)
{
MessageBox.Show("You have an empty database connection field. Please supply a valid value.");
return;
}
Conn = new MySqlConnection(strConnect);
Conn.Open();
if (Conn.State.ToString() != "Open")
{
MessageBox.Show("Could not open database connection");
return;
}
btnDisconnect.Enabled = true;
btnConnect.Enabled = false;
btnLoadData.Enabled = true;
btnLoadClients.Enabled = true;
// btnSubmitClient.Enabled = true;
}
catch (Exception ex) // catch on general exceptions, not specific
{
MessageBox.Show(ex.Message);
return;
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (Conn != null)
{
Conn.Close();
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
try
{
Conn.Close();
Conn = null;
btnDisconnect.Enabled = false;
btnConnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadData_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_receipients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadClients_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_clients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
After series of trials and error, i finally found what i was looking for, thus being able to update database from datagridview below is my worked around code which works 100% hope it helps someone in future, and thanks #RageComplex for helping out, but one more thing does anyone know how to implement that i mean instead of hitting the enter button to take changes in the datagridview you rather click on a button ty
private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
{
try
{
DataTable changes = ((DataTable)dataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)dataGridView1.DataSource).AcceptChanges();
MessageBox.Show("Cell Updated");
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You are not updateing your changes to the database. While you keep your connection open doesn't mean that this will automatically update your data.
First of all, don't keep your connection open. In your app you have a connect button which is good for testing but not for really keeping the connection open, not with databases in my opinion.
The way you load data is correct.
You give the datagridview an DataSource which is a table from your DataSet. So changes made in the datagridview ARE saved to your DataSet but not to your database.
This is how you update your database
public void UpdateTable(DataSet ds)
{
using (MySqlConnection connect = new MySqlConnection(ConnString))
{
connect.Open();
MySqlDataAdapter adapt = new MySqlDataAdapter();
MySqlCommandBuilder commbuilder = new MySqlCommandBuilder(adapt);
adapt.SelectCommand = new MySqlCommand("SELECT * FROM t_receipients", connect);
adapt.Update(ds.Tables[0]);
}
}
Make sure, before you Update your database, you use datagridview1.EndEdit()
Also, you using, this will ensure a connection is closed again after completing that code, best is to always have it in a try-except.
You had struggles with connecting the database as it appears to be in the commends.
I've also forgot to include MySqlDataAdapter above, I used an adapter globally in that case.
I didn't want to report this question as duplicated, but now it kinda does look like this answer.
I would like to give code which I have tested in my application.I used it for button click event.
private void button3_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
string MyConnection2 = "server=localhost;user id=root;password=;database=k";
using (MySqlConnection conn = new MySqlConnection(MyConnection2))
{
using (MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
StrQuery = #"update s set Quantity='" + dataGridView3.Rows[i].Cells["Quantity"].Value.ToString() + "' where No='" + dataGridView3.Rows[i].Cells["Item No"].Value.ToString() + "';";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch
{
}
}
I think it may help you

How do I search for values in a database using a value from a seperate database?

I'm making a system for checking bookings online using a booking ID, I've done all the code and when I run my application on the web browser it appears to disconnect with the message "Problem loading page"
this is the code used for checking the system when pressing the button
protected void Button1_Click(object sender, EventArgs e)
{
int custval = 70757;
if (BookID.Text == Convert.ToString(custval))
{
try
{
SqlConnection GuestBookings = new SqlConnection("Data Source=dell-vostro;Initial Catalog=HotelConference;Persist Security Info=True;User ID=website_application_testing;Password=***********");
SqlCommand sc = new SqlCommand();
sc.Connection = GuestBookings;
GuestBookings.Open();
sc.CommandText = ("SELECT CustomerFirstName, CustomerLastName FROM tblBookingGuests WHERE BookingID="+BookID.Text+")");
sc.ExecuteNonQuery();
GuestBookings.Close();
}
catch (Exception ex)
{
}
}
}

ASP.NET 2.0 C# Insert to database not working

I have an asp.net wizard control in my web application I am calling a stored procedure from code behind to insert data into database. Executing the proc in SSMS works fine and I had gotten this block to work once before and made changes (i unfortunately cannot remember which changes i made). My problem is that when the next button is clicked no errors are thrown and also no data is written to the database. I have tested by adding exception into the cnx2 try block and the exceptions were thrown so I know the code is executing to the place I want it to but it is still not inserting. Any help is appreciated Thank you. And please if there is any information i can add that may help let me know
protected void onNextButtonClick(object sender, EventArgs e)
{
if (Wizard1.ActiveStepIndex.Equals(1))
{
page1Submit();
}
else if (Wizard1.ActiveStepIndex.Equals(2))
{
page2Submit();
}
else if (Wizard1.ActiveStepIndex.Equals(3))
{
page3Submit();
}
else if (Wizard1.ActiveStepIndex.Equals(8))
{
page8submit();
}
}
protected void page1Submit()
{
string hispanic;
if (cbIsHispanic.Checked)
{
hispanic = "1";
}
else
{
hispanic = "0";
}
bool newReport = true;
SqlConnection cnx = new SqlConnection(server);
SqlCommand cmd = new SqlCommand("[ReportCheckExists]", cnx);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#reportNumber", dReportNumber.Text.ToString());
try
{
cnx.Open();
int rowCount = Convert.ToInt32(cmd.ExecuteScalar());
cnx.Close();
if (rowCount > 0)
{
newReport = false;
}
}
catch (Exception ex)
{
throw new Exception("Error executing MyProcedureName.", ex);
}
if (newReport)
{
SqlConnection cnx2 = new SqlConnection(server);
SqlCommand cmd2 = new SqlCommand("[NewReport]", cnx2);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("#reportNumber", dReportNumber.Text.ToString());
try
{
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
}
catch (Exception ex)
{
throw new Exception("Error executing MyProcedureName.", ex);
}
}
else
{
string strJavaScript = "<script language = javascript type=text/Javascript> alert('That report number already exists. If you need to modify a report select it from the main menu or enter the report number again.')</script>";
this.Page.RegisterClientScriptBlock("Key4", strJavaScript);
Wizard1.ActiveStepIndex = 0;
}
}
It's probably because you are executing the cmd command, and not cmd2 in your second try catch block

Use ContentEditable to Save Into DB With ASP.NET?

I'm trying to create a web page where a user can edit the text and when they are done, they hit save and the new text entered is saved into the database.
I'm not getting any errors in my code, but for some reason, the old text is just being rewritten into the db instead of the new text.
Here is my code-behind:
protected void saveBtn_Click(object sender, EventArgs e)
{
string newName;
string newIntro;
string newEduc;
string newWork;
h1New.Text = h1.Text;
newName = h1New.Text;
newIntro = intro.Text;
newEduc = educ.Text;
newWork = employ.Text;
string connectionInfo = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionInfo))
{
connection.Open();
SqlCommand myCommand = new SqlCommand("UPDATE simpleContent SET userName = #newName, infoContent = #newIntro, educContent = #newEduc, workContent = #newWork WHERE userID = #userName", connection);
try
{
string username = HttpContext.Current.User.Identity.Name;
myCommand.Parameters.AddWithValue("#userName", username.ToString());
myCommand.Parameters.AddWithValue("#newName", newName.ToString());
myCommand.Parameters.AddWithValue("#newIntro", newIntro.ToString());
myCommand.Parameters.AddWithValue("#newEduc", newEduc.ToString());
myCommand.Parameters.AddWithValue("#newWork", newWork.ToString());
myCommand.ExecuteNonQuery();
connection.Close();
}
catch
{
Response.Redirect("http://www.google.co.uk");
}
}
}
I would appreciate any pointers that you may have.
try to put you code in format:
protected void saveBtn_Click(object sender, EventArgs e)
{
// add variables
string connectionInfo = (...)
string commandText = (...)
using (...){
SqlCommand myCommand = (...)
// add parameters
try
{
connection.Open();
myCommand.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
(...)
}
}

Categories

Resources