I am searching and posting a lot in this issue,but could not get the satisfactory answer.I wanted to make sure that whenever I am making a call to server the value of Textbox should be the one which is the most updated one.
But when I am making the call to server the old value of the textbox persists.I know it is something to do with the postback,but I am not getting the exact way to get the updated value of textbox in my .cs file.
Please tell me what are the necessary steps that I should take to always get the latest value of the textbox.
Here is my code which is not working:
protected void Page_Load(object sender, EventArgs e)
{
int contentID = Convert.ToInt32(Request.QueryString["contentid"]);
if (contentID != 0)
{
if (!this.IsPostBack)
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text="Inside not PostBack";
}
else
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text="Inside PostBack";
}
}
else
Response.Write("Invalid URL for article");
}
public void getContentBody(int contentID)
{
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select content from content where contentID='" + contentID + "'";
//Response.Write(str);
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = str;
dr = command1.ExecuteReader();
if (dr.Read())
{
content = dr[0].ToString();
}
}
catch (Exception ex)
{
Response.Write("Exception reading data" + ex);
}
finally
{
dr.Close();
mycon.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//string textboxvalue = Request.Form[TextBox1.UniqueID];
mycon.Open();
string query = "update content set content='" +TextBox1.Text + "' where contentID= '"+contentID +"'";
msg_lbl.Text = query;
try
{
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = query;
command1.ExecuteNonQuery();
msg_lbl.Text = "text" + TextBox1.Text;
}
catch (Exception ex)
{
msg_lbl.Text = "Exception in saving data" + ex;
}
finally
{
mycon.Close();
}
}
Here is my aspx page code:
<asp:TextBox ID="TextBox1" runat="server" Height="500px"
TextMode="MultiLine" Width="90%" AutoPostBack="True"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Delete post" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Save changes" />
<asp:Button ID="Button3" runat="server" Text="Cancel" />
</p>
Please also tell me the reason why it is not working and how I can make it work.
Thanks,
Amandeep
According to the ASP.NET's life cycle, Page_Load executes before Button2_Click, so you have to show your updated text in the Button2_Click:
protected void Page_Load(object sender, EventArgs e)
{
contentID = Convert.ToInt32(Request.QueryString["contentid"]);
if (contentID != 0)
{
if (!this.IsPostBack)
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text = "Inside not PostBack";
}
}
else
Response.Write("Invalid URL for article");
}
public void getContentBody(int contentID)
{
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select content from content where contentID='" + contentID + "'";
//Response.Write(str);
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = str;
dr = command1.ExecuteReader();
if (dr.Read())
{
content = dr[0].ToString();
}
}
catch (Exception ex)
{
Response.Write("Exception reading data" + ex);
}
finally
{
dr.Close();
mycon.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//string textboxvalue = Request.Form[TextBox1.UniqueID];
mycon.Open();
string query = "update content set content='" + TextBox1.Text + "' where contentID= '" + contentID + "'";
msg_lbl.Text = query;
try
{
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = query;
command1.ExecuteNonQuery();
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text = "text" + TextBox1.Text;
}
catch (Exception ex)
{
msg_lbl.Text = "Exception in saving data" + ex;
}
finally
{
mycon.Close();
}
}
Related
i have created a dynamic list of employee user_ids by retrieving them from database and all of them are links or are created using anchor tags.i have assigned ids to them and also onServerClick events.but on the click of any link,the corresponding onServerClick function is not getting executed.
so help.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{int id = 0;
StringBuilder htmltable = new StringBuilder();
OracleConnection con = new OracleConnection(oradb);
OracleCommand cmd = new OracleCommand();
cmd.CommandText = "select USER_ID from Employee";
cmd.Connection = con;
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
try
{
if (dr.HasRows)
{
htmltable.Append("<table style='width:100%'>");
htmltable.Append("<tr><td style='text-align:center'><h3>USER ID</h3></td></tr>");
while (dr.Read())
{
htmltable.Append("<tr>");
htmltable.Append("<td style='text-align:center'>" + "<a href='' id = '" + (id++) + "' style='text-decoration:none;' runat='server' onServerClick='determine_id_Click'>" + dr["USER_ID"].ToString() + "</a>" + "</td>");
// htmltable.Append("<td>" + dr["TEAM"].ToString() + "</td>");
htmltable.Append("</tr>");
}
htmltable.Append("</table>");
PlaceHolder1.Controls.Add(new Literal { Text = htmltable.ToString() });
}
else
{
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
con.Close();
}
}
}
protected void determine_id_Click(object sender, EventArgs e)
{
//string id = (sender as Control).ClientID;
//Response.Write("<script>alert(id)</script>");
Response.Write("Hi");
}
When content is rendered like you are doing, it's rendered on the client. Hyperlinks like that are processed on the server, and the onserverclick is converted to a client-side event call to either __doPostBack or WebForm_PostBackWithOptions, which causes the server-side postback. You can generate this yourself by adding onclick and calling. Page.ClientScript.GetPostBackEventReference.
I have a link button as follow
<asp:LinkButton ID="LinkButtonSearchClient" PostBackUrl="~/UI/clients.aspx" runat="server">Recherche </asp:LinkButton>
i want get a query string from it
<asp:LinkButton ID="LinkButtonSearchClient" PostBackUrl="~/UI/clients.aspx?id=12" runat="server">Recherche </asp:LinkButton>
and the id value comes from the source code
public string ID
{
get { return ViewState["id"]; }
}
To get the value on page load (in the backend .cs file) :
protected void Page_Load(object sender, EventArgs e)
{
var id = Request.QueryString["id"];
if (id != null)
{
// use id
}
}
Or you might want to put the id into the link (in the html) :
<asp:LinkButton ID="LinkButtonSearchClient" runat="server"
NavigateUrl='<%# String.Format("~/UI/clients.aspx?id={0}", Eval("ID"))%>'
Text='Recherche'></asp:LinkButton>
You probably do not need a postback, look here : PostbackUrl vs NavigateUrl
Try this,
public string ID
{
get { Request.QueryString["id"]; }
}
Edit : In your page load set your postback url like this, access postbackurl in server side
LinkButtonSearchClient.PostBackUrl = "~/UI/clients.aspx?id=" + this.ID;
See my following example :
in design as follow
<asp:HyperLink ID="HLink" runat="server"
NavigateUrl='<%#"Mobiles_Details.aspx?ID=" + Eval("ID") %>' Text='<%#
Bind("Name") %>' Height="70px" Width="200px" Font-Bold="true" Font-
Size="10pt" Font-Names="Times New Roman" />
In coding the class Mobiles_Details is:
public partial class Mobiles_Details : System.Web.UI.Page
{
public string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
Session["UserID"] = "100";
//int ID = 102;
int ID = Convert.ToInt32(Request.QueryString["ID"].ToString());
Session["Product_ID"] = ID;
if (Session["UserID"] == null || Session["UserID"].ToString() == string.Empty)
{
Response.Redirect("Login.aspx", false);
}
else
{
if (ID != null)
{
DataTable dt = Load_Items_ID(Convert.ToInt32(Session["UserID"].ToString()), ID);
lbl_Name.Text = dt.Rows[0]["Name"].ToString();
lbl_Price.Text = dt.Rows[0]["Price"].ToString();
lbl_Details.Text = dt.Rows[0]["Details"].ToString();
img_Product.ImageUrl = dt.Rows[0]["image"].ToString();
}
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('An Error has been occured ');" + ex.ToString(), true);
}
}
}
public DataTable Load_Items_ID(int UserID, int ID)
{
DataTable Returned_Value = new DataTable();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Products where UserID= " + UserID + " and Status='False' and ID =" + ID))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(Returned_Value);
}
}
}
}
return Returned_Value;
}
}
For data access layer:
Source:
public string insert_details(bisuness_object user_details)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tbl_rgsthome values(#firstname,#lastname,#emailid,#password,#address,#upload)", con);
try
{
cmd.Parameters.AddWithValue("#firstname", user_details.firstname_value);
cmd.Parameters.AddWithValue("#lastname", user_details.lastname_value);
cmd.Parameters.AddWithValue("#emailid", user_details.emailid_value);
cmd.Parameters.AddWithValue("#password", user_details.pass_value);
cmd.Parameters.AddWithValue("#address", user_details.addr_value);
cmd.Parameters.AddWithValue("#upload", user_details.fileupl_value);
//cmd.Parameters.AddWithValue("#imagepath", user_details.imgpth_value);
return cmd.ExecuteNonQuery().ToString();
}
catch (Exception show_error)
{
throw show_error;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
home.aspx:
public string getimage(object ob)
{
string img = #"/image/" + ob.ToString();
return img;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);
bisuness_object bo = new bisuness_object();
// cmd.Parameters.AddWithValue("#imagepath", ("#uploadimage") + filename);
bo.firstname_value = TextBox1.Text;
bo.lastname_value = TextBox2.Text;
bo.emailid_value = TextBox3.Text;
bo.pass_value = TextBox4.Text;
bo.addr_value = TextBox6.Text;
bo.fileupl_value = FileUpload1.FileName.ToString();
bisuness_layer bl = new bisuness_layer();
bind();
try
{
string result = bl.record_insert(bo);
}
catch (Exception info)
{
throw info;
}
finally
{
bo = null;
bl = null;
bind();
}
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox6.Text = "";
}
}
how to solve it.....please help me
i want to image in gridview
bind the image tag inside the gridview dynamically
by giving the path dynamically
<asp:Image ID="image" Style="width:100px; height:100px;" runat="server" ImageUrl='<%# "~/folder/subfolder/" + Eval("id") +"."+ Eval("imagetype") %>' />
and the method for binding the gridview
protected void GetDayoffer()
{
gridview1.DataSource = bl.method();
gridview1.DataBind();
}
hope this will help you or recovert the bytes into image again and bind it into gridview
I am facing a strange problem. Two of my textboxes in asp.net are showing the default text, but there is no default value is set not even in the .cs file.
Here is the the code for a textbox:
<tr>
<td>
<asp:TextBox ID="txtName" runat="server" ValidationGroup="reg" Height="32px" Width="155px"
Style="border: 1px solid #999; background-color: #eee; width: 250px; height: 25px"
type="text"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtName" Display="Dynamic"
ValidationGroup="reg" ErrorMessage="Please fill your name as your Id"></asp:RequiredFieldValidator>
</td>
</tr>
Code behind:
public partial class Registration : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["conn"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnRegister_Click(object sender, EventArgs e)
{
con.Open();
try
{
if (IsUsernameEmailExist())
{
Messagebox("Username/Email address already exists. Please try another");
return;
}
if (txtPassword.Text == txtConfirm.Text)
{
MySqlCommand cmd = new MySqlCommand("insert into MEMBERS (memberNAME,memberEMAIL,memberPASSWORD,memberPHONE,isACTIVE) values(#memberNAME,#memberEMAIL,#memberPASSWORD,#memberPHONE,#isACTIVE)", con);
cmd.Parameters.AddWithValue("#memberNAME", txtName.Text);
cmd.Parameters.AddWithValue("#memberEMAIL", txtEmail.Text);
cmd.Parameters.AddWithValue("#memberPASSWORD", txtPassword.Text);
cmd.Parameters.AddWithValue("#memberPHONE", txtPhone.Text);
cmd.Parameters.AddWithValue("#isACTIVE", Label1.Text);
cmd.ExecuteNonQuery();
Sendemail();
Clear();
Messagebox("User Register Successfully .Now check your mail verification link is sent to your mail. After verification you can access your account");
cmd.Dispose();
}
else
{
Messagebox("Passowrd Not Match");
}
}
catch
{
}
}
public void Sendemail()
{
string ActivationUrl;
try
{
MailMessage message = new MailMessage();
message.To.Add(txtEmail.Text);
message.Subject = "Verification Email";
ActivationUrl = Server.HtmlEncode("http://localhost:55655/WebSite2/Verification.aspx?memberID=" + GetUserID(txtEmail.Text));
message.Body = "<a href='" + ActivationUrl + "'>Click Here to verify your acount</a>";
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new
smtp.EnableSsl = true;
smtp.Send(message);
}
catch
{
}
}
private string GetUserID(string Email)
{
MySqlCommand cmd = new MySqlCommand("SELECT memberID FROM MEMBERS WHERE memberEMAIL=#memberEMAIL", con);
cmd.Parameters.AddWithValue("#memberEMAIL", txtEmail.Text);
string memberID = cmd.ExecuteScalar().ToString();
return memberID;
}
private bool IsUsernameEmailExist()
{
MySqlCommand cmd = new MySqlCommand("Select * from MEMBERS where memberNAME='" + txtName.Text + "' or memberEMAIL='" + txtEmail.Text + "'", con);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
}
private void Messagebox(string Message)
{
Label lblMessageBox = new Label();
lblMessageBox.Text =
"<script language='javascript'>" + Environment.NewLine +
"window.alert('" + Message + "')</script>";
Page.Controls.Add(lblMessageBox);
}
public void Clear()
{
txtName.Text = "";
txtEmail.Text = "";
txtPassword.Text = "";
txtConfirm.Text = "";
txtPhone.Text = "";
}
}
Please add one of the following two combinations to your code
//do not change whole form tag, just add the autocomplete part
<form autocomplete="off">
//....
</form>
OR
add this to your elements directly
<asp:TextBox id="yourid" runat="server" autocomplete="off">
</asp:TextBox>
I think it might just be good practice to call the Clear() method in your Page_Load() if (!Page.isPostBack) and might solve your problem?
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
I have some dynamically generated checklist-items. When user deletes them, confirmation box should appear. How can i do that ?
protected void btndelete_Click(object sender, EventArgs e)
{
try
{
string conn = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
con.Open();
check:
if (CheckBoxList1.SelectedItem != null)
{
foreach (ListItem l in CheckBoxList1.Items)
{
if (l.Selected)
{
SqlCommand cmd = new SqlCommand("Drop Table " + l, con);
cmd.ExecuteNonQuery();
Label4.ForeColor = Color.Red;
Label4.Text = " PaperSet Deleted successfully";
CheckBoxList1.Items.Remove(l);
papersetlist.Items.Remove(l);
Psetlist.Items.Remove(l);
goto check;
}
}
}
con.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is delete button event code.
You just need to write something like this
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"
OnClientClick="return confirm('Are you certain you want to delete this item?');">
</asp:LinkButton>