I am stuck with an issue with updating. When I open my Windows form developed in C# using SQL, the update updates all fields but not the name. Could you tell me what I did wrong?
Here is my code
public void cc()
{
cbBname.Items.Clear();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from BkhurData";
db.ExeNonQuery(cmd);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
cbBname.Items.Add(dr["Name"].ToString());
}
}
private void BkhurUpdate_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update BkhurData set Name='" + tbBpname.Text + "',Details='" + tbBpdetails.Text + "',Price='" + tbBpprice.Text + "',Size='" + tbBpsize.Text + "', Quantity ='"+tbBpquantity.Text+"' where Name = '" + tbBpname.Text + "'";
db.ExeNonQuery(cmd);
tbBpname.Text = "";
tbBpdetails.Text = "";
tbBpprice.Text = "";
tbBpsize.Text = "";
tbBpquantity.Text = "";
cc();
MessageBox.Show("updated successfully");
}
You are updating the Name where the Name equals tbBpname.Text so it will not change the name for row you are updating.
private string originalName;
public void cc()
{
cbBname.Items.Clear();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from BkhurData";
db.ExeNonQuery(cmd);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
cbBname.Items.Add(dr["Name"].ToString());
originalName = dr["Name"].ToString()
}
}
private void BkhurUpdate_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update BkhurData set Name='" + tbBpname.Text + "',Details='" + tbBpdetails.Text + "',Price='" + tbBpprice.Text + "',Size='" + tbBpsize.Text + "', Quantity ='"+tbBpquantity.Text+"' where Name = '" + originalName+ "'";
db.ExeNonQuery(cmd);
tbBpname.Text = "";
tbBpdetails.Text = "";
tbBpprice.Text = "";
tbBpsize.Text = "";
tbBpquantity.Text = "";
cc();
MessageBox.Show("updated successfully");
}
Please note you should use SqlParameters and not build the query as a string.
Related
I have a problem , i'm trying to do operations between values recorded(type float) in table of data , the problem is when i try to update value(result of the operation in textbox) in datable using combobox after maintaining opération , it shows me error (System.Data.SqlClient.SqlException: 'Error converting data type varchar to float.'), So how can i resolve that !help please
This is a part a of my code in which the error exists
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
String query = "UPDATE Table_com SET Contents='" + textBox6.Text + "' WHERE Variable='" + comboBox5.Text + "'";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Table_com where Variable='" + comboBox5.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
MessageBox.Show("Variable mise à jour avec succés");
}
You cannot use float integer etc. values like text field as:
String query = "UPDATE Table_com SET Contents='" + textBox6.Text + "' WHERE Variable='" + comboBox5.Text + "'";
and your code really risky, you may use parameters like this, dont use string and convert your value to float :
static void Main(string[] args)
{
var ConnectionString = "YOUR CONNECTION STRING";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
String query = "UPDATE Table_com SET Contents=#contents WHERE Variable=#variable";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#contents", SqlDbType.Float).Value = Convert.ToDouble(textBox6.Text);
cmd.Parameters.Add("#variable", SqlDbType.NVarChar).Value = comboBox5.Text;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
}
this is what i tried refering to wikiCan answer
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-VEFPLGG\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String query = "UPDATE Table_com SET Contents=#contents ";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#contents", SqlDbType.Float).Value = textBox6.Text;
//cmd.Parameters.Add("#variable", SqlDbType.Float).Value = Convert.ToDouble(comboBox5.Text);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
I have two combo boxes "Year" & "Amount" on the top of them I do get values for user info, because there are text boxes when called with user ID text boxes fill up with correct data.
The two combo boxes are also filled with correct data but I have to manually select year and the amount corresponding to it.
I need help in when I call the data "Year" & "Amount" should appear visible in the combo box. When I select a Year then the Amount should change accordingly. Last but not the least my reset is not clearing the combo boxes.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace dss
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Data Source=USER-PC\\sqlexpress;Initial Catalog=JG_Test;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
cmbYear.Items.Clear();
string sql = "";
con.Open();
SqlCommand cmd = new SqlCommand();
try
{
sql += "SELECT m.MemberId, m.Name, m.Address, m.Cellular, m.Email, p.PaymentId, p.Year, p.Amount from Members as m";
sql += " INNER JOIN Payments as p ON m.MemberId = p.MemberId";
sql += " WHERE m.MemberId = '" + tbID.Text + "' ORDER BY p.Year ASC";
cmd.Connection = con;
cmd.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if(dt.Rows.Count >0)
{
for(int i = 0; i<=dt.Rows.Count -1;i++)
{
tbID.Text = dt.Rows[i]["MemberId"].ToString();
tbName.Text = dt.Rows[i]["Name"].ToString();
tbCellular.Text = dt.Rows[i]["Cellular"].ToString();
tbEmail.Text = dt.Rows[i]["Email"].ToString();
tbAddress.Text = dt.Rows[i]["Address"].ToString();
cmbAmount.Items.Add(dt.Rows[i]["Amount"].ToString());
cmbYear.Items.Add(dt.Rows[i]["Year"].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
//This part displaying og the existing data from all the fileds corrssponding within the database//
private void btnAdd_Click(object sender, EventArgs e)
{
{
con.Open();
string Sql = "INSERT INTO Members ( MemberId, Name, Cellular, Email, Address ) VALUES " + " (#Id, #name, #cell, #email, #address)";
using (SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#name", tbName.Text);
cmd.Parameters.AddWithValue("#cell", tbCellular.Text);
cmd.Parameters.AddWithValue("#email", tbCellular.Text);
cmd.Parameters.AddWithValue("#address", tbAddress.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Payments ( MemberId, [Year], [Amount] ) VALUES " + " (#Id, Amount, Year)";
cmd.Parameters.Clear();
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#year", cmbYear.Text);
cmd.Parameters.AddWithValue("#amount", cmbAmount.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
tbID.Clear(); tbName.Clear(); tbCellular.Clear(); tbEmail.Clear(); tbAddress.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
con.Close();
}
}
}
//This part represents adding of new input data from all the fileds into the database//
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "UPDATE Members SET MemberId = '" + tbID.Text + "', Name = '" + tbName.Text + "', Cellular = '" + tbCellular.Text + "', Email = '" + tbEmail.Text + "', Address = '" + tbAddress.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "UPDATE Payments SET MemberId = '" + tbID.Text + "', Year = '" + cmbYear.Text + "', Amount = '" + cmbAmount.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Updated");
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents deleteing of input data from all the fileds into the database//
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "DELETE FROM Members WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "DELETE FROM Payments WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
MessageBox.Show("Data Deleted");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents clearing of input data from all the fileds//
private void btnReset_Click(object sender, EventArgs e)
{
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
//This part represents shuting down the application//
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
I would be inclined to simplify things a bit. Treat the personal data and the finance data as 2 parts.
Firstly, request the personal data - keep it simple
private void btnSearch_Click(object sender, EventArgs e)
{
string sql = "SELECT MemberId, Name, Address, Cellular, Email FROM Members WHERE MemberId = #Id";
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
tbID.Text = dt.Rows[0]["MemberId"].ToString();
tbName.Text = dt.Rows[0]["Name"].ToString();
tbCellular.Text = dt.Rows[0]["Cellular"].ToString();
tbEmail.Text = dt.Rows[0]["Email"].ToString();
tbAddress.Text = dt.Rows[0]["Address"].ToString();
}
Once thats done, move on to second part - the years/amounts combo (which is almost identical code)
string sql = "SELECT Year, Amount FROM Payments WHERE MemberId = #Id"
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
cmbYear.DataSource = dt;
cmbYear.DisplayMember = "Year";
cmbYear.ValueMember = "Amount";
And finally, tell the textbox what it needs to read by using
private void cmbYear_SelectionChangeCommitted(object sender, EventArgs e)
{
amountTxt.Text = cmbYear.SelectedValue.ToString();
}
in the combobox's SelectionChangeCommitted event
And that should have you sorted!
I'm trying to show when an inventory is lower than critical. It doesn't seem to get there when I debug the system
This is my code behind
protected void Page_Load(object sender, EventArgs e)
{
GetInventory();
TotalCount();
CriticalItem();
Panel1.Visible = false;
}
void TotalCount()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT 'Total Count of Inventory ' + '(' + convert(nvarchar,SUM(Quantity)) + ')' AS TotalCount from Inventory";
SqlDataReader data = cmd.ExecuteReader();
if (data.HasRows)
{
while (data.Read())
{
lblTotalCount.Text = data["TotalCount"].ToString();
}
con.Close();
}
else
{
con.Close();
Response.Redirect("Default.aspx");
}
}
void GetInventory()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Inventory.InventoryID, Products.ProductName, " +
"Supplier.SupplierName, Inventory.Quantity, Users.LastName + ', ' + Users.FirstName AS UserAccount, " +
"SupplierProducts.CriticalLevel, Inventory.Status, Inventory.DateAdded, Inventory.DateModified, SupplierProducts.Price FROM Inventory " +
"INNER JOIN SupplierProducts ON Inventory.ProductID = SupplierProducts.SupplierProductID " +
"INNER JOIN Products ON SupplierProducts.ProductID = Products.ProductID " +
"INNER JOIN Supplier ON Inventory.SupplierID = Supplier.SupplierID " +
"INNER JOIN Users ON Inventory.UserID = Users.UserID";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Inventory");
lvInventory.DataSource = ds;
lvInventory.DataBind();
con.Close();
}
void CriticalItem()
{
var intcheck = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM Inventory", con))
{
da.Fill(intcheck);
}
var critcheck = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM SupplierProducts", con))
{
da.Fill(critcheck);
}
int finalQuantity = Convert.ToInt32(intcheck.Rows[0]["Quantity"]);
int criticalLevel = Convert.ToInt32(critcheck.Rows[0]["CriticalLevel"]);
if (finalQuantity > criticalLevel)
{
Panel1.Visible = true;
criticalItem.Text = "Available";
}
}
I want to criticalItem.text to tell the Inventory that is less than its critical level.
Can anybody tell me why my database isn't updating? Here's my code:
protected void editSection_selected(object sender, EventArgs e) {
int index = grdPhone.SelectedIndex;
GridViewRow row = grdPhone.Rows[index+1];
string values = ((DropDownList)sender).SelectedValue;
int tempVal = Convert.ToInt32(values);
int caseage = Convert.ToInt32(keyId);
int value = tempVal;
/*OleDbConnection con = new OleDbConnection(strConnstring);
//string query = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
string query = "Delete HRS_LEVEL_AMOUNT from Categories where parent_id=65 and id=" + caseage;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Dispose();
cmd.Dispose();
con.Close();
accPhoneNumbers.UpdateCommand = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
*/
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = ? WHERE ID=?";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("HRS_LEVEL_AMOUNT", tempVal);
cmd.Parameters.AddWithValue("ID", caseage);
con.Open();
cmd.ExecuteNonQuery();
}
}
Label1.Text += " editSection Success! (B) " + tempVal;
}
The commented part is my first solution (including the accPhoneNumbers.UpdateCommand).
I really need your help guys.
I hope this can help you:
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = #value1 WHERE ID=#value2";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#value1", tempVal);
cmd.Parameters.AddWithValue("#value2", caseage);
con.Open();
cmd.ExecuteNonQuery();
con.close();
}
}
For more information you can visit this video
How to increase totaldownloads value in my database file code is given below
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataRow dr;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserId"] == null)
{
lblMessage.Visible = true;
GridView1.Visible = false;
//AppContent.Visible = false;
}
else
{
if (!Page.IsPostBack)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
ArrayList myArrayList = ConvertDataSetToArrayList();
Literal objliteral = new Literal();
StringBuilder objSBuilder = new StringBuilder();
//Add some column to datatable display some products
dt.Columns.Add("appImg");
dt.Columns.Add("appName");
dt.Columns.Add("appLink");
dt.Columns.Add("appType");
dt.Columns.Add("TotalVisitors");
dt.Columns.Add("TotalDownloads");
dt.Columns.Add("RemainingVisitors");
// Display each item of ArrayList
foreach (Object row in myArrayList)
{
//Add rows with datatable and bind in the grid view
dr = dt.NewRow();
dr["appImg"] = ((DataRow)row)["AppImg"].ToString();
dr["appName"] = ((DataRow)row)["AppName"].ToString();
dr["appLink"] = ((DataRow)row)["AppLink"].ToString();
dr["appType"] = ((DataRow)row)["AppType"].ToString();
dr["TotalVisitors"] = "Plan Visitors: " + ((DataRow)row)["TotalVisitors"].ToString();
dr["TotalDownloads"] = "Downloaded: " + ((DataRow)row)["TotalDownloads"].ToString();
dr["RemainingVisitors"] = "Remaining Visitors: " + ((DataRow)row)["RemainingVisitors"].ToString();
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
public ArrayList ConvertDataSetToArrayList()
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand cmd = new SqlCommand();
if (Session["UserId"] != null && (Session["UserTypeId"] != null && Convert.ToInt32(Session["UserTypeId"]) != 2))
{
cmd.CommandText = "Select * from tblApp WHERE AppType = '" + Session["UserOSType"] + "' ORDER BY TotalVisitors";
}
else
{
cmd.CommandText = "Select * from tblApp ORDER BY TotalVisitors";
}
cmd.Connection = sqlcon;
sqlcon.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet dsApp = new DataSet();
da.Fill(dsApp, "tblApp");
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in dsApp.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
sqlcon.Close();
return myArrayList;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "download")
{
Button ib = (Button)e.CommandSource;
int index = Convert.ToInt32(ib.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Label l2 = (Label)row.FindControl("Label2");
Label lbTotallVisitors = (Label)row.FindControl("Label4");
Label lblTotalDownloads = (Label)row.FindControl("Label5");
Label lblRemainingVisitors = (Label)row.FindControl("Label6");
string updateSQL = "UPDATE tblUser SET DownloadedApps = '" + lbl + "', Amount = '" + Session["Amount"] + "', TotalAmount='" + Session["TotalAmount"] + "' WHERE Id= '" + Session["UserId"] + "'";
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString()))
{
using (SqlCommand updateCommand = new SqlCommand(updateSQL, sqlConn))
{
sqlConn.Open();
updateCommand.ExecuteNonQuery();
updateCommand.Connection.Close();
}
}
Response.Redirect(l2.Text);
}
}
UPDATE Table SET Column = Column + 1