How to reference a user control in its own code behind? - asp.net

Let's say I have a user control with a couple of buttons. I'd like to know which one caused the postback, using this method:
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
And this is how I am calling it:
string btn = GetPostBackControl(this.Page).ID;
I'm getting the "Object reference not set to an instance of an object." I know now that the problem comes from the fact that I'm using this.Page, which represents the parent page.
How to reference the user control that I'm in? (not the parent page) So that it can work with the method to find the button that caused the postback?
Thanks for helping.
EDIT
Both buttons are located inside the user control. GetPostBackControl() is also in the code-behind of the user control.

I did a quick example on your given code and it worked out pretty fine. Perhaps you did miss checking for Page.IsPostBack? Obviously there will only be a postBackControl if there is a postBack...
#Buttons - they will be rendered as <input type="submit"> so they won't appear within ___EVENTTARGET. That's why Ryan Farlay wrote in his blog
However, you can still get to it, just in a different way. Since the
button (or input) is what causes the form to submit, it is added to
the items in the Form collection, along with all the other values from
the submitted form. [...] If you were to
look in the Form collection for anything that is a button then that
will be what caused the postback (assuming that it was a button that
caused the page to submit). If you first check the __EVENTTARGET, then
if that is blank look for a button in the Form collection then you
will find what caused the postback
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Control postBackControl = GetPostBackControl(this.Page);
Debug.WriteLine("PostBackControl is: " + postBackControl.ID);
}
}
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}

Related

Why ViewState and Control Values lost on partial Postback using AJAXFileUpload?

I have a .aspx page containing button which opens the popup on button click.
The popup window have AJAXFileUpload control. When button is clicked to open the popup, session values are sent to popup and on page load these session values are assigned to ViewState and HiddenField, DataTable.
Problem:
When i click on Upload button in popup containing AjaxFileUploadit saves the images to the table in AJAXUploadComplete event. In this event i am not able to access the ViewState,HiddenField and DataTable Values dont know why?
Popup.aspx.cs
DataTable dt=new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
int noOfImages;
string[] imagePaths;
if (dt != null && dt.Rows.Count==0)
{
dt.Columns.Add("QuoteID");
dt.Columns.Add("PrepID");
dt.Columns.Add("IsPrep");
dt.Rows.Add(string.Empty, string.Empty, string.Empty);
}
if ((!IsPostBack ))
{
if (Session["IsPrep"] != null || ViewState["IsPrep"]!= null)
{
int Isprep = Convert.ToInt32(Session["IsPrep"].ToString());
if (Session["IsPrep"] != null)
{
ViewState["IsPrep"] = Session["IsPrep"];
ViewState["QuoteID"] = Convert.ToString(Session["QuoteIDForListing"]);
int intQuoteID = Convert.ToInt32(ViewState["QuoteID"]);
hdnQuoteID.Value = intQuoteID.ToString();
ViewState["PrepID"] = Convert.ToString(Session["PrepIDForListing"]);
if (dt != null && dt.Rows.Count > 0)
{
dt.Rows[0]["QuoteID"] = Convert.ToString(Session["QuoteIDForListing"]);
dt.Rows[0]["PrepID"] = Convert.ToString(Session["PrepIDForListing"]);
dt.Rows[0]["IsPrep"] = Convert.ToString(Session["IsPrep"]);
}
Session["IsPrep"] = null;
Session["QuoteIDForListing"] = null;
Session["PrepIDForListing"] = null;
}
}
}
}
protected void AjaxFileUpload1_UploadComplete1(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
//here: ViewState,HiddenField,DataTable values are all get cleared dont know why?
if (dt != null && dt.Rows.Count > 0)
{
//here dt is set to null any idea?
}
//if (!string.IsNullOrEmpty(Convert.ToString(ViewState["QuoteID"])))
if (!string.IsNullOrEmpty(Convert.ToString(hdnQuoteID.Value))&& hdnIsPrepId.Value=="0")
{
int QuoteID = Convert.ToInt32(ViewState["QuoteID"]);
///some code here
}
// else if (!string.IsNullOrEmpty(Convert.ToString(ViewState["PrepID"])))
else if (!string.IsNullOrEmpty(Convert.ToString(hdnPrepID.Value)) && hdnIsPrepId.Value == "1")
{
int PrepID = Convert.ToInt32(ViewState["PrepID"]);
///some code here
}
}
NOTE: Same functionality works fine on a page. But, used with the popup it flushed all the values of HiddenField,DataTable,ViewState.
Session cant be used to store data after popup opened because multiple instance of windows may be opened at a time.
Also, when query string is used with Popup to send values the AjaxFileUpload gives error as it appends its own querystring contextkey and guid.
Please suggest any solution/change?

unable to capture ImageButton click in postback event

Unable to capture the Imagebuttonclick event in postback.
I am using the below code for Button click and tried for Imagebutton as well however "Button" click its working and not for Image button.
public Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if ((ctrlname != null) & ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
Any solution?
try using replacing your button check block with this:
if (c is System.Web.UI.WebControls.ImageButton)
{
control = c;
break;
}
Got the solution:
Added one more check in the above mentioned code,
// handle the ImageButton postbacks
if (control == null)
{
for (int i = 0; i < page.Request.Form.Count; i++)
{
if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y")))
{
control = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2));
}
}
}
And now I am able to capture the ImageButton postback event.
Thanks

Control caused the post back

I have a form that contains a dropdownlist,
on index changed method,i will call my user control class .cs with parameters choosen by the user, when im putting my code inside the index changed like the code below, it doesnt work, which is a normal behavior:
protected void ResourceTypesDDL_SelectedIndexChanged(object sender, EventArgs e)
{
....
MyUsercontrol c = new MyUSercontrol(....);
this.panel.controls.add(c);
}
thats why i have to put the code inside my onload method, but the thing is how can i know if it is the ddl that caused the post back? is there a propertie? or should i use page.Request.Params.Get("__EVENTTARGET") technic ?
Thanks alot !
If your MyUserControl is really user control, that means .ascx file, you should use this:
Page.LoadControl("~/Controls/MyUserControl.ascx")
instead of creating the instance of the control by calling constructor directly.
protected void ResourceTypesDDL_SelectedIndexChanged(object sender, EventArgs e) {
....
var c = Page.LoadControl("~/Controls/MyUserControl.ascx");
this.panel.controls.add(c);
}
EDIT:
But of course, after every other post back, you will lose this control. So you should also make sure that you will create all dynamic controls during OnLoad event.
set the property autoPostBack=true on the dropdownlist in order for the page to postback
Or use the below function to get the post back control on the page_load
private string GetPostBackControl()
{
string retVal = string.Empty;
try
{
string ctrlname = Page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
Control ctrl = this.Page.FindControl(ctrlname);
if (ctrl != null)
{
retVal = ctrl.ID;
}
}
}
catch (Exception ex) { ManageException(ex, ShowGeneralErrorMessage); }
return retVal;
}
Try setting AutoPostBack="True" property of drop down list. After setting this property when you select an item in list it will automatically do the postback and your event ResourceTypesDDL_SelectedIndexChanged will be fired.

Passing Value from textboxes in one webform to texboxes in another webform

am trying to get users to enter some details into a textbox in form1 and get the entry validated against the database. if the entry is correct, form2 loads with other texboxes including the one they made entries into. however i dont want them to make any changes to the textboxes they entered values into previously neither should they have to re-enter the values again.
how do i get the values in the textboxes to move from form1 to form2?
the code below shows what ive done with both forms but the second form dosent display the items in the textboxes when the form is loaded.
first form
protected void Button1_Click(object sender, EventArgs e)
{
string strConn;
strConn = "Provider=MIcrosoft.Jet.OLEDB.4.0;data Source=" +
Server.MapPath("App_Data/test.mdb");
OleDbConnection mDB = new OleDbConnection(strConn);
mDB.Open();
prodSnStr = pSnTextBox.Text;
purDate = Convert.ToDateTime(purDateTextBox.Text);
string dateStr = purDateTextBox.Text;
productClass aProduct = new productClass();
if (aProduct.Prods(mDB, prodSnStr, purDate))
{
Session["ProdSn"] = pSnTextBox.Text;
Session["PurDate"] = purDateTextBox.Text.ToString();
Response.Redirect("Warranty.aspx");
}
else
{
//error message
}
}
form two
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["ProdSn"] != "")
{
pSNoTextBox.Text = Request.QueryString["ProdSn"];
if (Request.QueryString["PurDate"] != "")
{
dateTextBox.Text = Request.QueryString["PurDate"];
}
else
{
//error message to display
}
}
else
{
//error message to display
}
}
eagaerly waiting for your responses..thanks..
In your code you are putting the values on one page into the session:
Session["ProdSn"] = pSnTextBox.Text;
Session["PurDate"] = purDateTextBox.Text.ToString();
However you are trying to read them out on the 2nd page from the Request collection:
if (Request.QueryString["ProdSn"] != "")
{
pSNoTextBox.Text = Request.QueryString["ProdSn"];
if (Request.QueryString["PurDate"] != "")
{
dateTextBox.Text = Request.QueryString["PurDate"];
}
This makes no sense. If you want to use the session, you must also get the values back out from the session object.
Personally I would look into Cross Page postbacks and Server.Transfer combined with Page.PreviousPage. Just make sure you don't set preserveForm parameter to false if using Server.Transfer.
You aren't passing your values as a query string. If you were your Response.Redirect would look like this:
Response.Redirect("Warranty.aspx?ProdSn=something&PurDate=something");
Instead since you are saving these values in a Session variable try this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["ProdSn"] != "")
{
pSNoTextBox.Text = Session["ProdSn"];
if (Session["PurDate"] != "")
{
dateTextBox.Text = Session["PurDate"];
}
else
{
//error message to display
}
}
else
{
//error message to display
}
}
In the button_click of the first form i entered this code
Session["ProdSn"] = pSnTextBox.Text;
Session["PurDate"] = purDateTextBox.Text.ToString();
Response.Redirect("Warranty.aspx?ProdSn=" + Server.UrlEncode(pSnTextBox.Text) +
"&PurDate=" + Server.UrlEncode(purDateTextBox.Text));
and then in the Page_load event of the second form i did this..
string value = Request["ProdSn"];
string value1 = Request["PurDate"];
pSnTextBox.Text = value;
purDateTextBox.Text = value1;
no hassle sustained....easy and perfectly working....
thank for ya'11 helping....
am very grateful
your asp.net page must post your data to second page.
just set your buttons PostBackUrl attribute.
<asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="target.aspx" />
I do not understand while you are making things complex.
When users clicks the button all data will be send to your target page.

How to Get Source of postback

if (Page.IsPostBack)
{
//here I need to know which control causes the postback
}
Thanks
See this posting
Get control name in Page_Load event which make the post back
Here is the code from link "marked as Answer"( Just pasting code here so that we can save readers time):
private string getPostBackControlName()
{
Control control = null;
//first we will check the "__EVENTTARGET" because if post back made by the controls
//which used "_doPostBack" function also available in Request.Form collection.
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
control = Page.FindControl(ctrlname);
}
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in Page.Request.Form.AllKeys)
{
c = Page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button ||
c is System.Web.UI.WebControls.ImageButton )
{
control = c;
break;
}
}
}
if (control == null)
return "";
else
return control.ID;
}

Resources