C# what the methods do - c#

protected void Page_Load(object sender, EventArgs e)
{
Panel1.Visible = True;
Panel2.Visible = false;
LoadQuestion(); // auto choose question from database and add into Panel1
LoadQuestion1(); // auto choose question from database and add into Panel2
}
When I start my program, my form automatically loads questions into my textbox and radio button list. I click link button2 to make my Panel1 visible = false and Panel2 visible = true to continue answering question. But after I clicked the link button 2 or 1, it will go back to the Page_Load() method and causes my questions keep on changing.

You should check if it's a postback. You want to execute this only on first load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
Panel1.Visible = True;
Panel2.Visible = false;
LoadQuestion(); // auto choose question from database and add into Panel1
LoadQuestion1(); // auto choose question from database and add into Panel2
}
}
Source

This is because the Load event happens every time the server processes a request to your page.
There are two kinds of request: initial page load (when you go to the URL) and postback (when you click a button). What you do in your Page_Load method is kinda initialization, so it should be done only initially, but not during the postback.
protected void Page_Load(object sender, EventArgs e)
{
if( !IsPostBack )
{
// The code here is called only once - during the initial load of the page
}
// While the code here is called every time the server processes a request
}

Try:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Panel1.Visible = True;
Panel2.Visible = false;
LoadQuestion(); // auto choose question from database and add into Panel1
LoadQuestion1(); // auto choose question from database and add into Panel2
}
}

Related

Click Event not fired in User Control when multiple instances are created

I've a user control with 2 labels and two textboxes. When the label is clicked the textbox's visible prop is set to true. Here's the code I've used:
private void label_Heading_Click(object sender, EventArgs e)
{
label_Heading.Visible = false;
textBox_Heading.Text = label_Heading.Text;
textBox_Heading.Visible = true;
textBox_Heading.Focus();
}
After the textbox lose focus, it's visible prop is set to false and the label is updated with the text. Code:
private void textBox_Heading_Leave(object sender, EventArgs e)
{
textBox_Heading.Visible = false;
if(textBox_Heading.Text != "")
label_Heading.Text = textBox_Heading.Text;
label_Heading.Visible = true;
}
The code to create user controls on click:
private void label1_Click(object sender, EventArgs e)
{
TaskCard _taskCard = new TaskCard(++TOTAL_ITEM_COUNT, PanelName);
panel_DeletedItem.Controls.Add(_taskCard);
panel_DeletedItem.Refresh();
}
These code work fine when a single user control of this type is added to a panel. But if I add more than one, the code works only for the first user control, but it wont work for the new ones, although the event is fired for every user control. What am I missing here? Please suggest.
If I add a mbox to this code, the mbox is displayed for any control, but the rest of the code won't work, except for the first one.
private void label_Heading_Click(object sender, EventArgs e)
{
MessageBox.Show("Test"); // this will display, but the rest of the code is not executed or changes are not visible, i.e., the teboxes are not displayed even if I click the labels
label_Heading.Visible = false;
textBox_Heading.Text = label_Heading.Text;
textBox_Heading.Visible = true;
textBox_Heading.Focus();
}

Check to call sql script from different page?

I have two pages - the first page has two buttons and clicking on either of them will run different SQL queries and transfer them to the second page in a GridView. Upon page load, I have two different IF statements: the first one will run the first query and second will run the second query. My question is - how would I do the check to see if that button was clicked?
Here is a sample of my code:
public partial class Page2: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (page1 button1 is clicked) //this is what I need help with
{
//run sql...
}
else if (page1 button2 is clicked) //this will be similar to the first
{
//run sql...
}
}
}
You could use a session state to store which button was clicked. So in the button event, just have
protected void button1_OnClikc(object sender, EventArgs e)
{
session["WhichButtonWasClicked"] = "Button1";
}
On the Page load of the next page you can read that session value.
If (Session["WhichButtonWasClicked"] == "Button1")
{
// Button 1 is clicked
}
else
{
//Button 2
}
Another option is to pass the button click information as a URL parameter. You could also store the information in a cookie, store it in a DB and retrieve it later. Lots of options!
You can use SESSIONS, when your button is pressed, you should assign a value to a Session variable, for example:
protected void button1_Click(object sender, EventArgs e){
Session["buttonPressed"] = "button1";
// your query and transfer code here
}
protected void button2_Click(object sender, EventArgs e){
Session["buttonPressed"] = "button2";
// your query and transfer code here
}
The session variable will keep the value through the pages, so then use a switch if you want
protected void Page_Load(object sender, EventArgs e)
{
switch (Session["buttonPressed"].ToString())
{
case "button1":
//Your code if the button1 was pressed
break;
case "button2":
//Your code if the button2 was pressed
break;
default:
//Your code if you have a default action/code
break;
}
}

How does the Post back get reset ?

Let me elaborate on this... I have the code below, there is a Page_Init (which I still don't understand why it fires more than once, but that is another story), and a Page_Load and I am checking for the "isPostBack" ... everything works great while I use my controls, radio button and drop down list, as well as Buttons; however, if I press the key, even accidentally, the "isPostBack" is reset to False. What am I doing wrong? Also, my AutoEventWireup="true".
Also, this is an .ascx file.
protected void Page_init(object sender, EventArgs e)
{
LoadPageText1();
paymntpnl1.Visible = true;
curbalpnl.Visible = false;
paymntpnl2.Visible = false;
paymntpnl3.Visible = false;
paymntpnlcc.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
LoadPageData();
getContractInfo();
step2lbl.BackColor = System.Drawing.Color.White;
nopmt = Convert.ToDecimal(numpmts.Text);
nopmt = nopmt * nopymts2;
sb.Clear();
sb.Append("$");
sb.Append(nopmt.ToString("#.00"));
nopymts.Text = sb.ToString();
ValidateCC();
chkNewCC();
bool crdcrd = credCard;
bool newcrd = nwCard;
if (!IsPostBack){
}
}
You're checking IsPostBack but you're still doing all the resetting before the check! And then the check makes no difference because it's an empty conditional block! You should be doing this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// All the initial setup that you don't want to do again goes here.
}
// All the stuff you want to do on first load AND PostBack goes here.
}
Make sure you understand how conditionals work.

Panel within another Panel

I have 2 panels. Each start at the same location.(Let's say 10,10) and have the same size.
I have 2 buttons. One shows the first panel and the other shows the second panel.
My code is:
private void button1_Click(object sender, EventArgs e)
{
panel1.Visible = true;
panel2.Visible = false;
}
private void button2_Click(object sender, EventArgs e)
{
panel1.Visible = false;
panel2.Visible = true;
}
When I press button one the the first panel shows up, but when click button 2 the second panel doesn't show up. The panel's visible properties are initially false..
What is wrong?
Make sure that Panel2 is not a child window of Panel1.

Button Submit calls Onload first!

I have a problem with a webform.
My Goal: Intially when a page is loading, it has to load every textbox empty. After filling the info and click submit, it has to get submitted(UpdatePaymentInfo())
Problem: Here, When the user fills the info and clicks Submit,it calls onload function even before the submit button and makes all text box empty.
Here is the code:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
string QueryStringupdatecreditcard1 = Request.QueryString.ToString();
if (String.Equals(QueryStringupdatecreditcard1, "tabID=B"))
{
divTitle.Visible = false;
trmain.Visible = false;
tdOrderSummary.Visible = false;
trCCandBilling.Visible = true;
trtest2.Visible = false;
divUpdatecreditcard.Visible = true;
trusecompaddress.Visible = false;
txtFirstName.Text = "";
txtLastName.Text = "";
txtAddress1.Text = "";
txtAddress2.Text = "";
txtCity.Text = "";
txtZip.Text = "";
txtCardNo.Text = "";
txtVccNumber.Text = "";
trAmountCharged.Visible = false;
}
}
protected void imgbtnSubmit_Click(object sender, ImageClickEventArgs e)
{
try
{
UpdatePaymentInfo();
}
}
Wrap the current contents of your OnLoad method in:
if (!Page.IsPostBack)
{
// Code in here will only be executed when the page is *not* being loaded by a postback
}
This is because, as per the ASP.NET Page Life Cyle, the things that you care about in this instance happen in this order:
Load - During load, if the current request is a postback, control
properties are loaded with information
recovered from view state and control
state.
Postback event handling - If the request is a postback, control event
handlers are called. After that, the
Validate method of all validator
controls is called, which sets the
IsValid property of individual
validator controls and of the page.
So what happens is (somewhat simplified):
You click the image button, triggering the postback.
The data from your form is loaded into your controls.
Your OnLoad method overwrites the values in the controls to clear them.
Your click handler is run, but because of step 3 it sees empty values.
As others have sort-of mentioned, it wouldn't necessarily be a bad thing to refactor your OnLoad method whilst you're doing this. At the moment you seem to have it doing two distinct things:
Clearing the text fields
Setting the visibility of fields
It might be worth separating this into one or two (depending on if the visibility setting and field clearing will be done independently) separate methods and adjusting your OnLoad method so it looks like this:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Page.IsInPostBack)
{
SetFieldVisibility();
ClearFields();
}
}
Page_Load always occurs.
See the documentation on the Page Lifecycle
What you need to do is check to see if the Page_Load is being triggered by a Postback.
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
///do stuff in here that you want to occur only on the first lad.
}
else
}
// code that you want to execute only if this IS a postback here.
{
}
// do stuff you want to do on Page_Load regardless of postback here.
}
You can use the IsPostBack property of the Page as follows:
protected override void OnLoad(EventArgs e) {
if (!Page.IsPostBack) {
EmptyTextBoxes();
}
}
Have you tried wrapping the form reset code in a check to see if the page is a postback?
if(!Page.IsPostback) {
// Do form reset here
}
You thought about using the IsPostBack page variable?
protected override void OnLoad(EventArgs e)
{
if(!IsPostBack){
//all your logic here.
}
}
if it's the case, you might use a databound control and set it to insert mode

Categories