Reducing the lines of code based on conditions - c#

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);
}

Related

Is there equivalent C# function for "mysqli_fetch_array"?

So I want to manually convert the PHP function to C# Windows Form but I don't know the equivalent function mysqli_fetch_array in C# and how to do array PHP in C#?
I've googling but there is no correct solution.
This is in C# Windows Form
openConnection();
string selectQuery = "SELECT * FROM data_pegawai WHERE is_deleted=0 AND username='" + user + "'";
MySqlCommand command = new MySqlCommand(selectQuery, conn);
MySqlDataReader reader = command.ExecuteReader();
while (valuesList = reader.Read())
{
id = reader.GetInt32("id_peg");
}
closeConnection();
kembali = bayar - subtotal;
lblKembali.Text = kembali.ToString();
string insertQuery1 = "UPDATE data_transaksi SET status_pengerjaan='Lunas',potongan_harga='" + diskonrupiah.ToString() + "',subtotal='" + txtSubtotal.Text + "' WHERE id_transaksi =" + int.Parse(txtID_T.Text);
string insertQuery2 = "INSERT INTO pegawai_onduty VALUES(NULL, '" + id + "','" + txtID_T.Text + "')";
openConnection();
string selectQuery1 = "SELECT dsp.id_spareparts, dtsp.JUMLAH_SPAREPART from data_transaksi dt LEFT JOIN detail_transaksi_sparepart dtsp ON dt.id_transaksi=dtsp.id_transaksi LEFT JOIN spareparts_motor sm ON dtsp.ID_SPAREPARTMOTOR=sm.ID_SPAREPARTMOTOR LEFT JOIN data_spareparts dsp ON sm.id_spareparts=dsp.id_spareparts where dtsp.id_transaksi =" + int.Parse(txtID_T.Text);
MySqlCommand command1 = new MySqlCommand(selectQuery1, conn);
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
int getData = "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='$jml[0]'";
}
closeConnection();
runQuery(insertQuery1);
runQuery(insertQuery2);
loadTransaksi();
And this is PHP code that I trying to convert to
while($jml=mysqli_fetch_array($dataJumlah))
{
$getData = mysqli_query($conn, "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='$jml[0]' ") or die (mysqli_error($conn));
$dataSP = mysqli_fetch_array($getData);
$idSpareparts = $dataSP[0];
$jmlStok = (int) $dataSP[0];
$jmlJual = (int) $jml[1];
$sisaStok = $jmlStok-$jmlJual;
$updateStok = mysqli_query($conn,"UPDATE data_spareparts SET jumlah_stok=$sisaStok WHERE id_spareparts='$jml[0]'") or die (mysqli_error($conn));
}
So I want to do "while($jml=mysqli_fetch_array($dataJumlah))" in C# and the rest of it. But how?
This question has been answered.
Below is the answer
subtotal = Convert.ToDouble(txtSubtotal.Text);
bayar = Convert.ToDouble(txtBayar.Text);
if (bayar < subtotal)
{
MessageBox.Show("Nominal yang dibayarkan lebih kecil dari Subtotal!");
}
else
{
openConnection();
string selectQuery = "SELECT * FROM data_pegawai WHERE is_deleted=0 AND username='" + user + "'";
MySqlCommand command1 = new MySqlCommand(selectQuery, conn);
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
id = reader1.GetInt32("id_peg");
}
closeConnection();
kembali = bayar - subtotal;
lblKembali.Text = kembali.ToString();
string insertQuery1 = "UPDATE data_transaksi SET status_pengerjaan='Lunas',potongan_harga='" + diskonrupiah.ToString() + "',subtotal='" + txtSubtotal.Text + "' WHERE id_transaksi =" + int.Parse(txtID_T.Text);
string insertQuery2 = "INSERT INTO pegawai_onduty VALUES(NULL, '" + id + "','" + txtID_T.Text + "')";
openConnection();
string selectQuery1 = "SELECT dsp.id_spareparts, dtsp.JUMLAH_SPAREPART from data_transaksi dt LEFT JOIN detail_transaksi_sparepart dtsp ON dt.id_transaksi=dtsp.id_transaksi LEFT JOIN spareparts_motor sm ON dtsp.ID_SPAREPARTMOTOR=sm.ID_SPAREPARTMOTOR LEFT JOIN data_spareparts dsp ON sm.id_spareparts=dsp.id_spareparts where dtsp.id_transaksi =" + int.Parse(txtID_T.Text);
MySqlCommand command2 = new MySqlCommand(selectQuery1, conn);
MySqlDataReader reader2 = command2.ExecuteReader();
while (reader2.Read())
{
idSparepart = reader2.GetString(0);
jmlJual = reader2.GetInt32(1);
}
closeConnection();
openConnection();
string getData = "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='" + idSparepart + "'";
MySqlCommand command3 = new MySqlCommand(getData, conn);
MySqlDataReader reader3 = command3.ExecuteReader();
while (reader3.Read())
{
jmlStok = reader3.GetInt32(0);
}
closeConnection();
sisastok = jmlStok - jmlJual;
string updateStok = "UPDATE data_spareparts SET jumlah_stok = '" + sisastok + "' WHERE id_spareparts ='" + idSparepart + "'";
try
{
openConnection();
MySqlCommand command4 = new MySqlCommand(updateStok, conn);
if (command4.ExecuteNonQuery() == 1)
{
MessageBox.Show("Data berhasil disimpan!");
}
else
{
MessageBox.Show("Data tidak berhasil disimpan!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
runQuery(insertQuery1);
runQuery(insertQuery2);
loadTransaksi();
}

No mapping exists from object type

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 +"'";

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.

Error :Transaction is completed ,it is no longer usable

//How to exceute multiple sqlcommands in one transaction in C#..i am using like this but it gives me error..plz let me know what is problem with code..
string[] files = Directory.GetFiles(dir);
foreach (string subfiles in files)
{
con.Open();
SqlTransaction myTrans=null;
myTrans= con.BeginTransaction();
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.Transaction = myTrans;
cmd.CommandText = "select descr from genlookup where Code='SS_Purchase_No' and RecId=99998";
SqlDataReader drr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
//SqlDataAdapter da = new SqlDataAdapter(qry1, con);
DataTable dtw = new DataTable();
dtw.Load(drr);
DataSet dsr = new DataSet();
dsr.Tables.Add(dtw);
//SqlDataAdapter darun = new SqlDataAdapter("select descr from genlookup where Code='SS_Purchase_No' and RecId=99998", con);
//DataSet dsr = new DataSet();
//darun.Fill(dsr);
int run_no = Convert.ToInt32(dsr.Tables[0].Rows[0]["descr"].ToString());
filename = Path.GetFileNameWithoutExtension(subfiles);
string filenames = Path.GetFileName(subfiles);
if (subfiles.Trim().EndsWith(".xlsx"))
{
strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", subfiles);
}
else if (subfiles.Trim().EndsWith(".xls"))
{
strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", subfiles);
}
OleDbConnection exlcon = new OleDbConnection(strConn);
exlcon.Open();
string myTableName = exlcon.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString();
OleDbDataAdapter oledbadpt = new OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), exlcon);
DataSet d_s = new DataSet();
oledbadpt.Fill(d_s);
exlcon.Close();
for (int i = 7; i < d_s.Tables[0].Rows.Count - 1; i++)
{
PARTNER_ID = d_s.Tables[0].Rows[i]["F1"].ToString();
RTV_LOCTN = d_s.Tables[0].Rows[i]["F3"].ToString();
DateTime date1 = Convert.ToDateTime(d_s.Tables[0].Rows[i]["F13"]);
string ddmm = date1.ToString("yyyyMMdd");
string[] aa = Color_size.Split('/');
// string colr="";
string size = "";
foreach (string ss in aa)
{
size = ss;
}
}
con.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = con;
myCommand.Transaction = myTrans;
myCommand.CommandText = "insert into HSR_Purch_RETURN(PARTNER_ID,RTV_LOCTN)" +
" values('" + PARTNER_ID + "'," + "'" + RTV_LOCTN + "') ";
myCommand.ExecuteNonQuery();
//con.Open();
//SqlCommand cmdd = new SqlCommand(insert, con);
//int value1 = cmdd.ExecuteNonQuery();
//values = string.Empty;
con.Close();
if ((shrwcode != "") && (flag == "F"))
{
string zz = "select DistributionCenter,GLCountry,GLZone,GLState,GLCity from showroommaster where ShowroomCode='" + shrwcode + "'";
SqlDataAdapter da11 = new SqlDataAdapter(zz, con);
DataSet ds11 = new DataSet();
da11.Fill(ds11);
string Dcenter = ds11.Tables[0].Rows[0]["DistributionCenter"].ToString();
string GLCountry = ds11.Tables[0].Rows[0]["GLCountry"].ToString();
string fff = "select isnull(max(EntSrlNo),0)+1 as EntSrlNo from IDTableExtd where ShowroomCode='" + shrwcode + "' and DocDate='" + RTV_DATE + "'";
SqlDataAdapter das = new SqlDataAdapter(fff, con);
DataSet dss = new DataSet();
das.Fill(dss);
SqlCommand extdcmd = new SqlCommand();
extdcmd.Connection = con;
extdcmd.Transaction = myTrans;
string docpre = "PR" + RTV_DATE.Substring(2, 2);
if (dss.Tables[0].Rows.Count > 0)
{
slno = Convert.ToInt32(dss.Tables[0].Rows[0]["EntSrlNo"].ToString());
extdcmd.CommandText = "insert into IDTableExtd (ShowroomCode,TrnType,TrnCtrlNo,DocNoPrefix,docno,DocDate,EntSrlNo,StockNo,DistributionCenter,GLCountry,GLZone,GLState,GLCity,PartyType,PromoValue_LineLevel,DocQty,NetValue,BatchSrlNo)" +
"values ('" + shrwcode + "'," + "'2300'," + "'" + ddmm + "'," + "'" + docpre + "'," + "'" + ddmm + "'," + "'" + RTV_DATE + "'," + "'" + slno + "'," + "'" + TRN_STOCKNO + "'," + "'" + Dcenter + "'," + "'" + GLCountry + "'," + "'" + GLZone + "',"
+ "'" + GLState + "'," + "'" + GLCity + "','10'," + '0' + ",'" + RTV_QTY + "'," + "'" + RTV_cost + "','0')";
con.Open();
// SqlCommand extdcmd = new SqlCommand(instableextd, con);
extdcmd.ExecuteNonQuery();
con.Close();
}
}
}
myTrans.Commit(); ///Error is getting after exceuting this line..
You need refactor your´s code, first, and use something like that:
using (var = new SqlConnection(_connectionstring))
{
try
{
connection.Open();
using(SqlTransaction transaction = connection.BeginTransaction())
{
using (SqlCommand command1= new SqlCommand(commandtext, connection, transaction ))
{
//Do something here
}
using (SqlCommand command2= new SqlCommand(commandtext, connection, transaction ))
{
//Do another stuff here
}
...
transaction .Commit();
}
}
catch (Exception Ex)
{
if (transaction != null) transaction .Rollback();
}
}
(1)As Joseph said refactor your code using Using statement, which helps to dispose the objects properly.
(2)Your code is prone to SQL Injection, so use SQLParameter.
I've shown a sample from your code make it fully.
con.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = con;
myCommand.Transaction = myTrans;
myCommand.CommandText = "insert into HSR_Purch_RETURN(PARTNER_ID,RTV_LOCTN) values(#partnerId,#rtv)";
myCommand.Parameters.Add(new SqlParameter("partnerId",PARTNER_ID));
myCommand.Parameters.Add(new SqlParameter("rtv",RTV_LOCTN));
myCommand.ExecuteNonQuery();
//con.Open();
//SqlCommand cmdd = new SqlCommand(insert, con);
//int value1 = cmdd.ExecuteNonQuery();
//values = string.Empty;
con.Close();

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