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.
Related
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);
}
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();
}
}
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 +"'";
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.
I'm trying to make a search button that when i enter an ID to a Textbox and press it , it goes to my private SQL server database and get the data row referred to that ID , But The exception handler brings me error because of my wrong CommandText .. Here is my Code
private void SearchBtn_Click(object sender, EventArgs e)
{
cn.ConnectionString = Properties.Settings.Default.ConStr;
if (ID.Text == "")
{
MessageBox.Show("Please Enter The ID you would like to search");
}
else
{
SqlCommand com = new SqlCommand();
cn.Open();
SqlParameter user = new SqlParameter("#ID", SqlDbType.Int);
SqlParameter FN = new SqlParameter("#First_Name",SqlDbType.NChar);
SqlParameter LN = new SqlParameter("#Last_Name", SqlDbType.VarChar);
SqlParameter Jb = new SqlParameter("#Job", SqlDbType.VarChar);
SqlParameter Ag = new SqlParameter("#Age", SqlDbType.VarChar);
SqlParameter ph = new SqlParameter("#Phone", SqlDbType.VarChar);
com.Parameters.Add(user);
com.Parameters.Add(FN);
com.Parameters.Add(LN);
com.Parameters.Add(Jb);
com.Parameters.Add(Ag);
com.Parameters.Add(ph);
com.Connection = cn;
Here is my Error :
*com.CommandText = "Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList) ";*
user.Direction = ParameterDirection.Input;
FN.Direction = ParameterDirection.Output;
LN.Direction = ParameterDirection.Output;
Jb.Direction = ParameterDirection.Output;
Ag.Direction = ParameterDirection.Output;
ph.Direction = ParameterDirection.Output;
FN.Size = 10;
LN.Size = 10;
Jb.Size = 10;
Ag.Size = 10;
ph.Size = 10;
user.Value = Convert.ToInt32(ID.Text);
try
{
com.ExecuteNonQuery();
FirstName.Text = FN.Value.ToString();
LastName.Text = LN.Value.ToString();
Job.Text = Jb.Value.ToString();
Age.Text = Ag.Value.ToString();
Phone.Text = ph.Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
I'm Using Visual Studio 2012 .
Thanks in Advance .
"Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList)"
doesn't really look like SQL. Also I'm not quite sure why you're setting loads of parameters you're not using.
Maybe you meant something like
com.CommandText = "SELECT First_Name, Last_Name, Job, Age, Phone FROM MyList WHERE ID=#Id";
com.Parameters.AddWithValue("#Id", ID.Text);
Furthermore if that's your intention, then ExecuteNonQuery is wrong as that's for INSERT, UPDATE and other things that don't return a result.
Command text should be like
com.CommandText = "SELECT First_Name, Last_Name, Job, Age, Phone FROM MyList WHERE ....";
Remove most of your parameters, leave only input ones.
Instead of com.ExecuteNonQuery() use: SqlDataReader reader = command.ExecuteReader(); and using it read your data. Example article is here
Firstly:
"Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList)"
Doesn't look like valid SQL to me.
I think you're looking to do something like this:
using (SqlConnection myConnection = new SqlConnection(connString))
{
string oString = " SELECT * from MyList WHERE (id = #id)";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.Add(new SqlParameter("#id", ID.Text));
myConnection.Open();
string name="";
string lastname ="";
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
name = oReader["name"].ToString(); // replace "name" with the name of the column you want
lastname = oReader["lastname"].ToString();
}
}
myConnection.Close();
return name + lastname;
You can use these values to set the text in your textboxes on your form:
YourNameTextbox.Text = name;
.. etc