I wanted to update a record to the database but it just keep reverting to its original value.
Below is my code. No error was display to me either.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CandidateConnectionString"].ConnectionString);
conn.Open();
string updateData = "UPDATE Resume SET [Work_Experience] = #work_exp, [Educational_Level] = #edu_level, [Field_Of_Study] = #field_study, [University_Name] = #uni_name, [University_Location] = #uni_locate, [Graduation_Year] = #gra_year WHERE Cand_ID = (SELECT Cand_ID FROM Candidate WHERE Cand_Username = '"+ usernamelbl.Text +"')";
SqlCommand cmd = new SqlCommand(updateData, conn);
cmd.Parameters.AddWithValue("#work_exp", Work_Exp.Text);
cmd.Parameters.AddWithValue("#edu_level", Edu_Level.SelectedItem.Text);
cmd.Parameters.AddWithValue("#field_study", Field_Study.SelectedItem.Text);
cmd.Parameters.AddWithValue("#uni_name", Uni_Name.Text);
cmd.Parameters.AddWithValue("#uni_locate", Uni_Locate.Text);
cmd.Parameters.AddWithValue("#gra_year", Year.Text);
cmd.ExecuteNonQuery();
conn.Close();
Any Problem with the code?
I just found out a stupid mistake..
On the page_Load event, I have a line of code which is fetching value from the database
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CandidateConnectionString"].ConnectionString);
conn.Open();
string getdata = "SELECT * FROM Resume WHERE Cand_ID = (SELECT Cand_ID FROM Candidate WHERE Cand_Username = '" + usernamelbl.Text + "')";
SqlCommand com = new SqlCommand(getdata, conn);
SqlDataAdapter sda = new SqlDataAdapter(com);
DataSet ds = new DataSet();
sda.Fill(ds, "Resume");
Work_Exp.Text = ds.Tables["Resume"].Rows[0]["Work_Experience"].ToString();
Edu_Level.Text = ds.Tables["Resume"].Rows[0]["Educational_Level"].ToString();
Field_Study.Text = ds.Tables["Resume"].Rows[0]["Field_Of_Study"].ToString();
Uni_Name.Text = ds.Tables["Resume"].Rows[0]["University_Name"].ToString();
Uni_Locate.Text = ds.Tables["Resume"].Rows[0]["University_Location"].ToString();
Year.Text = ds.Tables["Resume"].Rows[0]["Graduation_Year"].ToString();
conn.Close();
But I didn't include it under if(!IsPostBack) and that's the reason whenever I submit, it overwrites my current value and revert it back to the original state. Thanks to you guys who trying to help me sort out and teaches me about new stuff. :)
Related
I am trying to make a feedback form where I want to show the name which is inserted n number of times.
My DataBase has for example 9 duplicate names as feedback was input for that same person 9 times and I want to display it on the result that common name.
Please help me out to complete the code/solution or Correct the code and get the result.
SQL QUERY IS RUNNING PROPERLY IT IS SELECTING THE SINGLE DATA FROM DATABASE BUT HOW TO SHOW THIS ON WEBPAGE
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT DISTINCT (F2NAME) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "'";
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
try using below code, i have made some change in sql query to get only single record as result.
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT max(DISTINCT (F2NAME)) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "' AND F2NAME<>'' AND F2NAME IS NOT NULL" ;
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
i have not check but it will work, if you result binding to lable is correct.
I am trying to update my data in a SQL Server database through C#. I am getting updated. But the problem is the data is updated twice.
For example I have 10 (int) in my balance and if I add another 10, it turns to 30.
Any help would be appreciated.
Here is my code:
protected void LoginClick(object sender, EventArgs e)
{
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
}
I would like to rectify few mistakes in your code,
DataTable is not needed to execute the update query, ExecuteNonQuery will do the job
The adapter.Fill and ExecuteNonQuery do the same job here and that's why your updates happening twice
Make use of parameterization while dealing with user inputs to avoid exceptions
For parsing integers use int.TryParse instead for Convert.ToInt32
I think the following code would help you to do the same function in a smarter way:
int currentBalance = 0;
if(int.TryParse(txtAdd.Text, out currentBalance))
{
string querSql = "Update [Order] set Balance = Balance + #balance," +
" Card = #card where email = #email"
using (SqlConnection dbConn = new SqlConnection("connectionString here"))
{
dbConn.Open();
using (SqlCommand sqlCommand = new SqlCommand(querySql, dbConn))
{
sqlCommand.Parameters.Add("#balance", SqlDbType.int).value = currentBalance;
sqlCommand.Parameters.Add("#card", SqlDbType.VarChar).value = card.Text;
sqlCommand.Parameters.Add("#email", SqlDbType.VarChar).value = email;
sqlCommand.ExecuteNonQuery();
}
}
}
Please note: YOu are parsing the balance as an integer value, so I assume the column Balance is an integer field in the database, if not make use of corresponding datatype for the parameter #balance also update the parsing technique
As per the documentation:
SqlDataAdapter(SqlCommand)
Initializes a new instance of the SqlDataAdapter class with the specified SqlCommand as the SelectCommand property.
What is going wrong in your code?
Actually you are passing SqlDataAdapter your update query as the Select command. So now when you will use this instance of SqlDataAdapter to Fill your datatable then actually you are executing your Update command. Look at the following code along with comments to see what is going wrong:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
SqlDataAdapter sda = new SqlDataAdapter(cmd);//The Select command for SqlDataAdapter
//is actually now the update command specified by cmd instnace of SqlCommand
DataTable dt = new DataTable();
sda.Fill(dt);//here SqlDataAdapter will execute it's Select command which is actually set
//to an update statement so your record will be updated
int i = cmd.ExecuteNonQuery();//and here again the update command is being executed now
//directly using the SqlCommand cmd instance and thus your record gets updated twice
con.Close();
Fixed Code:
DataTable dr = new DataTable();
string email = txtEmail.Text;
SqlConnection con = new SqlConnection(Ws.Con);
con.Open();
int s = Convert.ToInt32(add.Text);
SqlCommand cmd = new SqlCommand("Update [Order] set Balance=Balance+'" + s + "',Card='" + card.Text + "' where email=#email ", con);
cmd.Parameters.AddWithValue("email", email);
//Create a new SqlComamnd
SqlCommand selectCommand = new SqlCommand("Select * from [Order]");
//Put the newly created instance as SelectCommand for your SqlDataAdapter
SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
Hope this help and do have a look at the documentation for better understanding of the SqlDataAdapter and DataTable. Thanks.
I have this situation: in DataEntryForm I have a dropdownlist, where user selects a letter number, and according to that inserts other related data.
I plan to change letter's status in other table by choosing in dropdownlist automatically.
I am using this code:
SqlParameter answertoparam = new SqlParameter("answerto", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID ='2' where income_number=('" + ansTo + "' )";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
comm.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
Unfortunately, the result is nothing.
Server is not giving error, and it simply refreshes the page that is it.
In your posted code, you are passing the SqlParameter as well as passing the value as raw data. Do either of one and preferably pass it as SqlParameter like
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
Moreover, you have two SqlCommand object in place and calling two ExecuteNonQuery() on them. correct that ... see below
SqlCommand findincomelett = new SqlCommand(commandText, conn); --1
comm.Parameters.Add(answertoparam); --2
conn.Open();
findincomelett.ExecuteNonQuery(); --1
comm.ExecuteNonQuery(); --2
As far as I understand, the issue is that the correct IncomeLetters.docState_ID is not updated to '2'.
You may want to debug and see what value you are getting in :
string ansTo = ddlAnswerTo.SelectedItem.Value;
The record in the database that you are expecting to be updated may not have the record that satisfies the where clause 'income_number = #answertoparam'
I would like to bring you here full code of the page.
Idea is: I have page for enrollment. I am passing data to DB through stored procedure (DataInserter).
Problem is here: during enrollment, user selects from dropdownlist number of the letter he would like to answer to, and in the end, the status of the letter on other table of DB (IncomeLetters.tbl), would change from "pending"('1') to "issued" ('2').
I guess, I could clear my point to you and thank you for your support!
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MaktubhoConnectionString2"].ConnectionString);
using (SqlCommand comm = new SqlCommand("DataInserter", conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
SqlParameter employeeparam = new SqlParameter("EmployeeSentIndex", int.Parse(ddlemployee.SelectedItem.Value));
SqlParameter doctypeparam = new SqlParameter("doctype_ID", int.Parse(ddldoctype.SelectedItem.Value));
SqlParameter doccharparam = new SqlParameter("docchar_ID", int.Parse(ddldocchar.SelectedItem.Value));
SqlParameter authorityparam = new SqlParameter("authority", txtauthority.Text);
SqlParameter subjectparam = new SqlParameter("subject", txtsubject.Text);
DateTime dt = DateTime.Now;
string todasdate = dt.ToString("d", CultureInfo.CreateSpecificCulture("de-DE"));
SqlParameter entrydateparam = new SqlParameter("entrydate", todasdate);
string Pathname = "UploadImages/" + Path.GetFileName(FileUpload1.PostedFile.FileName);
SqlParameter imagepathparam = new SqlParameter("image_path", Pathname);
SqlParameter loginparam = new SqlParameter("login", "jsomon");
comm.Parameters.Add(employeeparam);
comm.Parameters.Add(doctypeparam);
comm.Parameters.Add(doccharparam);
comm.Parameters.Add(authorityparam);
comm.Parameters.Add(subjectparam);
comm.Parameters.Add(entrydateparam);
comm.Parameters.Add(imagepathparam);
comm.Parameters.Add(loginparam);
comm.Parameters.Add("#forlabel", SqlDbType.VarChar, 100);
comm.Parameters["#forlabel"].Direction = ParameterDirection.Output;
FileUpload1.SaveAs(Server.MapPath("~/UploadImages/" + FileUpload1.FileName));
string ansTo = ddlAnswerTo.SelectedItem.Value;
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
lblresult.Visible = true;
Image1.Visible = true;
lblresult.Text = "Document number:";
lblnumber.Visible = true;
lblnumber.Text = (string)comm.Parameters["#forlabel"].Value; ;
conn.Close();
}
txtauthority.Text = "";
txtsubject.Text = "";
}
When I try to get the value of 1 column out of my Database(using ExecuteScalar(), to string or integer nothing works) It crashes at the execution.
Is it because I am using ExecuteScalar() in my open SqlDataReader?
Here is my code, it crashes at iAantal:
SqlCommand get_order = new SqlCommand("SELECT * FROM Factuur WHERE ID = #ID1 OR order_id = #ID2", con);
get_order.Parameters.AddWithValue("#ID1", Session["LastOrderID"].ToString());
get_order.Parameters.AddWithValue("#ID2", Session["LastOrderID"].ToString());
SqlDataReader rdrOrder = get_order.ExecuteReader();
iAantal = 2;
while(rdrOrder.Read())
{
from_db_producten += "<tr>";
sHuidigeDatum = rdrOrder["besteldatum"].ToString();
sLeverdatum = rdrOrder["leverdatum"].ToString();
sToestelID = rdrOrder["item_id"].ToString();
iPrijsPerStuk = Convert.ToInt32(rdrOrder["prijs"]);
SqlCommand check_aantal_toestel = new SqlCommand("SELECT COUNT(item_id) FROM Factuur WHERE ID = #orderID1 OR order_id = #orderID2 AND item_id = #itemID", con);
check_aantal_toestel.Parameters.AddWithValue("#orderID1", Session["LastOrderID"].ToString());
check_aantal_toestel.Parameters.AddWithValue("#orderID2", Session["LastOrderID"].ToString());
check_aantal_toestel.Parameters.AddWithValue("#itemID", sToestelID);
iAantal = Convert.ToInt32(check_aantal_toestel.ExecuteScalar());
SqlCommand get_toestel_merk = new SqlCommand("SELECT item_value FROM ItemSpecificatie WHERE item_key = #merk AND item_id = #ID", con);
get_toestel_merk.Parameters.AddWithValue("#merk", "Merk");
get_toestel_merk.Parameters.AddWithValue("#ID", sToestelID);
SqlCommand get_toestel_naam = new SqlCommand("SELECT item_value FROM ItemSpecificatie WHERE item_key = #naam AND item_id = #ID", con);
get_toestel_merk.Parameters.AddWithValue("#naam", "Naam");
get_toestel_merk.Parameters.AddWithValue("#ID", sToestelID);
sToestelmerk = Convert.ToString(get_toestel_merk.ExecuteScalar());
sToestelnaam = Convert.ToString(get_toestel_naam.ExecuteScalar());
iPrijsTotaal = iAantal * iPrijsPerStuk;
}
As mentioned in your question itself, you cannot perform ExecuteScalar() when you have ExecuteReader() open.
However, you can add MultipleActiveResultSets = true in the connection string provider part to achieve multiple connections to the data source.
However, this is do-able this is not recommended way for database connectivity. Because, opening multiple connections with the data source will cause additional load on the database.
I am making a school application about articles publication. In a dropdownList I want to display the value that exists in database as default pre-selected value. DropdownList conatins "emertimi" from table "kategorite". When user selects a value it saves id of "kategoria_id" in table "artikulli". Here is my code behind
if (e.Item.ItemType == ListItemType.EditItem)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection);
string Qry = "select * from kategoria";
string id = Request.QueryString["id"];
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
DataSet ds2 = new DataSet();
DataSet ds3 = new DataSet();
con.Open();
da.Fill(ds);
string kategoria_id = "select kategoria_id from artikulli where id='" + id + "'";
SqlDataAdapter dk = new SqlDataAdapter(kategoria_id, con);
dk.Fill(ds2);
var kategoria_id_result = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
string emertimi = "select emertimi from kategoria where id='" + kategoria_id_result + "'";
SqlDataAdapter de = new SqlDataAdapter(emertimi, con);
de.Fill(ds3);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(emertimi).Value;
con.Close();
con.Dispose();
ds.Dispose();
ds2.Dispose();
ds3.Dispose();
da.Dispose();
dk.Dispose();
de.Dispose();
}
}
But it's showing this error: Object reference not set to an instance of an object. at this line: drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(emertimi).Value;
I guess emertimi contains a value that cannot be found in the dropdown list. Therefore, the FindByText will return null and getting the Value will result in this exception.
Test the result before you try to get the Value.
Also, instead of the separate Dispose calls, use using statements. And be aware of the SQL injection risk: use parameters instead.
That's because the item you're looking for has not been found. You should troubleshoot your code and figure out what emertimi is set to at run time.