i am creating c# project so far insert and delete buttons are working but when i hit update button it gives data has not been updated and i cant see what is wrong with my code please help
public bool Update(Classre c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
string sql = "UPDATE Class SET ClassName=#ClassName,ClassLevel=#ClassLevel WHERE ClassID=#ClassID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#ClassName", c.ClassName);
cmd.Parameters.AddWithValue("#ClassLevel", c.ClassLevel);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
and this is my update button code where i call the class that holds my update code
private void button3_Click(object sender, EventArgs e)
{
c.ClassID = int.Parse(textBox1.Text);
c.ClassName = textBox2.Text;
c.ClassLevel = comboBox1.Text;
bool success = c.Update(c);
if (success == true)
{
// label4.Text = "Data Has been updated";
MessageBox.Show("Data Has been updated");
DataTable dt = c.Select();
dataGridView1.DataSource = dt;
}
else
{
//label4.Text = "Data Has not been updated";
MessageBox.Show("Data Has not been updated");
}
}
I would prefer to use a stored procedure instead of pass through sql but you could greatly simplify this. As stated above your try/catch is worse than not having one because it squelches the error.
public bool Update(Classre c)
{
USING(SqlConnection conn = new SqlConnection(myconnstring))
{
string sql = "UPDATE Class SET ClassName = #ClassName, ClassLevel = #ClassLevel WHERE ClassID = #ClassID";
USING(SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#ClassName", SqlDbType.VarChar, 4000).Value = c.ClassName;
cmd.Parameters.Add("#ClassLevel", SqlDbType.Int).Value = c.ClassLevel;
cmd.Parameters.Add("#ClassID", SqlDbType.Int).Value = c.ClassID;
conn.Open();
int rows = cmd.ExecuteNonQuery();
return rows > 0;
}
}
}
Related
I ask these question coz i really don't know how i'm gonna do that and is it possible to do that?
What i want is to update/change here for example STA-100418-100 in database values, update/change the 100 based on the user input, like 50 it will be STA-100418-50.
Here's the provided image to be more precise
As you can see on the image, there's a red line, if user update the quantity as 60, In Codeitem STA-100418-100 should be STA-100418-60
I really have no idea on how to do that. I hope someone would be able to help me
here's my code for updating the quantity
private void btn_ok_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.ExecuteNonQuery();
}
}
}
Here's the code to get that format in codeitems
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
Here's what I use to update SQL-Server
public static DataTable GetSqlTable(string sqlSelect)
{
string conStr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(conStr);
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (connection.State != ConnectionState.Open)
{
return table;
}
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
try
{
adapter.Fill(table);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
connection.Close();
connection.Dispose();
return table;
}
public static void GetSqlNonQuery(string sqlSelect)
{
string newObject = string.Empty;
string strConn = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(strConn);
connection.Open();
if (connection.State != ConnectionState.Open)
{
return;
}
try
{
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
cmd.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
string x = ex.Message + ex.StackTrace;
throw;
}
}
Here's how to use it
DataTable dt = GetSqlTable("select Quantity from product where CodeItem = 'STA-100418-100'");
string strQuantity = dt.Rows[0]["Quantity"].ToString();
GetSqlNonQuery(string.Format("UPDATE product SET CodeItem = '{0}' WHERE = 'STA-100418-100'", strQuantity));
User will input everytime in the Quantity textbox, the textchanged event of Quantity will be hit and you will get new value everytime with the same date but with different quantity. So you can use the Code.Text to update the CodeDateTime value or you can use a global variable instead of Code.Text and use it to update the column.
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity, CodeItem = #Code where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.Parameters.Add("#Code", Code.Text);
}
}
as I understand it you need MSSQL String Functions
SELECT rtrim(left(Codeitem,charindex('-', Codeitem))) + ltrim(str(Quantity)) FROM ...
For detailed information
Using MySql, Substring the code item and then concatenate the quantity.
UPDATE Product_Details SET quantity = #quantity,CodeIem = CONCAT(SUBSTR(#code,1,11),#quantity) WHERE ProductID= #ProductID
protected void Btn_CheckOut_Click(object sender, EventArgs e)
{
int result = 0;
Payment user = new Payment(txt_CardNumber.Text, txt_CardHolderName.Text, txt_ExpirationDate.Text, txt_Cvv.Text);
result = ProductInsert();
/* Session["CardNumber"] = txt_CardNumber.Text;
Session["CardHolderName"] = txt_CardHolderName.Text;
Session["ExpirationDate"] = txt_ExpirationDate.Text;
Session["Cvv"] = txt_Cvv.Text;*/
Response.Redirect("Payment Sucessful.aspx");
}
public int ProductInsert()
{
int result = 0;
string queryStr = "INSERT INTO CustomerDetails(CardNumber, CardHolderName, ExpirationDate, Cvv)"
+ "values (#CardNumber,#CardHolderName, #ExpirationDate, #Cvv)";
try
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#CardNumber", this.CardNumber);
cmd.Parameters.AddWithValue("#CardHolderName", this.CardHolderName);
cmd.Parameters.AddWithValue("#ExpirationDate", this.ExpirationDate);
cmd.Parameters.AddWithValue("#Cvv", this.Cvv);
conn.Open();
result += cmd.ExecuteNonQuery(); // Returns no. of rows affected. Must be > 0
conn.Close();
return result;
}
catch (Exception ex)
{
return 0;
}
}
}
I am trying to store credit card informations into database. I have created a productInsert() method and now I am trying to insert whatever values into the database.
This code is giving the error:
ProductInsert() does not exist in current context
I Bind Data to a DataGridview using the following code
private void BindGrid()
{
try
{
string constr = "Data Source=INSPIRE-1;" +
"Initial Catalog=testdatabase;" +
"User id=testuser;" +
"Password=tester;";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM mytable", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
if (flag == false)
{
flag = true;
DataGridViewButtonColumn uninstallButtonColumn = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Edit";
uninstallButtonColumn.Text = "Edit";
dataGridView1.Columns.Insert(4, uninstallButtonColumn);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
I Update the selected record by hooking to a button click event in the datagridview row like this
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex ==4)
{
button4.Enabled = false;
try
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[0].Value;
using (SqlConnection conn = new SqlConnection(constr))
{
try
{
conn.Open();
SqlDataReader myReader = null;
string commandText = "select * from mytable where name= #name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("#name", orderId);
myReader = command.ExecuteReader();
while (myReader.Read())
{
textBox1.Text = myReader["name"].ToString();
textBox2.Text = myReader["age"].ToString();
textBox3.Text = myReader["phone"].ToString();
textBox4.Text = myReader["address"].ToString();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
catch (Exception error)
{
}
}
}
Now i update the values using the code below
private void button5_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(constr))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE mytable SET name=#NewName,age=#NewAge,phone=#NewPhone,Address=#NewAddress" +
" WHERE name=#oldname", conn))
{
cmd.Parameters.AddWithValue("#NewName", textBox1.Text);
cmd.Parameters.AddWithValue("#NewAge", textBox2.Text);
cmd.Parameters.AddWithValue("#NewPhone", textBox3.Text);
cmd.Parameters.AddWithValue("#NewAddress", textBox4.Text);
cmd.Parameters.AddWithValue("#oldname", orderId);
try
{
int rows = cmd.ExecuteNonQuery();
MessageBox.Show("Updated Successfully");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
BindGrid();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
button4.Enabled=true;
}
But after i click the Update Button then click on the Button Column corresponding to a Row e.ColumnIndex always returns 0.
What im i doing wrong?
UPDATE :
Please see the screenshot
Rahul's Answer will work but looks like orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[0].Value; should be modifiled to get Cells[1].Value and not 0 as 0 is the button cell from 2nd time onwards. But for 1st time you need to use 0 as then button is at index 4. Try below changes.
As far as I understand, issue is after update, you call the BindGrid again and since flag is true it just sets the datasource again for the grid and not generating button again thus button gets moved to index 0 followed by the datatable columns.
Another way to solve is modify your code a bit like
dataGridView1.Columns.Insert(0, uninstallButtonColumn);
dataGridView1.Columns[0].DisplayIndex = 4;
And then in CellClick event check for e.ColumnIndex == 0. This help you in showing the button at the position you want and always the click work as the columnindex never changes.
you can check button index like below without comparing its index:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
//TODO - Button Clicked - Execute Code Here
}
}
I am getting this error
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
I read this question and it states that the exception is caused because of not closing the connection. However, i close all the connection in my code
This is my code, it is simple
public partial class index : System.Web.UI.Page
{
private static string defaultReason = "reason not selected";
protected override object SaveViewState()
{
//save view state right after the dynamic controlss added
var viewState = new object[1];
viewState[0] = base.SaveViewState();
return viewState;
}
protected override void LoadViewState(object savedState)
{
//load data frm saved viewstate
if (savedState is object[] && ((object[])savedState).Length == 1)
{
var viewState = (object[])savedState;
fillReasons();
base.LoadViewState(viewState[0]);
}
else
{
base.LoadViewState(savedState);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string callIDValue = Request.QueryString["CallID"];
string callerIDValue = Request.QueryString["CallerID"];
if (!String.IsNullOrEmpty(callerIDValue))
{
callerID.Value = callerIDValue;
if (!String.IsNullOrEmpty(callIDValue))
{
string query = "INSERT INTO Reason (callerID, callID, reason, timestamp) VALUES (#callerID, #callID, #reason, #timestamp)";
SqlConnection con = getConnection();
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("#callerID", callerIDValue);
command.Parameters.AddWithValue("#callID", callIDValue);
command.Parameters.AddWithValue("#reason", defaultReason);
command.Parameters.AddWithValue("#timestamp", DateTime.Now.ToString());
try
{
con.Open();
command.ExecuteNonQuery();
command.Dispose();
con.Close();
}
catch (Exception ee)
{
command.Dispose();
con.Close();
message.InnerHtml = ee.Message;
}
}
else
{
message.InnerHtml = "Call ID is empty";
}
}
else
{
callerID.Value = "Undefined";
message.InnerHtml = "Caller ID is empty";
}
fillReasons();
}
else
{
}
}
private void fillReasons()
{
string query = "SELECT * FROM wrapuplist WHERE isEnabled = #isEnabled";
SqlConnection con = new SqlConnection(getConnectionString());
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("isEnabled", true);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable results = new DataTable();
da.Fill(results);
int numberOfReasons = 0; // a integer variable to know if the number of the reasons becomes able to be divided by four
HtmlGenericControl div = null;
foreach (DataRow row in results.Rows)
{
numberOfReasons++;
if ((numberOfReasons % 4) == 1)
{
div = new HtmlGenericControl("div");
div.Attributes.Add("class", "oneLine");
}
RadioButton radioButton = new RadioButton();
radioButton.ID = "reason_" + row["reasonName"].ToString();
radioButton.GroupName = "reason";
radioButton.Text = row["reasonName"].ToString();
div.Controls.Add(radioButton);
if (numberOfReasons % 4 == 0)
{
myValueDiv.Controls.Add(div);
//numberOfReasons = 0;
}
else if (numberOfReasons == results.Rows.Count)
{
myValueDiv.Controls.Add(div);
//numberOfReasons = 0;
}
}
cmd.Dispose();
da.Dispose();
con.Close();
}
private SqlConnection getConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["vmpcon"].ConnectionString);
}
private string getConnectionString()
{
return ConfigurationManager.ConnectionStrings["wrapupconnection"].ConnectionString.ToString();
}
protected void buttonSaveClose_Click(object sender, EventArgs e)
{
var divcontrols = myValueDiv.Controls.OfType<HtmlGenericControl>();
bool isFound = false;
RadioButton checkedRadioButton = null;
foreach (HtmlGenericControl loHTML in divcontrols)
{
var checkedRadioButtons = loHTML.Controls.OfType<RadioButton>().Where(radButton => radButton.Checked).ToList();
foreach (RadioButton lobtn in checkedRadioButtons)
{
if (lobtn.Checked)
{
isFound = true;
checkedRadioButton = lobtn;
}
}
}
if (isFound)
{
sReasonError.InnerText = "";
string reason = "";
reason = checkedRadioButton.Text;
string callIDValue = Request.QueryString["CallID"];
string callerIDValue = Request.QueryString["CallerID"];
if (String.IsNullOrEmpty(callIDValue))
{
message.InnerText = "Call ID is empty";
}
else if (String.IsNullOrEmpty(callerIDValue))
{
message.InnerText = "Caller ID is empty";
}
else
{
message.InnerText = "";
string query2 = "SELECT * FROM Reason WHERE callID = #callID AND reason != #reason";
SqlConnection con = getConnection();
SqlCommand command2 = new SqlCommand(query2, con);
command2.Parameters.AddWithValue("#callID", callIDValue);
command2.Parameters.AddWithValue("#reason", defaultReason);
con.Open();
if (command2.ExecuteScalar() != null)
{
message.InnerText = "Already saved";
command2.Dispose();
con.Close();
}
else
{
command2.Dispose();
con.Close();
string notes = taNotes.InnerText;
string query = "UPDATE Reason SET reason = #reason, notes = #notes, timestamp = #timestamp WHERE callID = #callID";
SqlCommand command = new SqlCommand(query, con);
command.Parameters.AddWithValue("#callID", callIDValue);
command.Parameters.AddWithValue("#reason", reason);
command.Parameters.AddWithValue("#notes", notes);
command.Parameters.AddWithValue("#timestamp", DateTime.Now.ToString());
try
{
con.Open();
command.ExecuteNonQuery();
command.Dispose();
con.Close();
message.InnerText = "Done Successfully";
//ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>");
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}
catch (Exception ee)
{
command.Dispose();
con.Close();
message.InnerText = "Error, " + ee.Message;
}
}
}
}
else
{
sReasonError.InnerText = "Required";
message.InnerText = "Select a reason";
//fillReasons();
}
}
}
as you see, all the connection are being closed, what wrong did I do please?
Closing connections and disposing should be in a finally block while using a try catch.
or use a using block like the one below
using(SqlConnection con = getConnection())
{
con.Open();
//Do your operation here. The connection will be closed and disposed automatically when the using scope is exited
}
I have a form in ASP.NET that loads data if it exists for the user, and then allows them to update. So in Page_Load I have:
protected void Page_Load(object sender, EventArgs e)
{
if (!CheckAndAddRecord(_currentUser.UserID))
{
CreateEntryPoint(_currentUser.UserID);
}
else
{
DataView dv = LoadApplicationData(_currentUser.UserID);
foreach (DataRowView rowView in dv)
{
DataRow row = rowView.Row;
_applicationId = row["id"].ToString();
txtProjectNumber.Text = row["ProjectNumber"].ToString();
if (String.IsNullOrEmpty(chkSignedNDANo.ToString()) || String.IsNullOrEmpty(chkSignedNDAYes.ToString()))
{
chkSignedNDANo.Checked = Convert.ToBoolean(row["SignedNDAOnFile"]);
chkSignedNDAYes.Checked = Convert.ToBoolean(row["SignedNDAOnFile"]);
}
txtDateWritten.Text = row["DateWritten"].ToString();
}
}
}
It calls this method:
public bool CheckAndAddRecord(int UserId)
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("CheckUserInTemp", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#SubmittedBy", UserId));
SqlDataAdapter dap = new System.Data.SqlClient.SqlDataAdapter(cmd);
DataSet ds = new DataSet();
// open conn
if (conn.State == ConnectionState.Closed)
conn.Open();
// fill
dap.Fill(ds);
// close the conn
if (conn.State == ConnectionState.Open)
conn.Close();
bool boolRecordExist = false;
if (ds.Tables[0].DefaultView.Count == 0)
{
boolRecordExist = false;
}
else
{
boolRecordExist = true;
}
return boolRecordExist;
}
This seems to work and populate the fields correctly. But then to update I call a Button click, which calls this method:
public void UpdateRecordInTemp(int appId, string projectNumber)
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("CPC_ProposalUpdateTemp", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", appId);
cmd.Parameters.AddWithValue("#ProjectNumber", txtProjectNumber.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Exception adding coupon. " + ex.Message);
}
finally
{
conn.Close();
}
}
The problem is the fields passed always contain the old values. So if the value when entering the page is "123" and I change it to "abc" and click the button, "123" is passed instead of "abc".
Sorry for the long post, I wanted to get all the details in. I am baffled by this. Thanks!
At page Load check IsPostBack property in if. It seems that your code is executing on every page load.
if(!IsPostBack)
{
// Do your work
}
UPDATE
In your code method UpdateRecordInTemp(int appId, string projectNumber) you are not using projectNumber instead you are using txtProjectNumber.Text