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")
Related
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...
I have a table called Phase it contains other columns and also an image column. All is working fine except that when i want to update the image it says " i cannot implicitly convert nvarchar to varbinary(max) and also when i want to update any one of the columns apart from the image it shows me the same error. Please help me out what am i doing wrong? Below is my aspx and aspx.cs codes respectively:
protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = e.RowIndex;
GridViewRow row = (GridViewRow)gv1.Rows[index];
Label eid = (Label)row.FindControl("lbleid");
TextBox date = (TextBox)row.FindControl("txtdate");
DropDownList ddl1 = (DropDownList)row.FindControl("ProjectID");
DropDownList ddl2 = (DropDownList)row.FindControl("ProjectTypeID");
DropDownList ddl3 = (DropDownList)row.FindControl("StateID");
DropDownList ddl4 = (DropDownList)row.FindControl("LGAID");
DropDownList ddl5 = (DropDownList)row.FindControl("CommunityID");
DropDownList ddl6 = (DropDownList)row.FindControl("CoyID");
FileUpload fu = (FileUpload)row.FindControl("fu1");
foreach (HttpPostedFile postedFile in fu.PostedFiles)
{
string filename = Path.GetFileName(postedFile.FileName);
string contentType = postedFile.ContentType;
using (Stream fs = postedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
SqlCommand cmd = new SqlCommand("update Phase set Photo = '" + fu.FileName + "' where Phase_1ID=" + Convert.ToInt32(eid.Text) + "", con);
con.Open();
int res = cmd.ExecuteNonQuery();
con.Close();
}
SqlCommand cmd1 = new SqlCommand("update Phase set DateOfVisit='" + date.Text + "', ProjectTitle='" + ddl1.Text + "', Type='" + ddl2.Text + "', StateName='" + ddl3.Text + "', LGName='" + ddl4.Text + "', CommunityName='" + ddl5.Text + "', CompanyName='" + ddl6.Text + "", con);
con.Open();
int res1 = cmd1.ExecuteNonQuery();
con.Close();
if (res1 == 1)
{
Response.Write("<script>alert('Updation done!')</script>");
}
gv1.EditIndex = -1;
gv1.DataBind();
}
}
}
}
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();
}
}
Here the save button in another form named Addwindow
The Datagrid in another form named Machine_List
I need the solution for,when i click on save button,the textbox values must stored in datagrid at the same time.
Here the below code for WPF C# am using but i cant get data.
private void SaveButton_Click(object sender, RoutedEventArgs e)//Save Button
{
Machine_List m = new Machine_List();//the datagrid present here Another form named Machine_List
if (this.Edit)
this.db.Datastore("UPDATE [databasename].[dbo].[Machinedup] SET [Name] = '" + textBox1.Text + "',[Type] = '" + comboBox1.SelectedItem + "',[AETitle] = '" + this.textBox2.Text + "',[IPAddress] = '" + textBox3.Text + "',[Port]='" + textBox4.Text + "' WHERE [ID] = '" + (string)(object)this.ID + "'");
else
this.db.Datastore("INSERT INTO [databasename].[dbo].[Machinedup] ([Name],[Type],[AETitle],[IPAddress],[Port]) VALUES('" + textBox1.Text + "','" + comboBox1.SelectedIndex.ToString() + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')");
this.Close();
DataTable dataTable = db.DataTab("SELECT [Name],[Type] AS Type,[AETitle] AS AET,[IPAddress] AS IP,[Port] AS PO FROM [databasename].[dbo].[Machinedup] WHERE ID ='" + (object)this.ID + "'");
DataRow row = dt.NewRow();
row[0] = textBox1.Text;
row[1] = textBox2.Text;
dt.Rows.Add(row);
m.dataGrid1.ItemsSource = dt.DefaultView;
}
if you're using different form/window. In your save button, all you have to do is to save your data.
private void SaveButton_Click(object sender, RoutedEventArgs e)//Save Button
{
this.db.Datastore("UPDATE [databasename].[dbo].[Machinedup] SET [Name] = '" + textBox1.Text + "',[Type] = '" + comboBox1.SelectedItem + "',[AETitle] = '" + this.textBox2.Text + "',[IPAddress] = '" + textBox3.Text + "',[Port]='" + textBox4.Text + "' WHERE [ID] = '" + (string)(object)this.ID + "'");
else
this.db.Datastore("INSERT INTO [databasename].[dbo].[Machinedup] ([Name],[Type],[AETitle],[IPAddress],[Port]) VALUES('" + textBox1.Text + "','" + comboBox1.SelectedIndex.ToString() + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')");
this.Close();
}
in the form where your datagrid is located, create a method that will refresh your datagrid
public void refreshgrid()
{
cmd = new SqlCommand("SELECT [Name],[Type] AS Type,[AETitle] AS AET, [IPAddress] AS IP,[Port] AS PO FROM [databasename].[dbo].[Machinedup] WHERE ID ='" + (object)this.ID + "'",conn);
da = new SqlDataAdapter(cmd);
dt = new DataTable("Machineup");
da.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
}
and in the window_loaded call the method.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
refreshgrid();
}
I am assigning the value to the variable from the text box on the page during the pageupload event of AjaxFileUpload1.The problem is that, I am not getting the value from the text box to my variable even though no error throws.My variables are
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
Any idea why AjaxFileUpload1_UploadComplete is not able to read text box value
My cs Code is:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
Please help me
I spent some time last week investigating this question but in the end couldn't find an easy solution for this. The OP in that question solved it by storing values in the Session but for this to work you would still need to cause a postback at some stage.
There apparently was functionality planned for the AjaxFileUpload control to pass values in the Context Keys collections but this was never implemented. This question describes how to implement this yourself though.
I think I saw another question around the same topic and the OP solved it by changing to using the AsyncFileUpload control but I stand to be corrected...
i think you need to add !Page.IsPostBack to your code. like this
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
if(!Page.IsPostBack)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
}