Dynamically created LinkButton posts back but does not call onClick Method - c#

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.

Related

How to standardize many button events C#

Could you tell me how to put together the many button event.
Writing all the many button event is bad Maintainability.
So I want to turn many button event into one method.
Like this...
Before
private void button1_Click(object sender, EventArgs e)
{
//button1 event
}
private void button2_Click(object sender, EventArgs e)
{
//button2event
}
private void buttonN_Click(object sender, EventArgs e)
{
//buttonNevent
}
After
private void buttonClickEvent(object sender, EventArgs e)
{
Button btn = (Button)sender;
int index = int.Parse(btn.Name.Replace("button", ""));
if(index==1)
{
//button1 event
}
if(index==2)
{
//button2 event
}
}
In ASP.NET Web Forms I've solved this situation like this.
Define a general hidden button (this will be the trigger for all). You should define it "hidden" using the styles.
<asp:Button ID="btnPrintPdf" runat="server" Style="display: none" OnClick="btnPrint_Click" />
For the all other buttons "redirect" the click on the client side to the general one like this:
btnPrintPlan.OnClientClick = ClientScript.GetPostBackClientHyperlink(btnPrintPdf, itemData.ClientIw.ID.ToString() + "|" + ((int)PrintDocs.NextStepsPlan).ToString()) + ";return false;";
btnPrintNetWorth.OnClientClick = ClientScript.GetPostBackClientHyperlink(btnPrintPdf, itemData.ClientIw.ID.ToString() + "|" + ((int)PrintDocs.NetWorth).ToString()) + ";return false;";
As you can see, I use a Enum to define what I want to print by clicking different buttons.
The last part is to define the "general" button logic:
protected void btnPrint_Click(object sender, EventArgs e)
{
string sVal = Request.Params["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(sVal))
return;
string[] tks = sVal.Split('|');
if (tks.Length != 2)
return;
string sOrderId = tks[0];
string sPrintType = tks[1];
int orderId = 0;
int iPrintType = 0;
if (!int.TryParse(sOrderId, out orderId) || !int.TryParse(sPrintType, out iPrintType))
return;
string sPdf = null;
if (iPrintType == (int)PrintDocs.NextStepsPlan)
{
....
}//endif
if (iPrintType == (int)PrintDocs.NetWorth)
{
....
}//endif
You could try something like this. Dictionary would be better than if's if you have hundreds of buttons.
private Dictionary<string, Action<object, EventArgs>> buttonEventMap = new Dictionary<string, Action<object, EventArgs>>();
private void setup()
{
buttonEventMap["button1"] = (object sender, EventArgs e)=>{Console.WriteLine("Button 1 Clicked");};
// etc....
}
private void buttonClickEvent(object sender, EventArgs e)
{
Button btn = (Button)sender;
if( buttonEventMap.ContainsKey(btn.Name))
buttonEventMap[btn.Name](sender, e);
}
Although this still is't much different from just implementing each individual ButtonClickEvent.

dropdown list goes back to first value after selected index changes

I have a drop down list with a button event that should send it's value for a textbox.But,even if I choose a value that is not the first one in the DDL,it only sends the value of the first item in the DDL. I was told to add the !IsPostBack in the page load,but it didn't help.
Codes:
protected void Page_Load(object sender, EventArgs e)
{
string testeddl;
codProfessor = Request.QueryString["id"];
if (db.conecta())
{
ddlTeste.Items.Clear();
ddlTesteAltDel.Items.Clear();
ddlQuestoes.Items.Clear();
listaX = db.retornaTestes(codProfessor);
for (int i = 0; i < listaX.Count; i++)
{
testeddl = listaX[i].nometeste;
ddlTesteAltDel.Items.Add(testeddl);
}
protected void btnBuscarTeste_Click(object sender, EventArgs e)
{
if (db.conecta())
{
int posic = ddlTesteAltDel.SelectedIndex;
txtNomeTeste.Text = listaX[posic].nometeste;
ddlaltdelTeste.Text = listaX[posic].materiateste;
}
}
}
}
In Page_Load, just need to indicate:
if(!IsPostBack()
{
// rest of the code.
}

Session variables set - Page_Load method C#

I tried to link default1.aspx and default 2.aspx.
What I'm trying to do is to display calculated results in default1.aspx when clicking confirm button in default2.aspx.
I run the codes but it doesn't work really.
How can I fix this?
I wrote the codes in default1.aspx below:
protected void confirmBookingButton_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("RoomBookingMain.aspx");
Session["confirmBooking"] = "confirm";
Session["totalBooking"] = calculateTextBox.Text;
}
and then I wrote other codes in default2.aspx like:
public partial class RoomBookingMain : System.Web.UI.Page
{
static int nbBookingInt = 0;
static int totalRevenueInt = 0;
}
protected void Page_Load(object sender, EventArgs e)
{
bookingNbLabel.Text = nbBookingInt.ToString();
totRevenueLabel.Text = totalRevenueInt.ToString();
string confirmBooking = (string)(Session["confirmBooking"]);
if ((string)(Session["confirmBooking"]) == "confirm")
{
nbBookingInt += 1;
totalRevenueInt += int.Parse(Session["totalBooking"].ToString());
Session["confirmBooking"] = "no current booking";
}
}
Session["confirmBooking"] = "confirm";
Session["totalBooking"] = calculateTextBox.Text;
Response.Redirect("RoomBookingMain.aspx");
Assign Session before Response.Redirect(). Redirect method will stop the execution at that point.
If you need to pass the data only to next page and if no secure data is involved you can use QueryStrings.

Two dropdown in a page ( conflict )

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);
}

DropDownList SelectedValue doesn't Change

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);
}

Categories

Resources