No mapping exists from object type - c#

private void button5_Click(object sender, EventArgs e)
{
DataGridViewRow updatedrow = dataGridView1.Rows[chooseAnyRow];
updatedrow.Cells[0].Value = SALUTATION.Text;
updatedrow.Cells[1].Value = NAME.Text;
updatedrow.Cells[2].Value = SEX.Text;
updatedrow.Cells[3].Value = ETHNICITY.Text;
updatedrow.Cells[4].Value = MARITALSTATUS.Text;
updatedrow.Cells[5].Value = ICNUMBER.Text;
updatedrow.Cells[6].Value = HPNUMBER.Text;
updatedrow.Cells[7].Value = DOB.Text;
updatedrow.Cells[8].Value = ADDRESS.Text;
updatedrow.Cells[9].Value = STATE.Text;
updatedrow.Cells[10].Value = CITY.Text;
updatedrow.Cells[11].Value = POSTCODE.Text;
updatedrow.Cells[12].Value = pictureBox1.Image;
con = new SqlConnection(#"Data Source=dasranrajlui\sqlexpress;Initial Catalog=SESoriginal;Integrated Security=True");
con.Open();
com = con.CreateCommand();
com.CommandType = CommandType.Text;
com.CommandText = " update VoterRegistration set SALUTATION = '" + SALUTATION.Text +
"', NAME = '" + NAME.Text +
"', SEX = '" + SEX.Text +
"', ETHNICITY = '" + ETHNICITY.Text +
"', MARITALSTATUS = '" + MARITALSTATUS.Text +
"', IC_NUMBER = " + ICNUMBER.Text +
", HP_NUMBER = " + HPNUMBER.Text +
", DOB = '" + DOB.Text +
"', ADDRESS = '" + ADDRESS.Text +
"', STATE = '" + STATE.Text +
"', CITY = '" + CITY.Text +
"', POSTCODE = '" + POSTCODE.Text +
"', VOTER_PIC = #VOTER_PIC where IC_NUMBER = " + ICNUMBER.Text;
com.CommandType = CommandType.Text;
com.Parameters.AddWithValue("#VOTER_PIC", pictureBox1.Image);
com.Parameters.AddWithValue("#Salutation", SALUTATION.Text);
com.Parameters.AddWithValue("#Name", NAME.Text);
com.Parameters.AddWithValue("#Sex", SEX.Text);
com.Parameters.AddWithValue("#Ethnicity", ETHNICITY.Text);
com.Parameters.AddWithValue("#MaritalStatus", MARITALSTATUS.Text);
com.Parameters.AddWithValue("#ICNumber", ICNUMBER.Text);
com.Parameters.AddWithValue("#HPNumber", HPNUMBER.Text);
com.Parameters.AddWithValue("#Dob", DOB.Text);
com.Parameters.AddWithValue("#Address", ADDRESS.Text);
com.Parameters.AddWithValue("#State", STATE.Text);
com.Parameters.AddWithValue("#City", CITY.Text);
com.Parameters.AddWithValue("#PostCode", POSTCODE.Text);
if (pictureBox1.Image != null)
{
ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
com.Parameters.AddWithValue("#VOTER_PIC", photo_aray);
}
try
{
com.ExecuteNonQuery();
MessageBox.Show("updated...");
SALUTATION.Text = null;
NAME.Text = null;
SEX.Text = null;
ETHNICITY.Text = null;
MARITALSTATUS.Text = null;
ICNUMBER.Text = null;
HPNUMBER.Text = null;
DOB.Text = null;
ADDRESS.Text = null;
STATE.Text = null;
CITY.Text = null;
POSTCODE.Text = null;
}
catch (Exception EX)
{
MessageBox.Show(EX + "NOT Updated");
}
finally
{
con.Close();
}
}
The error shows:
no mapping exists from object type
Is it because my convert image is wrong?
Or is there another way to update the image to my sql?
The thing is I need to update my values in the image which I can display and update which can save to my database.

Few more mistakes in your code; Corrected form is below
You are using the parameterized queries in wrong way. you need to use #parameterName instead for passing the corresponding value. your query will opens a wide door for sql Injection.
The , after POSTCODE =.. causing the current error, You need not to place , after the last column name`.
Finally you need to add com.Parameters.AddWithValue("#ICNumber",
ICNUMBER.Text); two times since the command expecting 12 parameters
Code will be like the following:
com.CommandText = " update VoterRegistration set SALUTATION =#Salutation" +
", NAME = #Name" +
", SEX = #Sex" +
", ETHNICITY = #Ethnicity" +
", MARITALSTATUS = #MaritalStatus" +
", IC_NUMBER = #ICNumber" +
", HP_NUMBER = #HPNumber" +
", DOB = #Dob" +
", ADDRESS = #Address" +
", STATE = #State" +
", CITY = #City" +
", POSTCODE = #PostCode where IC_NUMBER =#ICNumber";
com.CommandType = CommandType.Text;
com.Parameters.AddWithValue("#Salutation", SALUTATION.Text);
com.Parameters.AddWithValue("#Name", NAME.Text);
com.Parameters.AddWithValue("#Sex", SEX.Text);
com.Parameters.AddWithValue("#Ethnicity", ETHNICITY.Text);
com.Parameters.AddWithValue("#MaritalStatus", MARITALSTATUS.Text);
com.Parameters.AddWithValue("#ICNumber", ICNUMBER.Text);
com.Parameters.AddWithValue("#HPNumber", HPNUMBER.Text);
com.Parameters.AddWithValue("#Dob", DOB.Text);
com.Parameters.AddWithValue("#Address", ADDRESS.Text);
com.Parameters.AddWithValue("#State", STATE.Text);
com.Parameters.AddWithValue("#City", CITY.Text);
com.Parameters.AddWithValue("#PostCode", POSTCODE.Text);
com.Parameters.AddWithValue("#ICNumber", ICNUMBER.Text);

Use the parameters you created and remove extra commas
con = new SqlConnection(#"Data Source=dasranrajlui\sqlexpress;Initial Catalog=SESoriginal;Integrated Security=True");
con.Open();
com = con.CreateCommand();
com.CommandType = CommandType.Text;
com.CommandText = " update VoterRegistration set
SALUTATION #Salutation,
NAME = #Name,
SEX = #Sex,
ETHNICITY =#Ethnicity,
MARITALSTATUS = #MaritalStatus,
IC_NUMBER = #ICNumber,
HP_NUMBER = #HPNumber,
DOB = #Dob,
ADDRESS = #Address,
STATE = #State,
CITY = #City,
POSTCODE = #PostCode
where IC_NUMBER = #ICNumber";
com.CommandType = CommandType.Text;
com.Parameters.AddWithValue("#Salutation", SALUTATION.Text);
com.Parameters.AddWithValue("#Name", NAME.Text);
com.Parameters.AddWithValue("#Sex", SEX.Text);
com.Parameters.AddWithValue("#Ethnicity", ETHNICITY.Text);
com.Parameters.AddWithValue("#MaritalStatus", MARITALSTATUS.Text);
com.Parameters.AddWithValue("#ICNumber", ICNUMBER.Text);
com.Parameters.AddWithValue("#HPNumber", HPNUMBER.Text);
com.Parameters.AddWithValue("#Dob", DOB.Text);
com.Parameters.AddWithValue("#Address", ADDRESS.Text);
com.Parameters.AddWithValue("#State", STATE.Text);
com.Parameters.AddWithValue("#City", CITY.Text);
com.Parameters.AddWithValue("#PostCode", POSTCODE.Text);
com.Parameters.AddWithValue("#ICNumber", ICNUMBER.Text);

I suggest that you remove the , before where and add a quote around ICNUMBER.text
"', POSTCODE = '" + POSTCODE.Text + "' where IC_NUMBER = '" + ICNUMBER.Text +"'";

Related

syntax error missing operator in query expression c# using access as database

I'm getting syntax error in all my inputs into the textboxes.
In my database all the requirement is string other than the ID which is an autonumber, I try to search for possible answer but all didn't work or maybe I just missed some answer
Here is the error:
Syntax error (missing operator) in query expression ''hasdasd'password
= 'h'account_Type='Manager'Name='h'Middle_Name='h'Surname'h'address'h'BirthDate='3/17/1999'Mobile_Number'65465''.
Code:
private void update_Click(object sender, EventArgs e)
{
DateTime bdate = DateTime.Parse(birthdate.Value.ToShortDateString());
DateTime currentDate = DateTime.Parse(DateTime.Now.Date.ToShortDateString());
int age = currentDate.Year - bdate.Year;
String id = emp_view.SelectedRows[0].Cells[0].Value + String.Empty;
int id1 = Int32.Parse(id);
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\dbms\jollibee.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "update Employee_Details set username = '" + username.Text +
"'password = '" + password.Text +
"'account_Type='" + accountType.Text +
"'Name='" + name.Text +
"'Middle_Name='" + middlename.Text +
"'Surname'" + surname.Text +
"'address'" + address.Text +
"'BirthDate='" + birthdate.Value.ToShortDateString() +
"'Mobile_Number'" + mobilenumber.Text +
"'where ID = '" + id1 + "'";
if (username.Text.Equals("") ||
username.Text.Equals("") ||
password.Text.Equals("") ||
middlename.Text.Equals("") ||
surname.Text.Equals("") ||
address.Text.Equals("") ||
accountType.Text.Equals("") ||
mobilenumber.Text.Equals("")
)
{
MessageBox.Show("Please fill all fields.");
con.Close();
}
else if (age < 18)
{
MessageBox.Show("You are not allowed to work because you are under age..");
con.Close();
}
else
{
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(username.Text + "is now updated on database.");
list();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In your existing code, there are issues like.
1- Column in update are not separated by ","
2- All string are not separated using quotes ''
You should always avoid writing queries inline by concatenation of string. This will make you code vulnerable to SQL Injection.
To read more about SQL Injections check here
Change your code like following using command parameters.
cmd.CommandText = "update Employee_Details set [username] = #un, [password] = #pw, [account_Type]= #at, [Name] = #nm, [Middle_Name]= #mn, [Surname]= #sn, [address]= #add, [BirthDate] = #bd, [Mobile_Number] = #mn WHERE [Id]=#id";
cmd.Parameters.Add("#un", OleDbType.VarChar).Value = username.Text;
cmd.Parameters.Add("#pw", OleDbType.VarChar).Value = password.Text;
cmd.Parameters.Add("#at", OleDbType.VarChar).Value = accountType.Text;
cmd.Parameters.Add("#nm", OleDbType.VarChar).Value = name.Text;
cmd.Parameters.Add("#mn", OleDbType.VarChar).Value = middlename.Text;
cmd.Parameters.Add("#sn", OleDbType.VarChar).Value = surname.Text;
cmd.Parameters.Add("#add", OleDbType.VarChar).Value = address.Text;
cmd.Parameters.Add("#bd", OleDbType.Date).Value = Convert.ToDateTime(birthdate.Value);
cmd.Parameters.Add("#mn", OleDbType.VarChar).Value = mobilenumber.Text;
cmd.Parameters.Add("#id", OleDbType.VarChar).Value = id1;
Note: You need to correct the datatype based on your table structure as it is now known to me.
Your completely malformed SQL should look like:
cmd.CommandText = "update Employee_Details set " +
"username = '" + username.Text + "',"+
"[password] = '" + password.Text + "'," +
"account_Type = '" + accountType.Text + "'," +
"[Name] = '" + name.Text + "'," +
"Middle_Name = '" + middlename.Text + "'," +
"Surname = '" + surname.Text + "'," +
"address = '" + address.Text + "'," +
"BirthDate = #" + birthdate.Value.ToString("yyyy'/'MM'/dd") + "#," +
"Mobile_Number = '" + mobilenumber.Text + "' " +
"where ID = " + id1 + "";
That said, DO use parameters as already explained. Much easier and safer.

Reducing the lines of code based on conditions

I have 2 if conditions, but with this line of code is getting increased. Can I reduce some code so that it works the same as it is now.
if (ddlProject.SelectedValue != "0" && ddlBuilding.SelectedValue != "0")
{
string queryInsert;
DataTable dtval = new DataTable();
dtval = CF.ExecuteDT("Select BOOKING_NO from xxacl_pN_LEASES_ALL where project_id = '" + ddlProject.SelectedValue + "' and building_id = '" + ddlBuilding.SelectedValue + "'");
for (int i = 0; i < dtval.Rows.Count; i++)
{
string StrSeq = CF.ExecuteScaler("Select xxcus.xxacl_pN_LEASES_ALL_SEQ.next_val from xxacl_pN_LEASES_ALL");
queryInsert = "Insert into xxacl_pN_LEASES_ALL_h select '" + StrSeq + "', SYSDATE FROM xxacl_pn_leases_all where booking_no = '" + dtval.Rows[i]["BOOKING_NO"].ToString() + "'";
OracleConnection conUpdate = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd1 = new OracleCommand();
string allQueryUpdate = queryInsert;
cmd1.CommandText = allQueryUpdate;
cmd1.Connection = conUpdate;
conUpdate.Open();
cmd1.ExecuteNonQuery();
}
string queryUpdate;
queryUpdate = "update xxacl_pN_LEASES_ALL set ASSIGNED_TO = '" + ddlSalesUser.SelectedValue + "'";
OracleConnection conUpdate1 = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd2 = new OracleCommand();
string allQueryUpdate1 = queryUpdate;
cmd2.CommandText = allQueryUpdate1;
cmd2.Connection = conUpdate1;
conUpdate1.Open();
cmd2.ExecuteNonQuery();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record updated successfully');window.location ='FrmHoldingCoordinateUpdate.aspx?Redirect=" + Request.QueryString["Redirect"] + "&userid=" + Request.QueryString["userid"].ToString() + "';", true);
}
if (ddlProject.SelectedValue != "0" && ddlBuilding.SelectedValue == "0")
{
string queryInsert;
DataTable dtval = new DataTable();
dtval = CF.ExecuteDT("Select BOOKING_NO from xxacl_pN_LEASES_ALL where project_id = '" + ddlProject.SelectedValue + "' and building_id = '" + ddlBuilding.SelectedValue + "'");
for (int i = 0; i < dtval.Rows.Count; i++)
{
string StrSeq = CF.ExecuteScaler("Select xxcus.xxacl_pN_LEASES_ALL_SEQ.next_val from xxacl_pN_LEASES_ALL");
queryInsert = "Insert into xxacl_pN_LEASES_ALL_h select '" + StrSeq + "', SYSDATE FROM xxacl_pn_leases_all where booking_no = '" + dtval.Rows[i]["BOOKING_NO"].ToString() + "'";
OracleConnection conUpdate = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd1 = new OracleCommand();
string allQueryUpdate = queryInsert;
cmd1.CommandText = allQueryUpdate;
cmd1.Connection = conUpdate;
conUpdate.Open();
cmd1.ExecuteNonQuery();
}
string queryUpdate;
queryUpdate = "update xxacl_pN_LEASES_ALL set ASSIGNED_TO = '" + ddlSalesUser.SelectedValue + "'";
OracleConnection conUpdate1 = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd2 = new OracleCommand();
string allQueryUpdate1 = queryUpdate;
cmd2.CommandText = allQueryUpdate1;
cmd2.Connection = conUpdate1;
conUpdate1.Open();
cmd2.ExecuteNonQuery();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record updated successfully');window.location ='FrmHoldingCoordinateUpdate.aspx?Redirect=" + Request.QueryString["Redirect"] + "&userid=" + Request.QueryString["userid"].ToString() + "';", true);
}
Just I am checking the conditions.Rest code is same
I compared the code written in both the if statements using winMerge tool. There is absolutely no difference of even a single bit. You should simply create a private method to enable code reuse in your module. This is how it might look. Without doubt still more refactoring can be done even in the new function UpdateDatabase that I've written to align it to the principles of clean-code.
if (ddlProject.SelectedValue != "0" && ddlBuilding.SelectedValue != "0")
{
UpdateDatabase();
}
if (ddlProject.SelectedValue != "0" && ddlBuilding.SelectedValue == "0")
{
UpdateDatabase();
}
private void UpdateDatabase()
{
string queryInsert;
DataTable dtval = new DataTable();
dtval = CF.ExecuteDT("Select BOOKING_NO from xxacl_pN_LEASES_ALL where project_id = '" + ddlProject.SelectedValue + "' and building_id = '" + ddlBuilding.SelectedValue + "'");
for (int i = 0; i < dtval.Rows.Count; i++)
{
string StrSeq = CF.ExecuteScaler("Select xxcus.xxacl_pN_LEASES_ALL_SEQ.next_val from xxacl_pN_LEASES_ALL");
queryInsert = "Insert into xxacl_pN_LEASES_ALL_h select '" + StrSeq + "', SYSDATE FROM xxacl_pn_leases_all where booking_no = '" + dtval.Rows[i]["BOOKING_NO"].ToString() + "'";
OracleConnection conUpdate = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd1 = new OracleCommand();
string allQueryUpdate = queryInsert;
cmd1.CommandText = allQueryUpdate;
cmd1.Connection = conUpdate;
conUpdate.Open();
cmd1.ExecuteNonQuery();
}
string queryUpdate;
queryUpdate = "update xxacl_pN_LEASES_ALL set ASSIGNED_TO = '" + ddlSalesUser.SelectedValue + "'";
OracleConnection conUpdate1 = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd2 = new OracleCommand();
string allQueryUpdate1 = queryUpdate;
cmd2.CommandText = allQueryUpdate1;
cmd2.Connection = conUpdate1;
conUpdate1.Open();
cmd2.ExecuteNonQuery();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record updated successfully');window.location ='FrmHoldingCoordinateUpdate.aspx?Redirect=" + Request.QueryString["Redirect"] + "&userid=" + Request.QueryString["userid"].ToString() + "';", true);
}
Improving upon the above answer, I do not see a need for multiple IF conditions either.
if (ddlProject.SelectedValue != "0")
{
UpdateDatabase();
}
private void UpdateDatabase()
{
string queryInsert;
DataTable dtval = new DataTable();
dtval = CF.ExecuteDT("Select BOOKING_NO from xxacl_pN_LEASES_ALL where project_id = '" + ddlProject.SelectedValue + "' and building_id = '" + ddlBuilding.SelectedValue + "'");
for (int i = 0; i < dtval.Rows.Count; i++)
{
string StrSeq = CF.ExecuteScaler("Select xxcus.xxacl_pN_LEASES_ALL_SEQ.next_val from xxacl_pN_LEASES_ALL");
queryInsert = "Insert into xxacl_pN_LEASES_ALL_h select '" + StrSeq + "', SYSDATE FROM xxacl_pn_leases_all where booking_no = '" + dtval.Rows[i]["BOOKING_NO"].ToString() + "'";
OracleConnection conUpdate = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd1 = new OracleCommand();
string allQueryUpdate = queryInsert;
cmd1.CommandText = allQueryUpdate;
cmd1.Connection = conUpdate;
conUpdate.Open();
cmd1.ExecuteNonQuery();
}
string queryUpdate;
queryUpdate = "update xxacl_pN_LEASES_ALL set ASSIGNED_TO = '" + ddlSalesUser.SelectedValue + "'";
OracleConnection conUpdate1 = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd2 = new OracleCommand();
string allQueryUpdate1 = queryUpdate;
cmd2.CommandText = allQueryUpdate1;
cmd2.Connection = conUpdate1;
conUpdate1.Open();
cmd2.ExecuteNonQuery();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record updated successfully');window.location ='FrmHoldingCoordinateUpdate.aspx?Redirect=" + Request.QueryString["Redirect"] + "&userid=" + Request.QueryString["userid"].ToString() + "';", true);
}

Reading access database

I have written code to return values based on a search box however at times, the value entered into the search box can apply to several records within an MSAccess DB.
Is there a way where I can scroll through the records that apply to the value in the search box by using a button?
public void LoopThroughRecs(OleDbDataReader Data)
{
Data.Read();
{
FirstName.Text = Data["Initial"].ToString();
LastName.Text = Data["Surname"].ToString();
Address1.Text = Data["Address 1"].ToString();
Address2.Text = Data["Address 2"].ToString();
Address3.Text = Data["Address 3"].ToString();
TownCity.Text = Data["Post Town"].ToString();
PostCode.Text = Data["Post Code"].ToString();
Telephone.Text = Data["Telephone"].ToString();
LstSvcDat.Text = Data["LastService"].ToString();
BoilerMan.Text = Data["Manufacturer"].ToString();
BoilerMod.Text = Data["Model"].ToString();
}
Data.Close();
}
public void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
try
{
conn.Open();
OleDbCommand command = new OleDbCommand("SELECT CustCode,Initial,Surname,[Address 1],[Address 2],[Address 3],[Post Town],[Post Code],Telephone,Equipment.CustID AS CustID,Equipment.Manufacturer AS Manufacturer,Equipment.Model AS Model,Equipment.LastService AS LastService FROM Contacts LEFT OUTER JOIN Equipment ON Equipment.CustID = Contacts.CustID WHERE Archived = 0 AND (CustCode = '" + textBox12.Text + "' OR Initial = '" + textBox12.Text + "' OR Surname = '" + textBox12.Text + "' OR Initial = '" + textBox12.Text + "' OR [Post Town] = '" + textBox12.Text + "' OR [Post Code] = '" + textBox12 + "')", conn);
OleDbDataReader Data = command.ExecuteReader();
LoopThroughRecs(Data);
}
finally
{
conn.Close();
}
}

Updating Database on button click

i have a button that suppose to update data into the database.
private void button4_Click(object sender, EventArgs e)
{
//need update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = Int32.Parse(x);
int z = y + 1;
//SqlCeCommand cmdC = conn.CreateCommand();
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = '" + z + "', ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
conn.Close();
}
but i get this error..
can someone help?
update =
i've changed my code to
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
but the problem now is that , there's no update.
the iCount in the database is an INT , value is 0.
There is also no update for the viewtime and lastview.
where did i go wrong now?
change this:
cmdC.CommandText = "Update ComDet set iCount = '" + z + "', ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
to
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
you dont need the "'" apostrophe around it becuase its a number. That would definitely get you string not in correct format error
I would guess maybe the icount value is not a number, i would recommend using TryParse just in case. And that should keep this error from happening. What to do about a bad value getting returned by the query is another issue.
private void button4_Click(object sender, EventArgs e)
{
//need update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = 0;
if(Int32.TryParse(x,out y))
{
System.Diagnostics.Debug.WriteLine("iCount was an valid int32");
int z = y + 1;
//SqlCeCommand cmdC = conn.CreateCommand();
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
}
else
System.Diagnostics.Debug.WriteLine("iCount was NOT a valid int32, value: " + x);
conn.Close();
}
Have you checked the value of the 'x' variable? The exception informs that the value of X isn't a valid integer, so the FormatException is thrown.

Pass value from one page to another page and update

I have 2 pages, page 1 include the gridview and I made one linkbutton that passes the ID to another page ( page 2). On page 2 I fill 10 textboxes and I have one button for edit info.
This code is for page 1 :
...
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbNextPage" runat="server"
PostBackUrl='<%# "~/secure/upst.aspx?id="+ Eval("ID_st") %>'>edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
...
and this is the code for page 2:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtID.Text = Request.QueryString["id"].ToString();
}
SqlConnection con = new SqlConnection(strcon);
string query = "select * from user_st where ID_st = #id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", stid);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
txtName.Text = dr["name"].ToString();
txtFamily.Text = dr["family"].ToString();
txtAddress.Text = dr["adres"].ToString();
txtHomeTel.Text = dr["home_tel"].ToString();
txtTahsilat.Text = dr["tahsilat"].ToString();
txtTel.Text = dr["celphone"].ToString();
txtEmail.Text = dr["email"].ToString();
txtShoghl.Text = dr["shoghl"].ToString();
txtAge.Text = dr["age"].ToString();
txtFadername.Text = dr["fader_name"].ToString();
txtIDnumber.Text = dr["melli_code"].ToString();
txtShSh.Text = dr["sh_sh"].ToString();
}
protected void btnOk_Click(object sender, EventArgs e)
{
Boolean res = false;
SqlConnection conn = new SqlConnection(strcon);
string famil = txtFamily.Text;
string name = txtName.Text;
string fader = txtFadername.Text;
string tahsil = txtTahsilat.Text;
Double telhome = Convert.ToDouble(txtHomeTel.Text);
string adres = txtAddress.Text;
Double cel = Convert.ToDouble(txtTel.Text);
string email = txtEmail.Text;
Double shsh = Convert.ToDouble(txtIDnumber.Text);
string shoghl = txtShoghl.Text;
int age = Convert.ToInt32(txtAge.Text);
Double melli = Convert.ToDouble(txtIDnumber.Text);
int id = Convert.ToInt32(txtID.Text);
string query = "update user_st set name=#name ,fader_name=#fader ,family=#famil,tahsilat=#tahsil,adres=#adres,home_tel=#telhome,celphone=#cel,email=#email ,sh_sh=#shsh,shoghl=#shoghl,age=#age,melli_code=#melli where ID_st=#id";
SqlCommand cmdup = new SqlCommand(query, conn);
cmdup.Parameters.AddWithValue("#name",name);
cmdup.Parameters.AddWithValue("#fader_name",fader );
cmdup.Parameters.AddWithValue("#family", famil);
cmdup.Parameters.AddWithValue("#tahsilat",tahsil);
cmdup.Parameters.AddWithValue("#adres", adres);
cmdup.Parameters.AddWithValue("home_tel",telhome );
cmdup.Parameters.AddWithValue("#celphone",cel );
cmdup.Parameters.AddWithValue("#email", email);
cmdup.Parameters.AddWithValue("#sh_sh", shsh);
cmdup.Parameters.AddWithValue("#shoghl", shoghl);
cmdup.Parameters.AddWithValue("#age",age );
cmdup.Parameters.AddWithValue("#melli_code", melli);
cmdup.Parameters.AddWithValue("#id", id);
try
{
conn.Open();
cmdup.ExecuteNonQuery();
conn.Close();
res = true;
}
catch (SqlException ex)
{
lblRes.Text = "error" + ex.ToString();
}
if (res)
{
lblResult.Text = "Ok";
}
That is not working so, I tried this:
//cmdup.Parameters.Add("#name", SqlDbType.NVarChar, 50).Value = txtName.Text;
//cmdup.Parameters.Add("#fader_name", SqlDbType.NVarChar, 50).Value = txtFadername.Text;
//cmdup.Parameters.Add("#family", SqlDbType.NVarChar, 50).Value = txtFamily.Text;
//cmdup.Parameters.Add("#tahsilat", SqlDbType.NVarChar, 50).Value = txtTahsilat.Text;
//cmdup.Parameters.Add("#adres", SqlDbType.NVarChar, 150).Value = txtAddress.Text;
//cmdup.Parameters.Add("home_tel", SqlDbType.Char, 10).Value = txtHomeTel.Text;
//cmdup.Parameters.Add("#celphone", SqlDbType.Char, 10).Value = txtTel.Text;
//cmdup.Parameters.Add("#email", SqlDbType.VarChar).Value = txtEmail.Text;
//cmdup.Parameters.Add("#sh_sh", SqlDbType.Char, 10).Value = txtShSh.Text;
//cmdup.Parameters.Add("#shoghl", SqlDbType.NVarChar, 50).Value = txtShoghl.Text;
//cmdup.Parameters.Add("#age", SqlDbType.Int).Value = txtAge.Text;
//cmdup.Parameters.Add("#melli_code", SqlDbType.Char, 10).Value = txtIDnumber.Text;
//cmdup.Parameters.Add("#id", SqlDbType.Int).Value = txtID.Text;
or this :
//SqlCommand cmdup = new SqlCommand("EXEC up_st'" + txtName.Text. + "' , '" + txtFamily.Text + "' , '" + txtTahsilat.Text +"' , '" + txtAddress.Text + "' , '"
// + txtHomeTel.Text + "' , '" + txtTel.Text + "' , '" + txtEmail.Text + "' , '" + txtShoghl.Text + "' , '"
// + txtAge.Text + "' , '" + txtFadername.Text + "' , '" + txtIDnumber.Text + "' , '" + txtShSh.Text + "' , '"
// + txtID.Text + "'", conn);
or this :
/*"update user_st set name='" + txtName.Text + "',fader_name='" + txtFadername.Text + "',family='" + txtFamily.Text + "',tahsilat='" + txtTahsilat.Text + "',adres='" + txtAddress.Text + "',home_tel='" + txtHomeTel.Text + "',celphone='"
+ txtTel.Text + "',email='" + txtEmail.Text + "',sh_sh='" + txtShSh.Text + "',shoghl='" + txtShoghl.Text + "',age='" + txtAge.Text + "',melli_code='" + txtIDnumber.Text + "' where ID_st=" + txtID.Text*/
but it also doesn't work.
You need to move your initial Sql select into the !IsPostback block because what's happening is you are posting back your updates, but Page_Load fires before the textboxes are updated. So everything is working in your initial code, you are just updating it with the initial information. Try this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtID.Text = Request.QueryString["id"].ToString();
SqlConnection con = new SqlConnection(strcon);
string query = "select * from user_st where ID_st = #id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", stid);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
txtName.Text = dr["name"].ToString();
txtFamily.Text = dr["family"].ToString();
txtAddress.Text = dr["adres"].ToString();
txtHomeTel.Text = dr["home_tel"].ToString();
txtTahsilat.Text = dr["tahsilat"].ToString();
txtTel.Text = dr["celphone"].ToString();
txtEmail.Text = dr["email"].ToString();
txtShoghl.Text = dr["shoghl"].ToString();
txtAge.Text = dr["age"].ToString();
txtFadername.Text = dr["fader_name"].ToString();
txtIDnumber.Text = dr["melli_code"].ToString();
txtShSh.Text = dr["sh_sh"].ToString();
}
}
If you really want to reload the stuff from the database, you can pop that query into a function and re-run it after the button click update in the button click function (at the end), but there really is no reason since the textboxes will already have the same info.

Categories