I am trying to clear two text fields after the data is posted. The page posts back but does not delete the text fields.
txtComment.Text = "";
txtEmail.Text = "";
How can I fix my code below.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["PicID"] != null)
{
int vPicID = Convert.ToInt32(Request.QueryString["PicID"]);
BSComments DTGetComments = new BSComments();
DataTable DTGetCommentsbyID = DTGetComments.GetCommentsByPicIDs(vPicID);
//Create User object
// GetMemberInfo GetMember = new GetMemberInfo();
// DataTable DAMemberInfo = GetMember.GetmemberInfo(UserID);
txtComment.Text = "";
txtEmail.Text = "";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//Check to see if the Email has an account
BSComments CheckIFmember = new BSComments();
DataTable DAMemberInfo = CheckIFmember.CheckIFMemberReturnNameEmail(txtEmail.Text);
int picid =Convert.ToInt32(Request.QueryString["PicID"]);
if (DAMemberInfo.Rows.Count > 0)
{
String myGuid = "";
String MemberName = "";
foreach (DataRow row in DAMemberInfo.Rows)
{
myGuid = row["Guid"].ToString();
MemberName = row["MemberName"].ToString();
}
BSComments InstertComments = new BSComments();
InstertComments.InserComment(picid, txtEmail.Text, txtComment.Text, MemberName, myGuid);
txtComment.Text = "";
txtEmail.Text = "";
}
else
{
txtComment.Text = "You need to have an account to post.";
}
txtComment.Text = "";
txtEmail.Text = "";
}
}
If you have stepped through your code to determine that the txtComment and txtEmail fields have actually had their .Text values set to String.Empty, then I'd suggest the problem may not be in your code at all.
Look to see if the browser is "helpfully" prefilling those fields for you. If so, you can add an attribute in your aspx file on those controls for AutoComplete="off"
For example:
<asp:TextBox runat="server" id="txtComment" AutoComplete="off" />
Related
I have a field named country in Invoice.aspx form. I have the below code.
invoice.aspx
<asp:DropDownList ID="lstCountryy" runat="server" Width="216px" Height="27px" AutoPostback="false">
</asp:DropDownList>
invoice.aspx.cs
lstCountryy.SelectedValue = dtInquiry.Rows[0]["country"].ToString();
Page load:
protected void Page_Load(object sender, EventArgs e)
{
txtTotal.Attributes.Add("readonly", "readonly");
txtvatt.Attributes.Add("readonly", "readonly");//added by chetan
txtDiscount.Attributes.Add("readonly", "readonly");//added by chetan
txtAmountInWords.Attributes.Add("readonly", "readonly");
if (!IsPostBack)
{
loadInvoiceDetails();
//SetAllCountries();//added by chetan
if (lstCountryy.SelectedValue == "U.A.E" || lstCountryy.SelectedValue == "BAHRAIN" || lstCountryy.SelectedValue == "SAUDI ARABIA")
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "float");
trdeclaration.Visible = false;
//txtvat.Enabled = true;
}
else
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "none");
trdeclaration.Visible = true;
}
}
}
Bind dropdownlist:
protected void SetAllCountries()
{
try
{
string queryStrUserType = "SELECT country_id,country_name FROM crm_countries";
ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
DataTable dt = clsDtResult.GetDataTable(queryStrUserType);
lstCountryy.DataSource = dt;
lstCountryy.DataValueField = "country_id";
lstCountryy.DataTextField = "country_name";
lstCountryy.DataBind();
lstCountryy.Items.Insert(0, "--Select--");
}
catch (Exception Ex)
{
}
}
dtInquiry is my Inquiry table in which country field is there and I am fetching the value from inquiry form to invoice form. I am not getting the selected value; it shows blank (""). I don't know what's wrong with that. I am a beginner in C#.
I was not getting the selected value.It should be like this: SetAllCountries Should be first and then loadinvoicedetails.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetAllCountries();
loadInvoiceDetails();
.....
.....
}
}
I have a dropdownlist that load all the list items from a text file, it contains a list of printer name,description,ipaddress and connection string id. so I display to the user the printer name-description and when the user selects the printer the values I pass is either the ip address or connection string depending on the situation.
protected void Page_Load(object sender, EventArgs e)
{
LoadPrinterList();
}
protected void LoadPrinterList()
{
string CSVFilePathName =
System.Configuration.ConfigurationManager.AppSettings["FilePath"];
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
//1st row must be column names;
//force lower case to ensure matching later on.
for (int i = 0; i < Cols; i++)
dt.Columns.Add(Fields[i].ToLower(), typeof(string));
dt.Columns.Add("nameanddescription",
typeof(string), "name +'-'+ description");
dt.Columns.Add("ipandconnectionstring",
typeof(string), "ip +'-'+ ConncetionStringID");
DataRow Row;
for (int i = 1; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
Row = dt.NewRow();
for (int f = 0; f < Cols; f++)
Row[f] = Fields[f];
dt.Rows.Add(Row);
}
string hostname = Request.UserHostName.Substring(0, 3);
string[] name = Printerlist.SelectedValue.Split('-');
//string plant = name[0].ToString();
//string plantvalue = plant.Substring(0, 3);
//if(hostname == plantvalue)
//{
Printerlist.DataTextField = "nameanddescription";
Printerlist.DataValueField = "ipandconnectionstring";
//}
Printerlist.DataSource = dt;
Printerlist.DataBind();
}
What the user sees first as an option for the printer list
when the user click the drop down they see this:
when drop down is clicked
so now the user selects a printer so selected index is > 0 so based on that I do the following in code behind.
protected void Printerlist_SelectedIndexChanged(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
else
{
if (Printerlist.SelectedItem.Text.Length > 0)
{
TxtItem.Focus();
}
else
{
TxtItem.Text = string.Empty;
TxtQty.Text = string.Empty;
DropDownList2.SelectedIndex = 0;
lbldesc.Visible = false;
//TxtBase.Text = string.Empty;
//TxtBase1.Text = string.Empty;
bestbeforewillbe.Text = string.Empty;
TxtBestBeforeMonths.Text = string.Empty;
TxtRotcode.Text = string.Empty;
zplcode.Text = string.Empty;
string message = "The selected printer is
not a local printer";
System.Text.StringBuilder sb =
new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock
(this.GetType(), "alert", sb.ToString());
}
}
}
this is the dropdownlist values in my aspx page
<asp:DropDownList ID="Printerlist" runat="server"
Height="16px" Width="268px" AutoPostBack="True" OnSelectedIndexChanged="Printerlist_SelectedIndexChanged" OnTextChanged="Printerlist_TextChanged" ViewStateMode="Enabled"></asp:DropDownList>
I have EnableViewState=true; but that didn't help either.
plese help I cant seem to figure out, every time the user selects a value there is a postback and after the postback "-" is selected as the printer value.
Simply check ISPOSTBACK on page load
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
LoadPrinterList();
}
You need to explicitly check if a PostBack occurred, otherwise any time that your Page_Load method is being triggered, it is repopulating your controls with their initial data (i.e. you are losing your changes there).
You simply need to add an if-statement and only execute your LoadPrinterList() method if it is an initial load :
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// Only perform this on the initial load
LoadPrinterList();
}
}
Additionally, you shouldn't need a similar check within your Printerlist_SelectedIndexChanged event as the event is going to be triggered from within the page (i.e. after it has already been loaded), so that statement should never evaluate as true.
how can i update image in listview in gridview formate using folder path in asp.net in c#?
protected void UpdateButton_Click(object sender, EventArgs e)
{
TextBox ApplicantIdTextBox = (TextBox)RadListView8.FindControl("ApplicantIdTextBox");
FileUpload photoTextBox = (FileUpload)RadListView8.FindControl("photoTextBox");
string fileName1 = Path.GetExtension(ApplicantIdTextBox + photoTextBox.FileName);
string fileSavePath = Server.MapPath("ImageStorage/" + fileName1);
tblPersonalInfo pi = new tblPersonalInfo();
pi.photo = fileName1;
photoTextBox.SaveAs(fileSavePath);
dbcontext.AddTotblPersonalInfoes(pi);
dbcontext.SaveChanges();
}
But it show me error...What can i do?
Server Error in '/HrPayRoll' Application.
Object reference not set to an instance of an object.
I'd rewrite it something like this and then run it in debug mode and see what line the error is on. You were trying to use applicantIdTextBox as a string, although I would have thought that would give a different error:
protected void UpdateButton_Click(object sender, EventArgs e)
{
TextBox applicantIdTextBox = RadListView8.FindControl("ApplicantIdTextBox") as TextBox;
FileUpload photoTextBox = RadListView8.FindControl("photoTextBox") as FileUpload;
if ((applicantIdTextBox != null) && (photoTextBox != null))
{
string fileName = Path.GetExtension(applicantIdTextBox.Text + photoTextBox.FileName);
string fileSavePath = Server.MapPath("ImageStorage/" + fileName);
tblPersonalInfo personalInfo = new tblPersonalInfo();
personalInfo.photo = fileName;
photoTextBox.SaveAs(fileSavePath);
dbcontext.AddTotblPersonalInfoes(personalInfo);
dbcontext.SaveChanges();
}
}
Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.
I have a web part for managing comments related to ongoing promotions. The web part is hosted in a Sandbox Solution because server access of all kinds is restricted (//sharepoint)
I have two main issues with my code.
1: Items submitted do not appear after postback, leaving user to think their comments was not saved,
2: PostBack data refires after page refresh, meaning if a user refreshes hoping to see their comments, it is re-submitted and saved.
What am I doing wrong here?
public string OfferID { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
OfferID = Context.Request.QueryString["ItemID"];
LoadOffers();
}
protected void LoadOffers()
{
if (!String.IsNullOrEmpty(OfferID))
{
PopulateOfferDetails(OfferID);
PopulateComments(OfferID);
PopulateBestPractices(OfferID);
}
else
{
OfferID = "123";
PopulateOfferDetails(OfferID);
PopulateComments(OfferID);
PopulateBestPractices(OfferID);
}
}
protected void PopulateComments(string offerID)
{
rcOiD.InnerText += " " + offerID;
List<Comment> Comments = new List<Comment>();
SPList TargetList = web.Lists.TryGetList("Offer Comments");
SPQuery query = new SPQuery();
query.RowLimit = 100;
query.Query = "<Where><Eq><FieldRef Name=\"OfferID\"/><Value Type=\"Text\">" + offerID + "</Value></Eq></Where>";
try
{
SPListItemCollection items = TargetList.GetItems(query);
if (items.Count > 0)
{
commentsCount.InnerText = items.Count.ToString();
SPUser user = web.CurrentUser;
string alias = user.Email.Substring(0, user.Email.IndexOf('#'));
string profilePicBase = "<div class=\"profilePic\" " + "style=\"background-image:url('http://who/Photos/XX.jpg');\"" + "> </div>";
foreach (SPListItem item in items)
{
Comment c = new Comment();
c.Author = ((string)item["Created By"]).CleanUserName();
c.Body = (string)item["Body"];
c.Date = String.Format("{0:MMM dd, yyyy}", (DateTime)item["Created"]);
c.ProfilePic = profilePicBase.Replace("XX", alias);
Comments.Add(c);
}
Comments.Reverse();
CommentRepeater.DataSource = Comments;
CommentRepeater.DataBind();
}
else
{
commentsCount.InnerText = "0";
}
}
catch (Exception ex)
{
}
}
protected void SubmitListItem(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
SPUser user = web.CurrentUser;
string alias = user.Email.Substring(0, user.Email.IndexOf('#'));
if (ListChoice.SelectedItem.Text == "comment")
{
SPList TargetList = web.Lists.TryGetList("Offer Comments");
SPListItem item = TargetList.Items.Add();
item["Title"] = TitleBox.Text;
item["Body"] = BodyBox.Text;
item["OfferID"] = OfferID;
item["Alias"] = alias;
item.SystemUpdate();
TargetList.Update();
}
else
{
SPList TargetList = web.Lists.TryGetList("Offer Best Practices");
SPListItem item = TargetList.Items.Add();
item["Title"] = TitleBox.Text;
item["Body"] = BodyBox.Text;
item["OfferID"] = OfferID;
item.SystemUpdate();
TargetList.Update();
}
}
}
EDIT: I can confirm this isn't a databind() issue. The item.count being pulled on postback is being rendered properly, but is still 1 item short.
I assume SubmitListItem is an event handler of an control on the page.
If that is so then as in your previous question, Page_Load is is fired before any control's event handler.
Therefore on postback your repeater is getting bound before the item addition occurs so on that load you do not get to see the new item.
To prevent this rebind the repeater after item addition.
I think you should do this only if not is page postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
OfferID = Context.Request.QueryString["ItemID"];
LoadOffers();
}
}