How can i set a CommandText to my Search Button? - c#

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

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

how to insert date(long format) into access database using datetimepicker in c# ? (error is in date part only)

Error image is here
the error is in query line , its shows syntax error
try
{
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
command.CommandText = "insert into client_table(CLIENT, DATE,BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #" + dat.ToLongDateString() + "# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
this.Hide();
employee_form f1 = new employee_form("");
f1.ShowDialog();
}
thank you in advance
In Access, dates are delimited by #, not '. Also, Access does not recognize the long date format. But dates are not stored in any format so no worries, change it to:
... + "', #" + dat.ToString() + "# ...etc.
Although if you do not parameterize your query serious damage or data exposure can be done through SQL Injection because someone could type in a SQL statement into one of those textboxes that you are implicitly trusting.
Working example:
class Program
{
static void Main(string[] args)
{
System.Data.OleDb.OleDbConnectionStringBuilder bldr = new System.Data.OleDb.OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new System.Data.OleDb.OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#" + DateTime.Now.ToString() + "#)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
}
Update
However, you want to do something more like this which uses Parameters to protect against SQL Injection which is extremely easy to exploit so do not think that you don't really need to worry about it:
static void Main(string[] args)
{
OleDbConnectionStringBuilder bldr = new OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
OleDbParameter dobParam = new OleDbParameter("#dob", OleDbType.Date);
dobParam.Value = DateTime.Now;
cmd.Parameters.Add(dobParam);
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#dob)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
//code to write date in the access table.
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
//MessageBox.Show(dat.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
//command.CommandText = "insert into client_table(DATEE) values( '"dat.ToShortDateString()+"')";
command.CommandText = "insert into client_table (CLIENT, DATEE, BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #"+dat.ToShortDateString()+"# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
//New code for receiving the date between two range of dates
try
{
DateTime dat = this.dateTimePicker1.Value.Date;
DateTime dat2 = this.dateTimePicker2.Value.Date;
// MessageBox.Show(dat.ToShortDateString() + " " + dat2.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
string query;
query = "select * from client_table Where DATEE Between #" + dat.ToLongDateString() +"# and #" + dat2.ToLongDateString() + "# ";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection1.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
Thank you all of you for the support.

UPDATE STATEMENT 2 tables c#

my problem is that i tried all kind of solutions but it doesnt update my table here is my code behind of the button_click update:
protected void Button2_Click(object sender, EventArgs e)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("Files/" + fileName));
SqlConnection cnx = new SqlConnection();
cnx.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["str"].ConnectionString;
SqlCommand cmd = new SqlCommand("Update Appel_offre set Titre_ao='" + TextBox4.Text + "',Description_ao='" + TextBox5.Text + "',Cout='" + TextBox6.Text + "',Type='" + DropDownList3.Text + "',Date='" + TextBox8.Text + "',Echeance='" + TextBox9.Text + "',Reference='" + TextBox7.Text + "',Piece_jointe='" + "Files/" + fileName + "',filename='" + fileName + "' where Id_ao = '" + Session["Id_ao"] + "' ", cnx);
SqlCommand cmd1 = new SqlCommand("Update Lot set Description=#desc,Reference=#ref,Type=#type where Titre = '" + Dropdownlst.SelectedItem.Value + "'",cnx);
cnx.Open();
cmd1.Parameters.AddWithValue("#desc", TextBox2.Text );
cmd1.Parameters.AddWithValue("#ref", TextBox3.Text );
cmd1.Parameters.AddWithValue("#type", DropDownList2.Text );
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
cnx.Close();
if (IsPostBack)
{
conff.Visible = true;
}
}
It's difficult to tell what's wrong here but I will gry to improve your code.
Maybe it also fixes the issue.
Use verbatim string literals, that makes your SQL query much better to read
Use the using statement to ensure that everything gets disposed properly
Don't use string concatenation to build your SQL query but SqlParameter, without exception. That prevents you from SQL injection and other issues.
Use not AddWithvalue but Add with the correct SqlDbType, otherwise the database makes guesses about the type of your parameter.
Pass the correct type and don't let the database cast your parameters, that also validates invalid input(f.e. incorrect date)
Code:
string updateApple = #"Update Appel_offre Set
Titre_ao = #Titre_ao,
Description_ao = #Description_ao,
Cout = #Cout,
Type = #Type,
Date = #Date,
Echeance = #Echeance,
Reference = #Reference,
Piece_jointe = #Piece_jointe,
filename = #filename
where Id_ao = #Id_ao;";
string updateLot = #"Update Lot Set
Description = #Description,
Reference = #Cout,
Type = #Type
where Titre = #Titre;";
using (var cnx = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["str"].ConnectionString))
using(var cmd_UpdateApple = new SqlCommand(updateApple, cnx))
using (var cmd_UpdateLot = new SqlCommand(updateLot, cnx))
{
cmd_UpdateApple.Parameters.Add("#Titre_ao", SqlDbType.VarChar).Value = TextBox4.Text;
cmd_UpdateApple.Parameters.Add("#Description_ao", SqlDbType.VarChar).Value = TextBox5.Text;
// ...
cmd_UpdateApple.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.Parse(TextBox8.Text);
// ...
cnx.Open();
int updatedAppels = cmd_UpdateApple.ExecuteNonQuery();
cmd_UpdateLot.Parameters.Add("#Description", SqlDbType.VarChar).Value = TextBox2.Text.Text;
// ...
cmd_UpdateLot.Parameters.Add("#Titre", SqlDbType.VarChar).Value = Dropdownlst.SelectedItem.Value;
int updatedLot = cmd_UpdateApple.ExecuteNonQuery();
}
I've used DateTime.Parse, use DateTime.TryParse if the format can be invalid.

SQL query for update statement in (C#)

I am new to the C# programming. Facing the problem Incorrect syntax near 'First_Name'.! in the given below code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=HP\SQLEXPRESS100;Database=CD_Gallery;Integrated Security=true";
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("update Customer_Info First_Name ='" + fname.Text + "'");
//'" + fname.Text.ToString() + "','" + lname.Text.ToString() + "','" + landmark.Text.ToString() + "','" + address.Text.ToString() + "','" + contact.Text.ToString() + "','" + email.Text.ToString() + "','" + dateTimePicker1.Text.ToString() + "','" + deposite.Text.ToString() + "')", con);
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("You Have Successfully Updated");
Custid.Text = "";
fname.Text = "";
lname.Text = "";
address.Text = "";
contact.Text = "";
email.Text = "";
landmark.Text = "";
deposite.Text = "";
}
}
}
Problem : You forgot to add word SET after your table name in update statement.
Solution1 : Add the word SET after table name in Update query (Don't Recommend this)
"update Customer_Info SET First_Name ='" + fname.Text + "'"
Warning : Your query is open to sql injection attacks.please use parameterised queries to avoid them
Solution 2: Using Parameterised Queries
Replace This:
SqlCommand cmd = new SqlCommand("update Customer_Info SET First_Name
='"+fname.Text+"'");
With This:
SqlCommand cmd = new SqlCommand("update Customer_Info First_Name = #fname");
cmd.Parameters.AddWithValue("#fname" , fname.Text);
Your problem not in C#, in SQL syntax (you miss set keyword)
SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");
you are missing SET keyword:
update Customer_Info SET First_Name ='" + fname.Text + "'"
and also provide where clause otherwise it will update all the records in your table.
You are missing set keyword in query you have to place set like this
SqlCommand cmd = new SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");

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