Two dropdownlists drop1, drop2 have separate selected index changed. Any dropdown, on selectedindexchanged, goes to another page. If we use back button in browser it goes back to our home page and one of dropdown will be selected position. If we change the other dropdown, it works only the first selected index changed in the coding section
How can we solve this problem?
code
protected void Page_Load(System.Object sender, System.EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
string zCenterId="0";
if(Request.QueryString["LCID"]!=null)
{
zCenterId = Request.QueryString["LCID"].ToString();
}
ManageActivityAdminUIController ObjCtrl = new ManageActivityAdminUIController();
List<ManageActivityAdminUIInfo> ObjInfo = ObjCtrl.GetActivityList(zCenterId );
drplistactivity.DataSource = ObjInfo;
drplistactivity.DataBind();
drplistactivity.DataSource = ObjInfo;
drplistactivity.DataTextField = "ActivityName";
drplistactivity.DataValueField = "ID";
drplistactivity.DataBind();
drplistactivity.Items.Insert(0, new ListItem("<--Select Activity-->", "0"));
ManageCoursesController ObjCtrl = new ManageCoursesController();
List<ManageCoursesInfo> ObjInfo = ObjCtrl.GetCourses(zCenterId );
drplistcourse.DataSource = ObjInfo;
drplistcourse.DataTextField = "CourseName";
drplistcourse.DataValueField = "ID";
drplistcourse.DataBind();
drplistcourse.Items.Insert(0, new ListItem("<--Select Course-->", "0"));
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void drplistactivity_SelectedIndexChanged(object sender, EventArgs e)
{
string url = ResolveClientUrl("~/Activity.aspx?ActivityId="+drplistactivity.SelectedItem.Value);
Response.Redirect(url);
}
protected void drplistcourse_SelectedIndexChanged(object sender, EventArgs e)
{
string url = ResolveClientUrl("~/Course.aspx?CourseId=" + drplistcourse.SelectedItem.Value);
Response.Redirect(url);
}
If ViewState is off (on the dropdown or any of its parents - all the way up to the page) then the event won't fire. (It should post back though...)
The problem seems to be caused by the caching of your page.
I'd say that your two events are triggered, but you can not see it because of redirect
You may disable caching of your form :
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
Response.Expires = -1;
or you may test the eventtarget inside your eventhandlers
protected void drplistcourse_SelectedIndexChanged(object sender, EventArgs e)
{
if(drplistcourse.UniqueID!=Request.Form["__EVENTTARGET"])
return;
string url = ResolveClientUrl("~/Course.aspx?CourseId=" + drplistcourse.SelectedItem.Value);
Response.Redirect(url);
}
Related
My problem is that when i display data in listview for first time then it show correctly but when i display data second time then listview does not update the data correctly. I have made a function for databinding with listview which i have called in pageLoad and some other method.
Can anyone please give me a solution about this ?
I have also uploaded my source code for more detail.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
protected void LoadDataIntoListView()
{
Users objQuery = new Users();
string adminID = "Here is my query to get the data from MS-SQL";
objQuery.ExecuteSql(str);
if (objQuery.RowCount > 0)
{
Title = "Row affected";
lstAppointments.Items.Clear();
lstAppointments.DataSource = objQuery.DefaultView;
lstAppointments.DataBind();
}
else
{
Title = "None Row affected";
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string caseID = (string)Session["caseID"];
//string updateQuery = "update Cases set sCaseStatus='cancel' where iCaseID= '" + caseID + "'";
Cases objCases = new Cases();
objCases.LoadByPrimaryKey(Convert.ToInt32(caseID));
if (String.Equals(objCases.SCaseStatus, "cancel"))
{
Page.Title = "No Update";
ModalPopupExtender1.Hide();
}
else
{
objCases.SCaseStatus = "cancel";
objCases.Save();
Page.Title = "No Update";
ModalPopupExtender1.Hide();
lstAppointments.Items.Clear();
LoadDataIntoListView();
}
}
Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
You are binding data in not Postback. That means it does not binds data when you postback to same page. If you want to bind that on every page load, call the function LoadDataIntoListView() in Page_Load
My issue is the page posts back but does not call the method.
Here is where I create the link Buttons inside the RenderProducts method
for (var counter = 1; counter <= numberOfPages; counter++)
{
var pagingLink = new LinkButton
{
Text = " " + counter.ToString(CultureInfo.InvariantCulture) + " ",
ID = "page" + counter
};
pagingLink.Attributes["runAt"] = "server";
pagingLink.Attributes["class"] = "paging-link";
pagingLink.Attributes.Add("AutoPostBack", "true");
pagingLink.Attributes.Add("AutoEventWireup", "true");
pagingLink.Click +=ChangePage;
paging.Controls.Add(pagingLink);
}
The method it is calling
public void ChangePage(object sender, EventArgs args)
{
// handle this particular case
RenderProducts(2);
}
For completeness below you will see on PostBack I prevent it's default action
protected void Page_Load(object sender, EventArgs e)
{
GetSideBar();
BuildRefineSearch();
PopulateList();
PerformSearch();
if(!IsPostBack )
{
RenderProducts(1);
}
}
I moved everything to the
override protected void OnInit(EventArgs e)
as this was a user control this solved my issue.
Thanks to Chandermani for getting me to think about when my event was firing.
I've created a simple ASPX page that lists records in a GridView. The records are a list of incidents and one of the columns is the ID of the person who reported the incident.
The initial page shows all records but I would like to provide a filter for the ReportedBy column. I've gotten this working by allowing the user to type in the ReportedByID in a textbox and then clicking on the submit button. This refreshes the page as expected with the filtered view.
The code for this page is as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;
if (int.TryParse(txtReportedById.Text, out reportedById) == false)
{
reportedById = 0;
}
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}
To make it more user friendly, I decided to add a dropdown box populated with the ReportedBy names for the user to select which would then be used to filter on upon clicking the submit button. The dropdown box has names as the display items but the values should still be set to the IDs.
The problem I have is that the ID number I get from the dropdown box always comes up as the first element of the list rather than the one the user selected at the time they clicked on the submit button.
The code for this page with this implementation is as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
DataAccessObj daObj = new DataAccessObj();
foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}
if (IsPostBack == false)
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;
if (combobox.SelectedItem != null)
{
if (int.TryParse(combobox.SelectedItem.Value, out reportedById) == false)
{
reportedById = 0;
}
}
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}
Any help would be gratefully appreciated. TIA
Keep in mind that with WebForms the Page_Load code is executed before the event handler code for the control which created the postback.
You have to populate the list in the section where postbacks flags are checked, just like you do with the grid.
if (IsPostBack == false){
//bind the combobox
}
Otherwise, on a postback, the list will re-populate and the selection will be gone.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataAccessObj daObj = new DataAccessObj();
foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
I have a pretty interesting dilemma that is giving me a hurricane of a headache. I've seen a similar question asked here, but the user posted no code, so it was unresolved. This is a asp.net, sql server, and c# app.
In my application, I use JavaScript to display dummy data in a TextBox to entertain the user while a long process is running. (please note, this is a project, not a professional app).
The problem is, once the app is done executing, the app (I believe) refreshes the page and clears the TextBox. I want to prevent this from happening and continue to display the text after the program is completed.
My question is, where in the following code is the page being refreshed? How can I re-code it to prevent the text from being cleared?
I know there is no issue with the JavaScript or the .aspx page. I have not set or programmed any property to clear the text. If anyone could shed light on the issue, I would greatly appreciate it. If you need more code from me please let me know. I will be very active on this page until it is resolved. Thanks again!
public partial class SendOrders : System.Web.UI.Page
{
protected enum EDIType
{
Notes,
Details
}
protected static string NextBatchNum = "1";
protected static string FileNamePrefix = "";
protected static string OverBatchLimitStr = "Batch file limit has been reached. No more batches can be processed today.";
protected void Page_Load(object sender, EventArgs e)
{
Initialize();
}
protected void Page_PreRender(object sender, EventArgs e)
{ }
protected void btnExit_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
protected void Button_Click(object sender, EventArgs e)
{
PutFTPButton.Enabled = false;
Thread.Sleep(3000);
Button btn = (Button)sender;
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
KaplanFTP.Transmit transmit = new KaplanFTP.Transmit();
if (btn.ID == PutFTPButton.ID)
{
DirectoryInfo dir = new DirectoryInfo(#"C:\Kaplan");
FileInfo[] BatchFiles = bf.GetBatchFiles(dir);
bool result = transmit.UploadBatchFilesToFTP(BatchFiles);
if (!result)
{
ErrorLabel.Text += KaplanFTP.errorMsg;
return;
}
bf.InsertBatchDataIntoDatabase("CTL");
bf.InsertBatchDataIntoDatabase("HDR");
bf.InsertBatchDataIntoDatabase("DET");
bf.InsertBatchDataIntoDatabase("NTS");
List<FileInfo> allfiles = BatchFiles.ToList<FileInfo>();
allfiles.AddRange(dir.GetFiles("*.txt"));
bf.MoveFiles(allfiles);
foreach (string order in bf.OrdersSent)
{
OrdersSentDiv.Controls.Add(new LiteralControl(order + "<br />"));
}
btnExit.Visible = true;
OrdersSentDiv.Visible = true;
OrdersInfoDiv.Visible = false;
SuccessLabel.Visible = true;
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
BatchesCreatedLbl.Text = int.Parse(NextBatchNum).ToString();
Thread.Sleep(20000);
if (KaplanFTP.errorMsg.Length != 0)
{
ErrorLabel.Visible = false;
SuccessLabel.Visible = true;
ErrorLabel.Text = KaplanFTP.errorMsg;
}
}
}
private void Initialize()
{
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
if (!IsPostBack)
{
FileNamePrefix = bf.FileNamePrefix;
NextBatchNum = bf.NextBatchNum;
BatchesCreatedLbl.Text = (int.Parse(NextBatchNum) - 1).ToString();
if (bf.CheckLocalForNewBatch() == true)
{
NoBatchesToProcessLbl.Visible = false;
BatchesToProcessLbl.Visible = true;
if (int.Parse(NextBatchNum) >= 50)
{
ErrorLabel.Text += ErrorLabel.Text + OverBatchLimitStr;
ErrorLabel.Visible = true;
PutFTPButton.Enabled = false;
}
else
{
bf.ReadyFilesForTransmission();
ErrorLabel.Visible = false;
PutFTPButton.Enabled = true;
List<string[]> detStream = bf.GetBatchStream("DET");
List<string[]> hdrStream = bf.GetBatchStream("HDR");
OrdersInfoDiv.Visible = true;
DataTable dt = new DataTable();
dt.Columns.Add("ORDER NUMBER");
dt.Columns.Add("LINE NUMBER");
dt.Columns.Add("ITEM NUMBER/ISBN");
dt.Columns.Add("DESCRIPTION");
dt.Columns.Add("QUANTITY");
dt.Columns.Add("SHIPPING");
Dictionary<string, string> orderShip = new Dictionary<string, string>();
foreach (string[] hdrItems in hdrStream)
{
orderShip.Add(hdrItems[0], hdrItems[2]);
}
foreach (string[] detItems in detStream)
{
List<string> detLineList = new List<string>(detItems);
detLineList.Add(orderShip[detItems[0]]);
detLineList.RemoveAt(13);
detLineList.RemoveAt(12);
detLineList.RemoveAt(11);
detLineList.RemoveAt(10);
detLineList.RemoveAt(9);
detLineList.RemoveAt(8);
detLineList.RemoveAt(7);
detLineList.RemoveAt(4);
detLineList.RemoveAt(2);
detLineList[1] = detLineList[1].TrimStart('0');
detLineList[4] = detLineList[4].TrimStart('0');
dt.Rows.Add(detLineList.ToArray());
}
BatchDetails.DataSource = dt;
BatchDetails.DataBind();
}
}
else
{
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
}
}
}
}
Yes. You will have to determine the state of your calculation and populate the control inside Page_Load in the case where IsPostBack is true:
protected void Page_Load(object sender, EventArgs e) {
if (IsPostBack) {
// re-populate javascript-fill UI
} else {
}
Initialize();
}
You can probably also move Initialize() into the else clause as well.
Since you are handling the button click server side (I'm assuming the problem is happening once the user clicks the button?) there has to be a postback to handle it.
You could try putting your button and label into an updatepanel control - it uses AJAX to refresh its contents.
See this page for more information on updatepanels.
In my page when I call searchBtn_Click the selectedvalue will be carried into the variable ind only if the selection hasnt changed. So if a User selects Automotive, then clicks the search button, and then they change the selection to Government, it will refresh the page and display Automotive, am I missing something in the postback or doing something wrong here?
protected void Page_Load(object sender, EventArgs e)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
protected void searchBtn_Click(object sender, EventArgs e)
{
string ind = IndustryDropDownList.SelectedValue;
Response.Redirect("Default.aspx?ind=" + ind);
}
Simply replace your code with this code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
}
You don't need to use Redirect and QueryString.
Use SelectedValue at Page_PreRender (In your sample clear Page_Load completely).
you better try this in search button click
but remember your dropdowndlist's value-member==display-member to do this.. i had the same problem and this is how i solved it.
string ind = IndustryDropDownList.Text.Tostring().Trim();
Response.Redirect("Default.aspx?ind=" + ind);
i knw this is not the best way but it did work for me..
You're not leveraging the ViewState of asp.net forms (good mentality for MVC 3 though). But since you are using asp.net, you should change your code to this:
The logic in your page load is not necessary, unless you want the user to set the industry as the enter the page. Since I assumed you do, I left some logic in there. It checks for postback because it doesn't need to execute after the initial page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack() && Request.QueryString["ind"] != null)
{
SetIndustry(Request.QueryString["ind"].ToString());
}
}
protected void SetIndustry(String industry)
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
You don't have to redirect the page, since Page_Load will be called every time the page posts back. With .NET, your controls remember their last values automatically.
protected void searchBtn_Click(object sender, EventArgs e)
{
SetIndustry(IndustryDropDownList.SelectedValue);
}