How to Get Source of postback - asp.net

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

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?

How to reference a user control in its own code behind?

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

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

How to find child gridview in user defined function

This is my code to save the selected check box values while paging, but as I am working with nested gridview I am unable to find the control of the required child gridview
private void SaveCheckedValues()
{
ArrayList userdetails = new ArrayList();
int index = -1;
GridView gv = (GridView)gvCustomers.FindControl("gvOrders"); // Is this correct or any other way of finding the child control
foreach (GridViewRow gvrow in gv.Rows)
{
index = (int)gv.DataKeys[gvrow.RowIndex].Value;
bool result = ((CheckBox)gvrow.FindControl("chkBoxChild")).Checked;
// Check in the Session
if (Session["CHECKED_ITEMS"] != null)
userdetails = (ArrayList)Session["CHECKED_ITEMS"];
if (result)
{
if (!userdetails.Contains(index))
userdetails.Add(index);
}
else
userdetails.Remove(index);
}
if (userdetails != null && userdetails.Count > 0)
Session["CHECKED_ITEMS"] = userdetails;
}
I have a generic recursive find control code that often helps in these circumstances. The issue with grid controls is that there is a certain level of nesting of controls int hem for the row and cell, and contents in the cell.
Private Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control
If root.ClientID Is Nothing AndAlso root.ClientID.EndsWith(id) Then
Return root
End If
For Each c As Control In root.Controls
Dim t As Control = FindControlRecursive(c, id)
If Not t Is Nothing Then
Return t
End If
Next c
Return Nothing
End Function
The code is in VB.net but you get the gist
private void SaveCheckedValues()
{
ArrayList userdetails = new ArrayList();
int index = -1;
foreach (GridViewRow gvRow1 in gvCustomers.Rows)
{
GridView gv = (GridView)gvRow1.FindControl("gvOrders");
foreach (GridViewRow gvrow in gv.Rows)
{
index = (int)gv.DataKeys[gvrow.RowIndex].Value;
bool result = ((CheckBox)gvrow.FindControl("chkBoxChild")).Checked;
// Check in the Session
if (Session["CHECKED_ITEMS"] != null)
userdetails = (ArrayList)Session["CHECKED_ITEMS"];
if (result)
{
if (!userdetails.Contains(index))
userdetails.Add(index);
}
else
userdetails.Remove(index);
}
}
if (userdetails != null && userdetails.Count > 0)
Session["CHECKED_ITEMS"] = userdetails;
}
try this:
private void SaveCheckedValues()
{
foreach(GridViewRow rIndex in GridView1.Rows)
{
GridView gv = new GridView();
gv = (GridView)row.FindControl("GridView2");
//user gv
}
}

Selected Index changed doesnt fire

I have a drop down list that is populated on page load and by default the selected index is 0 and its set to an emty string. On page load if we change the selected value the selected index method doesnt fire.
if(!page.isPostback)
{
this.ddl.DataSource = list;
this.ddl.DataValueField = "Id";
this.ddl.DataTextField = "Name";
this.ddl.DataBind();
this.ddl.Items.Insert(0, String.Empty);
if (Request.QueryString != null)
{
string name = Request.QueryString["name"];
long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault();
this.selectedIndex = 1;
this.ddl.SelectedValue = Id.ToString();
}
}
That's as it should be. If you want to execute some piece of logic from both the event and/or from page load, put that logic in a separate method so you can call it easily from your page load.
private void BindList()
{
this.ddl.Items.Clear();
this.ddl.DataSource = list;
this.ddl.DataValueField = "Id";
this.ddl.DataTextField = "Name";
this.ddl.DataBind();
this.ddl.Items.Insert(0, String.Empty);
this.ddl.Items.SelectedIndex = 0;
}
if(!page.isPostback)
{
BindList();
if (Request.QueryString != null)
{
string name = Request.QueryString["name"];
long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault();
this.ddl.Items.ClearSelection();
this.ddl.Items.FindByValue(Id.ToString()).Selected = true;
}
}

Resources