Button click fires text changed event - c#

I have a textbox with autopostback property true and a button for saving.
On text changed, I get data from a database, and display in other textboxes. When I edit the textboxes and then save, the textchanged event fires, and the data does not update. Instead it saves the previous data only. I want to save the edited data.
Can anyone help me do this?
Here is the button click event:
protected void btnSave_Click(object sender, EventArgs e)
{
//TextBox1.Text = exists;
if(exists=="yes")
{
OdbcConnection DbConnection2 = new OdbcConnection(con1);
OdbcCommand DbCommand2 = DbConnection2.CreateCommand();
try
{
DbConnection2.Open();
DbCommand2.CommandText = "update tbl_trip_login set username='" + txtUser.Text.ToUpper() + "',password='" + txtPwd.Text + "',name='" + txtname.Text + "',department='" + txtDept.Text + "',designation='" + txtDesg.Text + "',DOJ='" + txtDOJ.Text + "',DOB='" + txtDOJ.Text + "',phone='" + txtPh.Text + "',Email='" + txtEmail.Text + "',Gender='" + rdbGender.SelectedItem.Text + "',Active='" + rdbActive.SelectedItem.Text + "' where upper(username)=upper('" + txtUser.Text + "')";
TextBox1.Text = DbCommand2.CommandText.ToString();
int t2 = DbCommand2.ExecuteNonQuery();
if (t2 == 1)
{
lblError.Visible = true;
lblError.Text = "Successfully Saved";
}
else
{
lblError.Text = "Not Saved.. Try again later";
lblError.Visible = true;
}
DbConnection2.Close();
}
catch (Exception e1)
{
lblError.Text = e1.Message;
lblError.Visible = true;
DbConnection2.Close();
}
}
else //if user doesn't exists,create new user
{
DateTime dd = DateTime.Now; //current date and time
string custom = dd.ToString("dd-MMM-yyyy,hh:mm,tt"); // to convert in the form : 14-APR-2013 01:35 PM
string ss = "to_date('" + custom + "','dd-mon-yyyy HH:MI AM')"; // oracle does not take only time by default, so use to_date(), and pass this string variable directly in the query
OdbcConnection DbConnection1 = new OdbcConnection(con1);
OdbcCommand DbCommand1 = DbConnection1.CreateCommand();
try
{
DbConnection1.Open();
DbCommand1.CommandText = "insert into tbl_trip_login(username,password,name,department,designation,DOJ,DOB,phone,Email,Gender,Active,Entered_by,Entered_time)values('" + txtUser.Text + "','" + txtPwd.Text + "','" + txtname.Text + "','" + txtDept.Text + "','" + txtDesg.Text + "','" + txtDOJ.Text + "','" + txtDOB.Text + "','" + txtPh.Text + "','" + txtEmail.Text + "','" + rdbGender.SelectedItem.Text + "','" + rdbActive.SelectedItem.Text + "','" + Session["UserAuthentication"].ToString() + "','" + ss + "')";
TextBox1.Text = DbCommand1.CommandText.ToString();
int t1 = DbCommand1.ExecuteNonQuery();
if (t1 == 1)
{
lblError.Visible = true;
lblError.Text = "Successfully Saved";
}
else
{
lblError.Text = "Not Saved.. Try again later";
lblError.Visible = true;
}
DbConnection1.Close();
}
catch (Exception e1)
{
lblError.Text = e1.Message;
lblError.Visible = true;
DbConnection1.Close();
}
txtUser.Focus();
txtUser.Text = "";
txtPwd.Text = "green";
}
}
And the Text Changed event:
protected void txtUser_TextChanged(object sender, EventArgs e)
{
var targetID = Request.Form["__EVENTTARGET"];
if (targetID != null && targetID != string.Empty)
{
btnSave.Enabled = true;
exists = "no";
try
{
OdbcConnection myOdbcConnection = new OdbcConnection(con1);
OdbcCommand myOdbcCommand = myOdbcConnection.CreateCommand();
string sSQL = "select username,password,name,department,designation,doj,dob,phone,email,gender,active from tbl_trip_login where upper(username)=upper('" + txtUser.Text + "')";
myOdbcCommand.CommandText = sSQL;
myOdbcConnection.Open();
OdbcDataReader myOdbcDataReader = myOdbcCommand.ExecuteReader();
if (myOdbcDataReader.HasRows)
{
exists = "yes";
txtPwd.Text = myOdbcDataReader[1].ToString();
txtname.Text = myOdbcDataReader[2].ToString();
txtDept.Text = myOdbcDataReader[3].ToString();
txtDesg.Text = myOdbcDataReader[4].ToString();
txtDOJ.Text = myOdbcDataReader[5].ToString();
txtDOB.Text = myOdbcDataReader[6].ToString();
txtPh.Text = myOdbcDataReader[7].ToString();
txtEmail.Text = myOdbcDataReader[8].ToString();
rdbGender.Text = myOdbcDataReader[9].ToString();
rdbActive.Text = myOdbcDataReader[10].ToString();
}
}
catch (Exception ex)
{
lblError.Text = ex.Message;
lblError.Visible = true;
}
}
}

Related

response redirect conflict with image inserting

I'm a beginner in C# and I have a problem with image uploading.
Everything in my code inserting in my database except for the files that I uploaded, I didn't know why it doesn't save it in the database, it only saved when I remove the Response.Redirect("Personalinformation.aspx") but I can't remove this response redirect because I need it.
protected void Button8_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conString);
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
if (TextBox11.Text != "" && TextBox8.Text != "" && TextBox9.Text != "" )
{
if (FileUpload1.PostedFile != null)
{
if (FileUpload2.PostedFile != null)
{
string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string FileName1 = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("/upload/" + FileName));
FileUpload2.SaveAs(Server.MapPath("/identification/" + FileName1));
String q = "Insert into dbo.requests(request_type,visit_date,reason,request_date,status_id,user_id,user_name,FileName,FilePath,End_vdate,FileName1,FilePath1,RequestNotes,VisitorType)values(N'" + DropDownList1.SelectedValue + "',N'" + TextBox8.Text + "',N'" + TextBox9.Text + "','" + DateTime.Now + "','4','" + Session["empNo"] + "',N'" + Session["ArbnName"] + "' , #FileName , #FilePath ,N'" + TextBox10.Text + "',#FileName1 , #FilePath1)";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#FileName", FileName);
cmd.Parameters.AddWithValue("#FilePath", "/upload/" + FileName);
cmd.Parameters.AddWithValue("#FileName1", FileName1);
cmd.Parameters.AddWithValue("#FilePath1", "/identification/" + FileName1);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
else
{
String q = "Insert into dbo.requests(request_type,visit_date,reason,request_date,status_id,user_id,user_name,End_vdate,phone_ext)values(N'" + DropDownList1.SelectedValue + "',N'" + TextBox8.Text + "',N'" + TextBox9.Text + "','" + DateTime.Now + "','4','" + Session["empNo"] + "' ,N'" + Session["ArbnName"] + "',N'" + TextBox10.Text + "','" + TextBox11.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
}
response.redirect("Personalinformation.aspx");
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert(' هناك حقول مطلوبة فارغة ');</script>");
}
String c = "Insert into dbo.logFile(user_id,transaction_date,action_type) values ('" + Session["empNo"] + "', '" + DateTime.Now + "' ,N' طلب قبول زائر') ";
SqlCommand cmdc = new SqlCommand(c, con);
cmdc.ExecuteNonQuery();
con.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0) //index of long visit
{
FileUpload1.Visible = false;
FileUpload2.Visible = false;
Button6.Visible = false;
TextBox10.Visible = false;
Label2.Visible = false;
Label3.Visible = false;
}
else
{
FileUpload1.Visible = true;
FileUpload2.Visible = true;
Button6.Visible = true;
TextBox10.Visible = true;
Label2.Visible = true;
Label3.Visible = true;
}
}
Instead of Response.Redirect, you can try using Server.Transfer if you intend to transfer the user to other page.
See more details at difference between Server.Transfer and Response.Redirect?
You have used FileUpload1.SaveAs:
FileUpload1.SaveAs(Server.MapPath("/upload/" + FileName));
FileUpload2.SaveAs(Server.MapPath("/identification/" + FileName1));
Instead of that use this:
FileUpload1.PostedFile.SaveAs(Server.MapPath("/upload/" + FileName));
FileUpload2.PostedFile.SaveAs(Server.MapPath("/identification/" + FileName1));
You are missing PostedFile keyword in that.

I Cannot Update A Table in Ms Access with C#. No Error Message

I want to update a table in Ms Access whenever I click save button in C#. So, whenever I add a new value into the [Checkin] table, the [kamar] table will update itself. But, [kamar] table doesn't want to update. There is no error message.
Here is my code:
private void simpan()
{
string noreg = noregBox.Text;
string noktp = noktpCBox.Text;
string nokamar = nokamarCBox.Text;
string tglCheckin = txttanggalCheckin.Value.ToString("MM/dd/yyyy");
decimal dp = Convert.ToDecimal(dpBox.Text);
if (nokamar.Equals("") || noreg.Equals(""))
{
MessageBox.Show("Data tidak boleh kosong");
return;
}
try
{
cmdCheckin = new OleDbCommand("insert into Checkin (no_reg_in,tgl_checkin,no_ktp,no_kamar,dp_kamar) values ('" + noreg + "', '" + tglCheckin + "', '" + noktp + "', '" + nokamar + "', '" + dp + "')", cn);
cmdCheckin.ExecuteNonQuery();
MessageBox.Show("Data berhasil disimpan");
nokamarCBox.Text = "";
noktpCBox.Text = "";
namatamuBox.Clear();
jktamuCBox.Text = "";
telptamuBox.Clear();
alamatBox.Clear();
kelaskamarBox.Clear();
biayaBox.Clear();
dpBox.Clear();
muat();
}
catch (OleDbException error)
{
MessageBox.Show(Convert.ToString(error));
return;
}
}
private void perbarui()
{
string nokamar = nokamarCBox.Text;
string kelas = kelaskamarBox.Text;
try
{
cmdCheckin = new OleDbCommand("update kamar set status = 0 where no_kamar = '" + nokamar + "'", cn);
cmdCheckin.ExecuteNonQuery();
dtCheckin.Clear();
daCheckin.Fill(dtCheckin);
}
catch (Exception err)
{
MessageBox.Show("Data gagal diubah, error" + err);
}
}
private void button2_Click(object sender, EventArgs e)
{
simpan();
perbarui();
muat();
}
button2 is save button. Thank you. Sorry for my bad English
First you set:
nokamarCBox.Text = "";
Then:
string nokamar = nokamarCBox.Text;
Thus, no nokamar is to update.

how to put validation for certain empty textbox

How can i put validation for txtPName and txtAddress if they are empty i cannot proceed to submit and a messagebox will pop up.
private void btnSubmit_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO patientdb.addpatient(PatientName,MobileNumber,Occupation,Gender,Address,Age,PhoneNumber,MedicalHistory,ChiefComplaint) VALUES ('" + txtPName.Text + "','" + txtMNum.Text + "','" + txtOccup.Text + "','" + comboBox1.Text + "','" + txtAddress.Text + "','" + txtAge.Text + "','" + txtPNum.Text + "','" + rtbMHistory.Text + "','" + rtbCC.Text + "')";
con.Open();
MySqlCommand command = new MySqlCommand(insertQuery, con);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Data Inserted");
txtPName.Text = "";
txtMNum.Text = "";
txtPNum.Text = "";
txtAddress.Text = "";
txtAge.Text = "";
txtOccup.Text = "";
rtbMHistory.Text = "";
rtbCC.Text = "";
comboBox1.Text = " ";
}
else
{
MessageBox.Show("Data Not Inserted");
}
}
You can add a validation check before executing the rest of the code. Calling return will immediately leave the method after validation fails.
private void btnSubmit_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtPName.Text) || string.IsNullOrEmpty(txtAddress.Text))
{
MessageBox.Show("Missing Data");
return;
}
// Your code here...

Array of Background Worker to Read Tcpclient continuously

We have developed Window service in C# to read data using TcpClient with the help of background worker. Here, we are reading data from multiple IP's so using array of background worker to achieve this. Our service works perfectly fine but after few hours one of thread stops running. For Here i am pasting functions which is related to this problem.
Calling sequence
1. StartMonitoring
2. Dowork
Assuming two rows are coming from database so two background worker objects are creating which will call backgroundWorkerFiles_DoWork function.
In backgroundWorkerFiles_DoWork function the int i = (int)e.Argument; first comes 0 then 1 and according to 0 and 1 they connect there IP with its port. But after some time i always comes 1 not 0. Intially both runs but one thread stop running and always gives 1 to connect the IP not 0.
Kindly help us out from this problem. i am also trying. I can paste complete code also if you want.
public static string SERVICE_TIMER =Convert.ToString(ConfigurationSettings.AppSettings["SERVICE_TIMER"]);
public static int READING_TIMER = Convert.ToInt32(ConfigurationSettings.AppSettings["READING_TIMER"]);
public static string PLANT = Convert.ToString(ConfigurationSettings.AppSettings["PLANT"]);
public static string FAMILY = Convert.ToString(ConfigurationSettings.AppSettings["FAMILY"]);
public static BackgroundWorker[] BackgroundWorker_Controllers = new BackgroundWorker[maxThreads];
public static TcpClient[] tcpClientRead = new TcpClient[maxThreads];
public static TcpClient[] tcpClientWrite = new TcpClient[maxThreads];
public CONTROLLERS[] listObj = new CONTROLLERS[maxThreads];
public Thread _thread;
private void startMonitoring()
{
//while (true)
//{`enter code here`
try
{
CHECK:
WriteLog("startsMonitoring");
Thread.Sleep(1000 * 20);
if (ReadSetting())
{
Microsoft.Win32.Registry.SetValue("HKEY_CURRENT_USER\\Control Panel\\International", "sShortDate", "dd-MMM-yyyy");
CreateTables();
query = "select * from XXES_CONTROLLERS where active='Y'";
DataTable dt = returnDataTable(query);
if (dt.Rows.Count > 0)
{
maxThreads = dt.Rows.Count;
if (maxThreads > 0)
{
BackgroundWorker_Controllers = new BackgroundWorker[maxThreads];
tcpClientRead = new TcpClient[maxThreads];
tcpClientWrite = new TcpClient[maxThreads];
listObj = new CONTROLLERS[maxThreads];
int Counter = 0;
foreach (DataRow dr in dt.Rows)
{
listObj[Counter] = new CONTROLLERS();
listObj[Counter].DID = Convert.ToString(dr["DID"]).Trim();
listObj[Counter].IP_ADDR = Convert.ToString(dr["IP_ADDR"]).Trim();
listObj[Counter].PORT = Convert.ToString(dr["PORT"]).Trim();
listObj[Counter].STAGE = Convert.ToString(dr["STAGE"]).Trim();
listObj[Counter].INPUT_MODE = Convert.ToString(dr["INPUT_MODE"]).Trim();
listObj[Counter].READING_TYPE = Convert.ToString(dr["READING_TYPE"]).Trim();
Counter++;
}
for (int f = 0; f < maxThreads; f++)
{
BackgroundWorker_Controllers[f] = new BackgroundWorker();
BackgroundWorker_Controllers[f].DoWork += new DoWorkEventHandler(backgroundWorkerFiles_DoWork);
BackgroundWorker_Controllers[f].RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorkerFiles_RunWorkerCompleted);
//BackgroundWorker_Controllers[f].ProgressChanged +=
// new ProgressChangedEventHandler(backgroundWorkerFiles_ProgressChanged);
//BackgroundWorker_Controllers[f].WorkerReportsProgress = true;
BackgroundWorker_Controllers[f].WorkerSupportsCancellation = false;
}
for (int threadNum = 0; threadNum < maxThreads; threadNum++)
{
if (!BackgroundWorker_Controllers[threadNum].IsBusy)
{
BackgroundWorker_Controllers[threadNum].RunWorkerAsync(threadNum);
}
}
}
}
}
else
{
goto CHECK;
}
}
catch (Exception ex)
{
ErrorLog("Module:startMonitoring: " + ex.Message.ToString());
}
finally { }
// }
}
private void backgroundWorkerFiles_DoWork(object sender, DoWorkEventArgs e)
{
string ip = ""; bool toggle = false; DateTime todaysdate = new DateTime();
try
{
BackgroundWorker sendingWorker = (BackgroundWorker)sender;//Capture the BackgroundWorker that fired the event
int i = (int)e.Argument;
#region Main
while (!sendingWorker.CancellationPending)
{
#region MainTry
try
{
try
{
StreamWriter sw = new StreamWriter(AppPath + "\\Live.txt");
sw.WriteLine(DateTime.Now);
sw.Close();
}
catch { }
finally { }
#region WhileLOOP
todaysdate = GetServerDateTime();
if (listObj[i].toggle == false)
{
try
{ if (tcpClientRead[i].Connected) tcpClientRead[i].Close(); }
catch { }
finally { }
tcpClientRead[i] = new System.Net.Sockets.TcpClient();
tcpClientRead[i].Connect(listObj[i].IP_ADDR, Convert.ToInt32(listObj[i].PORT));
}
//if (tcpClientRead[i].Connected)
if (isPinging(listObj[i].IP_ADDR) && tcpClientRead[i].Connected)
{
query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and data_type='ERROR'";
EXEC_QUERY(query);
listObj[i].toggle = true;
//NetworkStream myNetworkStream = tcpClientRead[i].GetStream();
listObj[i].myNetworkStream = tcpClientRead[i].GetStream();
if (listObj[i].myNetworkStream.CanRead)
{
byte[] myReadBuffer = new byte[1024];
// StringBuilder myCompleteMessage = new StringBuilder();
listObj[i].myCompleteMessage = new StringBuilder();
int numberOfBytesRead = 0;
// Incoming message may be larger than the buffer size.
while (listObj[i].myNetworkStream.DataAvailable)
{
listObj[i].myNetworkStream.Flush();
numberOfBytesRead = listObj[i].myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
listObj[i].myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
Thread.Sleep(READING_TIMER);
}
if (!string.IsNullOrEmpty(Convert.ToString(listObj[i].myCompleteMessage)))
{
query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and data_type='MSG'";
EXEC_QUERY(query);
//query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,SRLNO,STAGE,SCAN_DATE,DATA_TYPE) values('" + PLANT + "','" + FAMILY + "','" + Convert.ToString(listObj[i].myCompleteMessage) + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG')";
//EXEC_QUERY(query);
if (listObj[i].STAGE == "BP")
{
WriteLog("Before Paint : " + Convert.ToString(listObj[i].myCompleteMessage));
if (string.IsNullOrEmpty(BP_JOB) && Convert.ToString(listObj[i].myCompleteMessage).Length == 4)
BP_HOOK = Convert.ToString(listObj[i].myCompleteMessage).Trim();
if (string.IsNullOrEmpty(BP_JOB) && Convert.ToString(listObj[i].myCompleteMessage).Length != 4)
BP_JOB = Convert.ToString(listObj[i].myCompleteMessage).Trim();
}
if (listObj[i].STAGE == "AP")
{
WriteLog("After Paint : " + Convert.ToString(listObj[i].myCompleteMessage).Trim());
if (string.IsNullOrEmpty(AP_HOOK) && Convert.ToString(listObj[i].myCompleteMessage).Trim().Length == 4)
AP_HOOK = Convert.ToString(listObj[i].myCompleteMessage).Trim();
if (string.IsNullOrEmpty(AP_JOB) && Convert.ToString(listObj[i].myCompleteMessage).Trim().Length != 4)
AP_JOB = Convert.ToString(listObj[i].myCompleteMessage).Trim();
}
if (Convert.ToString(listObj[i].myCompleteMessage).Trim().Length == 4)
listObj[i].HOOK = Convert.ToString(listObj[i].myCompleteMessage).Trim();
else if (Convert.ToString(listObj[i].myCompleteMessage).Trim().Length > 4)
listObj[i].JOB = Convert.ToString(listObj[i].myCompleteMessage).Trim();
if (!string.IsNullOrEmpty(listObj[i].HOOK) && !string.IsNullOrEmpty(listObj[i].JOB) && listObj[i].STAGE.Trim() == "BP")
{
bool isCheck = false;
Data = "";
Data = get_Col_Value("select fcode_id || '#' || ITEM_CODE || '#' || final_label_date from XXES_JOB_STATUS where jobid='" + listObj[i].JOB.Trim() + "'"); // and final_label_date is null");
if (Data.Contains('#'))
{
listObj[i].fcode_id = Convert.ToString(Data.Split('#')[0]).Trim();
listObj[i].ITEM_CODE = Convert.ToString(Data.Split('#')[1]).Trim();
listObj[i].FINAL_DATE = Convert.ToString(Data.Split('#')[2]).Trim();
}
else
{
listObj[i].FINAL_DATE=listObj[i].fcode_id = listObj[i].ITEM_CODE = "";
}
if (string.IsNullOrEmpty(listObj[i].fcode_id))
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "JOB :" + listObj[i].JOB + " is not buckleup','" + listObj[i].JOB + "')";
EXEC_QUERY(query);
WriteLog("JOB :" + listObj[i].JOB + " is not buckleup");
}
else
{
if (!string.IsNullOrEmpty(listObj[i].FINAL_DATE))
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "Final sticker already taken for JOB :" + listObj[i].JOB + "','" + listObj[i].JOB + "')";
EXEC_QUERY(query);
isCheck = true;
WriteLog("Final sticker already taken for JOB :" + listObj[i].JOB + "");
}
else if (!string.IsNullOrEmpty(listObj[i].HOOK))
{
query = "select * from (select JOBID from XXES_CONTROLLERS_DATA where hook_no='" + listObj[i].HOOK.Trim() + "' order by ENTRY_DATE DESC) where rownum=1";
string jobid = get_Col_Value(query).Trim();
if (!string.IsNullOrEmpty(jobid))
{
if (CheckExits("select count(*) from XXES_JOB_STATUS where jobid='" + jobid + "' and plant_code='" + PLANT.Trim() + "' and family_code='" + FAMILY.Trim() + "' and final_label_date is null"))
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "JOB " + jobid + " already in paint shop on HOOK " + listObj[i].HOOK + "','" + listObj[i].JOB + "')";
if (EXEC_QUERY(query))
{
isCheck = true;
WriteLog("JOB " + jobid + " already working on HOOK " + listObj[i].HOOK + "");
}
}
}
}
if (isCheck == false)
{
query = "select count(*) from XXES_CONTROLLERS_DATA where JOBID='" + listObj[i].JOB.Trim() + "' and stage='" + listObj[i].STAGE.Trim() + "' and plant_code='" + PLANT.Trim().ToUpper() + "' and FAMILY_CODE='" + FAMILY.Trim() + "'";// and flag is null";
if (CheckExits(query))
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "JOB: " + listObj[i].JOB + " Already HOOKED UP','" + listObj[i].JOB + "')";
if (EXEC_QUERY(query))
{
WriteLog("JOB: " + listObj[i].JOB + " Already HOOKED UP");
}
}
else
{
query = #"insert into XXES_CONTROLLERS_DATA(PLANT_CODE,FAMILY_CODE,JOBID,HOOK_NO,STAGE,ENTRY_DATE,FCODE_ID,ITEM_CODE)
values('" + PLANT.Trim().ToUpper() + "','" + FAMILY.Trim().ToUpper() + "','" + listObj[i].JOB.Trim() + "','" + listObj[i].HOOK.Trim() + "','" + listObj[i].STAGE + "',SYSDATE,'" + listObj[i].fcode_id.Trim() + "','" + listObj[i].ITEM_CODE.Trim() + "')";
if (EXEC_QUERY(query))
{
WriteLog("Inserted= " + query);
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "LAST JOB: " + listObj[i].JOB + " HOOKED UP','" + listObj[i].JOB + "')";
if (EXEC_QUERY(query))
{
WriteLog("LAST JOB: " + listObj[i].JOB + " HOOKED UP");
}
}
}
}
}
listObj[i].FINAL_DATE=listObj[i].ITEM_CODE= listObj[i].fcode_id=listObj[i].JOB = listObj[i].HOOK = "";
}
else if (!string.IsNullOrEmpty(listObj[i].HOOK) && listObj[i].STAGE.Trim() == "AP")
{
string data = "";
data = get_Col_Value("select jobid || '#' || fcode_id || '#' || ITEM_CODE from XXES_CONTROLLERS_DATA where HOOK_NO='" + listObj[i].HOOK.Trim() + "' and stage='BP' and plant_code='" + PLANT.Trim().ToUpper() + "' and FAMILY_CODE='" + FAMILY.Trim() + "' and flag is null");
if (!string.IsNullOrEmpty(data) && data.Trim().Contains('#'))
{
listObj[i].JOB = data.Split('#')[0].Trim();
listObj[i].fcode_id = data.Split('#')[1].Trim();
listObj[i].ITEM_CODE = data.Split('#')[2].Trim();
query = #"insert into XXES_CONTROLLERS_DATA(PLANT_CODE,FAMILY_CODE,JOBID,HOOK_NO,STAGE,ENTRY_DATE,FCODE_ID,ITEM_CODE)
values('" + PLANT.Trim().ToUpper() + "','" + FAMILY.Trim().ToUpper() + "','" + listObj[i].JOB.Trim() + "','" + listObj[i].HOOK.Trim() + "','" + listObj[i].STAGE + "',SYSDATE,'" + listObj[i].fcode_id.Trim() + "','" + listObj[i].ITEM_CODE.Trim() + "')";
if (EXEC_QUERY(query))
{
query = "update XXES_CONTROLLERS_DATA set flag='Y' where HOOK_NO='" + listObj[i].HOOK.Trim() + "' and flag is null";
if (EXEC_QUERY(query))
{
WriteLog("Hook :" + listObj[i].HOOK + " Out from After Paint");
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','" + "LAST JOB: " + listObj[i].JOB + " HOOK DOWN','" + listObj[i].JOB + "')";
if (EXEC_QUERY(query))
{
WriteLog("LAST JOB: " + listObj[i].JOB + " HOOKED DOWN");
}
}
}
}
else
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','HookNo " + listObj[i].HOOK + " not found at before paint stage or already scanned','" + listObj[i].HOOK + "')";
EXEC_QUERY(query);
WriteLog("HookNo " + listObj[i].HOOK + " not found at before paint stage or already scanned");
}
listObj[i].JOB = listObj[i].HOOK = "";
}
else if (!string.IsNullOrEmpty(listObj[i].JOB) && listObj[i].STAGE.Trim() == "AP")
{
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1,srlno) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'MSG','Please scan valid Hook','" + listObj[i].JOB + "')";
EXEC_QUERY(query);
WriteLog("Please scan valid Hook");
listObj[i].JOB = listObj[i].HOOK = "";
}
}
}
}
else
{
listObj[i].toggle = false;
throw new SocketException(10060);
}
Thread.Sleep(Convert.ToInt32(SERVICE_TIMER) * 1000);
#endregion WhileLOOP
}
catch (SocketException ex)
{
#region ERROR
string error = "";
if (ex.ErrorCode.Equals(10060))
{
error = listObj[i].IP_ADDR + " not connected. Please check the network";
}
else
{
if (ex.Message.Length > 500)
error = ex.Message.Substring(0, 498);
else
error = ex.Message.ToString();
}
listObj[i].toggle = false;
query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and DATA_TYPE='ERROR'";
EXEC_QUERY(query);
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'ERROR','" + error.Trim() + "')";
EXEC_QUERY(query);
ErrorLog("Module:While Connecting Controller: " + ex.Message.ToString());
if (tcpClientRead[i].Connected)
tcpClientRead[i].Close();
#endregion ERROR
}
catch (Exception ex)
{
#region ERROR
string error = "";
if (ex.Message.Length > 500)
error = ex.Message.Substring(0, 498);
else
error = ex.Message.ToString();
error = listObj[i].STAGE + "=>" + error;
listObj[i].toggle = false;
query = "delete from XXES_LIVE_DATA where stage='" + listObj[i].STAGE.Trim() + "' and DATA_TYPE='ERROR'";
EXEC_QUERY(query);
query = #"insert into XXES_LIVE_DATA(PLANT_CODE,FAMILY_CODE,STAGE,SCAN_DATE,DATA_TYPE,REMARKS1) values('" + PLANT.Trim() + "','" + FAMILY + "','" + listObj[i].STAGE.Trim() + "',SYSDATE,'ERROR','" + error.Trim() + "')";
EXEC_QUERY(query);
ErrorLog("Module:While Connecting Controller: " + ex.Message.ToString());
#endregion ERROR
}
finally
{
// toggle = false;
//tcpClientRead[i].Close();
}
#endregion MainTry
//}
Thread.Sleep(Convert.ToInt32(SERVICE_TIMER) * 1000);
}
#endregion MAIN
}
catch (Exception ex)
{
ErrorLog("Module:DoWork: " + ex.Message.ToString());
}
finally { }
}
public static bool isPinging(string ip)
{
bool isPing = false;
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send(ip, 1000);
if (reply != null)
{
if (reply.Status.ToString().ToUpper() == "SUCCESS")
isPing = true;
else
isPing = false;
}
return isPing;
}
catch { return isPing; }
finally { }
}
//}
//private void backgroundWorkerFiles_ProgressChanged(object sender, ProgressChangedEventArgs e)
//{
// // Use this method to report progress to GUI
//}
private void backgroundWorkerFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
WriteLog("Worker Completed");
for (int i = 0; i < maxThreads; i++)//Start a for loop
{
if (tcpClientRead[i].Connected)
tcpClientRead[i].Close();
}
}
catch { }
finally { }
}
I have converted the background worker into TASK library. Now problem is solved thanks. Changed the following things:-
public static Task[] BackgroundWorker_Controllers = new Task[maxThreads]; //declration
//calling
for (int f = 0; f < maxThreads; f++)
{
var ii = f;
BackgroundWorker_Controllers[f] = new Task(() =>
{
ConnectControllers(ii, dt.Rows.Count); }, TaskCreationOptions.None);
BackgroundWorker_Controllers[f].Start();
}

Textbox value does not get updated in asp.net

I have some Textboxes in my page. I am getting values from Database in and updating Textboxes in my page load. I have a code to update values in database behind update button. the problem is that when I change the textbox value and click update button, the value in textbox is again the original one. It retains its value. My code is
protected void Page_Load(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["DocumentID"]);
Connection conn = new Connection();
string query = "SELECT * from Document where DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
SqlDataAdapter daexp = new SqlDataAdapter(sqlcom);
System.Data.DataTable dtexp = new System.Data.DataTable();
daexp.Fill(dtexp);
TextBox1.Text = dtexp.Rows[0][1].ToString();
TextBox3.Text = dtexp.Rows[0][2].ToString();
TextBox6.Text = dtexp.Rows[0][3].ToString();
TextBox4.Text = dtexp.Rows[0][4].ToString();
TextBox5.Text = dtexp.Rows[0][5].ToString();
TextBox7.Text = dtexp.Rows[0][6].ToString();
TextBox7.ReadOnly = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["DocumentID"].ToString());
if (FileUpload1.HasFile)
{
HttpPostedFile Image = FileUpload1.PostedFile;
string contentType = Image.ContentType;
if (contentType.Equals("application/octet-stream"))
{
contentType = "application/pdf";
}
else if (contentType.Equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
{
contentType = "application/msword";
}
int nFileLen = Image.ContentLength;
byte[] myData = new byte[nFileLen];
Image.InputStream.Read(myData, 0, nFileLen);
Connection con = new Connection();
con.conopen();
string query = "UPDATE Document SET Setup='" + TextBox1.Text + "', ReferenceNO='" + TextBox3.Text + "', DocumentDate='" + TextBox6.Text + "', Subject='" + TextBox4.Text + "', NameOfInitiator='" + TextBox5.Text + "', Document=#Doc, FolderID='" + DropDownList1.Text + "', DocTypeID='" + DropDownList4.Text + "', DirectorateID='" + DropDownList3.Text + "', OrganizationID='" + DropDownList2.Text + "' WHERE DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, con.conopen());
sqlcom.Parameters.AddWithValue("#Doc", myData);
sqlcom.ExecuteNonQuery();
Label12.Text = "Document Updated Successfully";
Label12.ForeColor = System.Drawing.Color.Green;
Label12.Visible = true;
Label12.Text = "Document Updated Successfully";
Label12.ForeColor = System.Drawing.Color.Green;
Label12.Visible = true;
}
else
{
Connection conn = new Connection();
string query = "UPDATE Document SET Setup='" + TextBox1.Text + "', ReferenceNO='" + TextBox3.Text + "', DocumentDate='" + TextBox6.Text + "', Subject='" + TextBox4.Text + "', NameOfInitiator='" + TextBox5.Text + "', FolderID='" + DropDownList1.Text + "', DocTypeID='" + DropDownList4.Text + "', DirectorateID='" + DropDownList3.Text + "', OrganizationID='" + DropDownList2.Text + "' WHERE DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
sqlcom.ExecuteNonQuery();
}
}
You are updating the values of Textboxes from database in your Page_Load. Every time page is posted back it gets values from database and sets in TextBoxes. You need to add a check and only update values and set to TextBoxes if page is loaded first time and not posted back. Like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//your code here...
}
}
I know: Order Event of asp.net PreInit -Init -InitComplete -PreLoad -LoadPage -Control events -LoadComplete -PreRender -SaveStateComplete -Render -Unload
Therefore , When u onckick button, Webpage will ispostback. after, call pageload -> EventButton. value of textbox change, because your pageload set value for textbox.
Edit code:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){
int id = Convert.ToInt32(Session["DocumentID"]);
Connection conn = new Connection();
string query = "SELECT * from Document where DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
SqlDataAdapter daexp = new SqlDataAdapter(sqlcom);
System.Data.DataTable dtexp = new System.Data.DataTable();
daexp.Fill(dtexp);
TextBox1.Text = dtexp.Rows[0][1].ToString();
TextBox3.Text = dtexp.Rows[0][2].ToString();
TextBox6.Text = dtexp.Rows[0][3].ToString();
TextBox4.Text = dtexp.Rows[0][4].ToString();
TextBox5.Text = dtexp.Rows[0][5].ToString();
TextBox7.Text = dtexp.Rows[0][6].ToString();
TextBox7.ReadOnly = true;
}
}
Try to refer to the value Attribute:
TextBox1.Attributes("value")

Categories