Record not updated in Database - c#

I am unable to update record in my database.
my code is as follows:
private void update_Click(object sender, EventArgs e)
{
con.Open();
try
{
string strQuery = "UPDATE test_name SET Test_Name = #name, Price = #price, Lab_Price = #lprice, normal_value_child = #child, normal_value_men = #men, normal_value_women = #women, notes = #note, unit = #un, SubGroup = #sub, MainGroup = #main" +
"WHERE Test_Id = #tstID";
using (System.Data.SqlServerCe.SqlCeCommand cmdSelect = new System.Data.SqlServerCe.SqlCeCommand(strQuery, con))
{
cmdSelect.Parameters.AddWithValue("#tstID", richTextBox2.Text);
cmdSelect.Parameters.AddWithValue("#name", richTextBox1.Text);
cmdSelect.Parameters.AddWithValue("#price", richTextBox7.Text);
cmdSelect.Parameters.AddWithValue("#lprice", richTextBox8.Text);
cmdSelect.Parameters.AddWithValue("#child", richTextBox5.Text);
cmdSelect.Parameters.AddWithValue("#men", richTextBox4.Text);
cmdSelect.Parameters.AddWithValue("#women", richTextBox3.Text);
cmdSelect.Parameters.AddWithValue("#note", richTextBox9.Text);
cmdSelect.Parameters.AddWithValue("#un", richTextBox6.Text);
cmdSelect.Parameters.AddWithValue("#sub", comboBox2.Text);
cmdSelect.Parameters.AddWithValue("#main", comboBox1.Text);
cmdSelect.ExecuteNonQuery();
updatedb();
con.Close();
}
}
catch (Exception ex)
{
}
this.test_nameTableAdapter2.Fill(this.datalabDataSet14.test_name);
MessageBox.Show("Updated Successfully");
}
}
I don't understand what's the problem.

Add space before WHERE:
string strQuery = "UPDATE test_name SET Test_Name = #name, Price = #price, Lab_Price = #lprice, normal_value_child = #child, normal_value_men = #men, normal_value_women = #women, notes = #note, unit = #un, SubGroup = #sub, MainGroup = #main" +
" WHERE Test_Id = #tstID";

Related

Adding data from SQL Server table into textbox when entering data in another textbox

Here is my program:
What I want to do: when I enter 1 in ProductID textbox, I want category, name and price for ProductID = 1 to be filled into their textboxes.
I have tried to read from product table where ProductID = ProductIDTB.Text and then changed the other textboxes to show the data inside the other columns
Here is my code when ProductID textbox is changed:
protected void ProductIDTB_TextChanged(object sender, EventArgs e)
{
string connectionString1;
SqlConnection cnn1;
connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
cnn1 = new SqlConnection(connectionString1);
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = ('" + Convert.ToInt32(ProductIDTB.Text) + "') ";
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
try
{
cnn1.Open();
using (SqlDataReader read = com1.ExecuteReader())
{
while (read.Read())
{
String productcategory = Convert.ToString(read["ProductCategory"]);
ProductCategoryTB.Text = productcategory;
String productname = Convert.ToString(read["ProductName"]);
ProductNameTB.Text = productname;
String productprice = Convert.ToString(read["ProductPrice"]);
ProdPriceTB.Text = productprice;
}
}
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
finally
{
cnn1.Close();
}
}
Work-around: as textbox_textchanged event was not working, I decided to add a button which finds product using the ID:
protected void FindProductBtn_Click(object sender, EventArgs e)
{
string connectionString1;
SqlConnection cnn1;
connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
cnn1 = new SqlConnection(connectionString1);
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = (" + Convert.ToInt32(ProductIDTB.Text) + ") ";
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
try
{
cnn1.Open();
using (SqlDataReader read = com1.ExecuteReader())
{
while (read.Read())
{
String productcategory = Convert.ToString(read["ProductCategory"]);
ProductCategoryTB.Text = productcategory;
String productname = Convert.ToString(read["ProductName"]);
ProductNameTB.Text = productname;
String productprice = Convert.ToString(read["ProductPrice"]);
ProdPriceTB.Text = productprice;
}
}
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
finally
{
cnn1.Close();
ProductCategoryTB.ReadOnly = true;
ProductNameTB.ReadOnly = true;
ProdPriceTB.ReadOnly = true;
}
}
Set the textbox's AutoPostBack attribute to true
More info: https://meeraacademy.com/textbox-autopostback-and-textchanged-event-asp-net/
<asp:TextBox ID="ProductIDTB" runat="server" AutoPostBack="True"
OnTextChanged="ProductIDTB_TextChanged"></asp:TextBox>
By the way, use SqlParameter to use parameterized query. Aside from sql-injection attack prevention, parameterized query can help the RDBMS store and re-use the execution plan of similar queries, to ensure better performance. See: https://dba.stackexchange.com/questions/123978/can-sp-executesql-be-configured-used-by-default
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = #productIdFilter";
int productIdFilter = Convert.ToInt32(ProductIDTB.Text);
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
com1.Parameters.AddWithValue("productIdFilter", productIdFilter);
OnTextChanged Event in Code Behind
protected void txtProductId_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["_connect"].ToString());
int ProductId = Convert.ToInt32(txtProductId.Text);
SqlCommand com = con.CreateCommand();
com.CommandText = "sp_ProductGetData";
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Mode", 1);
com.Parameters.AddWithValue("#ProductId", ProductId);
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
txtProductCategory.Text = Convert.ToString(dr["ProductCategory"]);
txtProductName.Text = Convert.ToString(dr["ProductName"]);
txtPrice.Text = Convert.ToString(dr["Price"]);
}
else
{
ScriptManager.RegisterClientScriptBlock((Page)(HttpContext.Current.Handler), typeof(Page), "alert", "javascript:alert('" + Convert.ToString(("No Record Found with Prodcut Id: "+ProductId)) + "');", true);
return;
}
con.Close();
}
Stored Procedure
CREATE PROCEDURE sp_ProductGetData
(
#Mode INT=NULL,
#ProductId INT=NULL
)
AS
BEGIN
IF(#Mode=1)
BEGIN
SELECT ProductCategory,ProductName,Price FROM Product
WHERE ProductId=#ProductId
END
END

Prevent duplicates in datagrid when databound

after some testing I came with this way to handle my datagrid. dgVariedad_CellEditEnding use the function nombreVariedadDisponible(txtBoxTemporal.Text) to check if the new value already exist in List<Variedad> variedades and it works. The problem is that the value wont be inserted in the database but will be added in the datagrid control, I can't find a way to cancel the new row in the control.
private List<Variedad> variedades = new List<Variedad>();
private void bindVariedad()
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
cmd.CommandText = "SELECT NOMBRE FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
Conexion.abrirConexion();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable table = new DataTable("DATAFRUT_VARIEDADES");
da.Fill(table);
table.Columns[0].ColumnName = "Nombre";
dgVariedad.ItemsSource = table.DefaultView;
cmd.CommandText = "SELECT * FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
using (MySqlDataReader dr = cmd.ExecuteReader())
{
variedades.Clear();
while (dr.Read())
{
Variedad var = new Variedad();
var.codigo = Convert.ToInt32(dr[0]);
var.nombre = dr[1].ToString();
var.eliminado = Convert.ToChar(dr[2]);
variedades.Add(var);
}
}
}
}
private void dgVariedad_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
TextBox txtBoxTemporal = e.EditingElement as TextBox;
int indice = e.Row.GetIndex();
if (e.Row.IsNewItem)
{
if (nombreVariedadDisponible(txtBoxTemporal.Text))
{
bool insertExitoso = false;
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
cmd.CommandText = "INSERT INTO DATAFRUT_VARIEDADES VALUES (default, '" + txtBoxTemporal.Text + "', 'F');";
try
{
cmd.ExecuteNonQuery();
insertExitoso = true;
}
catch
{
MessageBox.Show("Error");
}
Conexion.cerrarConexion();
}
if (insertExitoso)
{
variedades.Add(Variedad.cargarUltimoInsert(txtBoxTemporal.Text));
}
}
else
{
e.Cancel = true;
}
}
else
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
DataRowView dataRow = (DataRowView)dgVariedad.SelectedItem;
cmd.CommandText = "UPDATE DATAFRUT_VARIEDADES SET NOMBRE = '" + txtBoxTemporal.Text + "' WHERE CODIGO = " + variedades[dgVariedad.SelectedIndex].codigo + ";";
try
{
cmd.ExecuteNonQuery();
variedades[dgVariedad.SelectedIndex].nombre = txtBoxTemporal.Text;
}
catch(MySqlException mex)
{
MessageBox.Show("Error " + mex.Message);
}
Conexion.cerrarConexion();
}
}
}
My table on mysql has 3 fields:
int codigo (primary key, auto increment)
string Nombre (Unique) char
char Eliminado -> Eliminado (Deleted) with values (F = false and V =
true)
Here is how I check if the value already exist.
private bool nombreVariedadDisponible(string nombreAComparar)
{
//busca el nombre en la lista "variedades"
foreach (Variedad var in variedades)
{
if (var.nombre.ToLower() == nombreAComparar.ToLower() && var.eliminado == 'F')
return false;
}
return true;
}

Not able to update data in update page

I am working on updating gridview value by sending gridview values to other page. Here, I am able to update category dropdown list value and image file only. I am not able to update textbox values.
Here is my code..
Update Product Code:
protected void SubmitButton_Click(object sender, EventArgs e)
{
int productId = Convert.ToInt32(Request.QueryString["ProductID"]);
Product product = new Product();
product.ProductID = productId;
product.ProductName = TitleTextBox.Text;
product.Description = DescriptionTextBox.Text;
product.ItemsInSet = Convert.ToInt32(SetTextBox.Text);
product.UnitPriceOwner = Convert.ToInt32(UnitResellerTextBox.Text);
product.UnitPriceReseller = Convert.ToInt32(UnitResellerTextBox.Text);
product.ShippingCost = Convert.ToInt32(ShipmentTextBox.Text);
product.CategoryID = Convert.ToInt32(CategoryDropDownList.SelectedValue.ToString());
product.Visible = true;
product.InOffer = false;
if (ImageUpload.HasFile)
{
int length = ImageUpload.PostedFile.ContentLength;
product.ProductImage = new byte[length];
ImageUpload.PostedFile.InputStream.Read(product.ProductImage, 0, length);
}
else
{
Byte[] image;
image = ProductBL.GetImage(productId);
product.ProductImage = image;
}
ProductBL.UpdateProduct(product);
MessageLabel.Text = "Product successfully Updated!";
}
UpdateProduct() code:
public static void UpdateProduct(Product product)
{
string query = "UPDATE [Products] SET [ProductName] = #ProductName, [Description] = #Description, [ItemsInSet] = #ItemsInSet, " +
"[UnitPriceOwner] = #UnitPriceOwner, [UnitPriceReseller] = #UnitPriceReseller, [CategoryID] = #CategoryID, " +
"[ShippingCost] = #ShippingCost, [InOffer] = #InOffer, [ProductImage] = #ProductImage, [Visible] = #Visible WHERE [ProductID] = #ProductID";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#ProductName", SqlDbType.Text).Value = product.ProductName;
cmd.Parameters.AddWithValue("#Description", SqlDbType.Text).Value = product.Description;
cmd.Parameters.AddWithValue("#ItemsInSet", SqlDbType.Int).Value = product.ItemsInSet;
cmd.Parameters.AddWithValue("#UnitPriceOwner", SqlDbType.Int).Value = product.UnitPriceOwner;
cmd.Parameters.AddWithValue("#UnitPriceReseller", SqlDbType.Int).Value = product.UnitPriceReseller;
cmd.Parameters.AddWithValue("#CategoryID", SqlDbType.Int).Value = product.CategoryID;
cmd.Parameters.AddWithValue("#ShippingCost", SqlDbType.Int).Value = product.ShippingCost;
cmd.Parameters.AddWithValue("#InOffer", SqlDbType.Bit).Value = product.InOffer;
cmd.Parameters.AddWithValue("#Visible", SqlDbType.Bit).Value = product.Visible;
cmd.Parameters.AddWithValue("#ProductID", SqlDbType.Text).Value = product.ProductID;
cmd.Parameters.Add("#ProductImage", SqlDbType.Image).Value = product.ProductImage == null ? (object)DBNull.Value : product.ProductImage;
DbUtility.UpdateDb(cmd);
}
Page Load Code:
protected void Page_Load(object sender, EventArgs e)
{
int productId = 0;
productId = Convert.ToInt32(Request.QueryString["ProductID"]);
LoadProductDetails(productId);
}
protected void LoadProductDetails(int productId)
{
var product = ProductBL.GetProductById(productId);
TitleTextBox.Text = product.ProductName;
DescriptionTextBox.Text = product.Description;
SetTextBox.Text = Convert.ToInt32(product.ItemsInSet).ToString();
UnitOwnerTextBox.Text = Convert.ToInt32(product.UnitPriceOwner).ToString();
UnitResellerTextBox.Text = Convert.ToInt32(product.UnitPriceReseller).ToString();
ShipmentTextBox.Text = Convert.ToInt32(product.ShippingCost).ToString();
}
Kindly Help me
Try to load your LoadProductDetails in
if(!IsPostback)
{
//here
}
first thing always check for null condition before using Session or Query String variable to avoid any chances of getting error.
I think here you are missing to check !IsPostback condition that's why when you click on Update button then your updated values will be lost as your method LoadProductDetails(productId); called.

Table not updated in database after changing values from Textbox linked to Selected Item from ListView

This is how it works. I select a row from my listview then I will click "Edit" button which the values from the selected item will also be shown in the registration form. The "Register" button will now then changed to "Update". I am trying to update my customers table after changing inputs from the textboxes on my registration form but there are no changes in my database.
I receive no errors but I might have missed something here.
This is my code here:
private void btnRfrsh_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "SELECT Cust_Lname, Cust_Fname, Cust_MI, Birthdate, Age, Sex, Passport_ID, Address, Contact_Num, Nationality from customers where removed = 0";
MySqlCommand select = new MySqlCommand(query, connect);
MySqlDataReader refresh = select.ExecuteReader();
while (refresh.Read())
{
ListViewItem item;
item = new ListViewItem(refresh.GetString(0));
item.SubItems.Add(refresh.GetString(1));
item.SubItems.Add(refresh.GetString(2));
item.SubItems.Add(refresh.GetString(3));
item.SubItems.Add(refresh.GetString(4));
item.SubItems.Add(refresh.GetString(5));
item.SubItems.Add(refresh.GetString(6));
item.SubItems.Add(refresh.GetString(7));
item.SubItems.Add(refresh.GetString(8));
item.SubItems.Add(refresh.GetString(9));
lviewCust.Items.Add(item);
}
if (refresh.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (lviewCust.SelectedItems.Count > 0)
{
ListViewItem item = lviewCust.SelectedItems[0];
cust_fname.Text = item.SubItems[0].Text;
cust_lname.Text = item.SubItems[1].Text;
cust_mi.Text = item.SubItems[2].Text;
//DateTime bdate = Convert.ToDateTime(item.SubItems[3].Text);
String bdate_string = item.SubItems[3].Text;
DateTime bdate = DateTime.ParseExact(bdate_string, "dd-MM-yyyy", null);
cust_bdate.Value = bdate;
cust_age.Text = item.SubItems[4].Text;
cust_sex.Text = item.SubItems[5].Text;
cust_passid.Text = item.SubItems[6].Text;
cust_nation.Text = item.SubItems[9].Text;
cust_add.Text = item.SubItems[7].Text;
cust_contact.Text = item.SubItems[8].Text;
}
cust_fname.ReadOnly = true;
cust_lname.ReadOnly = true;
cust_mi.ReadOnly = true;
cust_passid.ReadOnly = true;
btnReg.Text = "Update";
btnReg.Name = "btnUpdate";
btnReg.Click -= this.btnReg_Click;
btnReg.Click += this.btnUpdate_Click;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "UPDATE customers SET Age = '" + this.cust_age.Text + "', Nationality = '" + this.cust_nation.Text + "', Address = '" + this.cust_add.Text + "', Contact_Num = '" + this.cust_contact.Text + "' WHERE Cust_Fname = '" + this.cust_fname.Text + "' and Cust_Lname = '" + this.cust_lname.Text + "'";
MySqlCommand update = new MySqlCommand(query, connect);
MySqlDataReader updte = update.ExecuteReader();
MessageBox.Show("Customer Info Updated Successfully");
if (updte.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
cust_fname.Clear();
cust_lname.Clear();
cust_mi.Clear();
cust_bdate.Value = DateTime.Now;
cust_age.Clear();
cust_passid.Clear();
cust_add.Clear();
cust_contact.Clear();
cust_nation.Clear();
cust_fname.ReadOnly = false;
cust_lname.ReadOnly = false;
cust_mi.ReadOnly = false;
cust_passid.ReadOnly = false;
btnReg.Text = "Register";
btnReg.Name = "btnReg";
btnReg.Click -= this.btnUpdate_Click;
btnReg.Click += this.btnReg_Click;
}
}
}
First, I think you should use ExecuteNonQuery() instead of ExecuteReader().
You call ExecuteReader() when you execute a sql command that returns something (such as SELECT).
When you call a command that doesn't return anything (such as INSERT, UPDATE, DELETE, etc.), you should call ExecuteNonQuery().
See the details here.
Second, I think you should check the result before alert "successfully". ExecuteNonQuery() returns the number of rows affected, you can check this to determine success or not.

Slow data Selection from MDB file to C# Desktop application

Although everything is correct, but data selection process is very slow in my Application, while retriving data from access .mdb file. Is there any idea that data can be accessed fast. Is there any mechanism??
This below code Runs when Button Clicked .
public class GetData {
OleDbConnection con = new OleDbConnection(DatabseConnection.ConnectionStringAccessDatabase);
public string lblPolicyNumber, lblInsuredName, lblIssuedDatePolicy, lblStatusPolicy,
lblModalPremium, lblDueDate, lblNextDueDate, lblAgentCode,
lblMode, lblType1, lblAmount1, lblDate1, lblPremAmt1,
lblDueDate1, lbPaidDate1, lblPremAmt2, lblDueDate2,
lblPaidDate2, lblPremAmt3, lbDueDate3, lblPadiDate3,
lblOwnersName, lblOwnersCode, lblAddress1, lblAddress2,
lblPlan, lblCoverageAmt, lblSex, lblBirthDate, lblAge,
lblAutomaticPrmloan, lblAPLCount, lblLoanType, lblLoanPrincipleamt,
lblLoanDate, lblRatedNotRated, lblUnderWritingApproved , LateFee,
TotalAmountDue, AmountInDeposit, NetPayableAmount, Overdueprem,
CurrentPremiumDue, lblPMFlastUpdated = null;
public void getData(string policyNumber)
{
try
{
con.Open();
}
catch { MessageBox.Show("Please Download the File From the Server, Or Contact IT Department"); }
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "(Select capolnum, cainame, iss_dte, castatus, mod_prm, due_dte1, nxt_due, agent_code, cabmode, casustyp1, casusamt1, casusdate1, chbldpm1, pd_dte1, chbldpm2, due_dte2, pd_dte2, chbldpm3, due_dte3, pd_dte3 , caoname, ocode, Addr1, addr2, plan, cbcovamt, cbsex, birth_dte, cbissage, apl, as400_cl_aplcnt, as400_cl_lntype, as400_cl_lnprinc, apl_date, cstype, approved FROM agy_pmf where capolnum ='" + policyNumber + "' )";
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
SetData.lblPolicyNumber = lblPolicyNumber = dr.GetValue(0).ToString();
SetData.lblInsuredName = lblInsuredName = dr.GetValue(1).ToString();
lblIssuedDatePolicy = dr.GetValue(2).ToString();
lblStatusPolicy = dr.GetValue(3).ToString();
lblModalPremium = dr.GetValue(4).ToString();
lblDueDate = dr.GetValue(6).ToString();
lblNextDueDate = dr.GetValue(6).ToString();
lblAgentCode = dr.GetValue(7).ToString();
SetData.lblMode = lblMode = dr.GetValue(8).ToString();
lblType1 = dr.GetValue(9).ToString();
lblAmount1 = dr.GetValue(10).ToString();
lblDate1 = dr.GetValue(11).ToString();
lblPremAmt1 = dr.GetValue(12).ToString();
lblDueDate1 = dr.GetValue(5).ToString();
lbPaidDate1 = dr.GetValue(13).ToString();
lblPremAmt2 = dr.GetValue(14).ToString();
lblDueDate2 = dr.GetValue(15).ToString();
lblPaidDate2 = dr.GetValue(16).ToString();
lblPremAmt3 = dr.GetValue(17).ToString();
lbDueDate3 = dr.GetValue(18).ToString();
lblPadiDate3 = dr.GetValue(19).ToString();
lblOwnersName = dr.GetValue(20).ToString();
lblOwnersCode = dr.GetValue(21).ToString();
lblAddress1 = dr.GetValue(22).ToString();
lblAddress2 = dr.GetValue(23).ToString();
lblPlan = dr.GetValue(24).ToString();
lblCoverageAmt = dr.GetValue(25).ToString();
lblSex = dr.GetValue(26).ToString();
lblBirthDate = dr.GetValue(27).ToString();
lblAge = dr.GetValue(28).ToString();
lblAutomaticPrmloan = dr.GetValue(29).ToString();
lblAPLCount = dr.GetValue(30).ToString();
lblLoanType = dr.GetValue(31).ToString();
lblLoanPrincipleamt = dr.GetValue(32).ToString();
lblLoanDate = dr.GetValue(33).ToString();
lblRatedNotRated = dr.GetValue(34).ToString();
lblUnderWritingApproved = dr.GetValue(35).ToString();
con.Close();
}
}}

Categories

Resources