I want to get asp
button ID from previous page and I'm getting an exception.
Here is my code for C#
public partial class ADD_MOBILE : System.Web.UI.Page
{
string BUTN_ID;
protected void Page_Load(object sender, EventArgs e)
{
Button button = (Button)sender;
string BUTTON_CLICKER_ID = button.ID;
BUTN_ID = BUTTON_CLICKER_ID;
}
protected void saveMOBILE_Click(object sender, EventArgs e)
{
if(BUTN_ID == "samsung"){ ... }
}
}
I'm getting exception at this point Button button = (Button)sender;
why?
Okay, after going through your code it seems you want to get the button id so you can process some code based on that. Well, Let me make something clear, Page Load event will never give you the control that caused postback in sender object even if it gets triggered when you click a button and it posts back but it will NOT have the information in sender object for the control that posted it back.
For that you might want to use this approach from this James Johnson's answer to know which control caused postback:
/// <summary>
/// Retrieves the control that caused the postback.
/// </summary>
/// <param name="page"></param>
/// <returns></returns>
private Control GetControlThatCausedPostBack(Page page)
{
//initialize a control and set it to null
Control ctrl = null;
//get the event target name and find the control
string ctrlName = page.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(ctrlName))
ctrl = page.FindControl(ctrlName);
//return the control to the calling method
return ctrl;
}
This will return the Control
object that you can further dig more into.
Otherwise, the suitable and neat approach in your case would be to do it like this:
public partial class ADD_MOBILE : System.Web.UI.Page
{
string BUTN_ID; // I do not think it is necessary here.
protected void Page_Load(object sender, EventArgs e)
{
}
protected void saveMOBILE_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
if(button is null) return; // you can use == instead of keyword 'is'
if(button.ID.Equals("samsung"))
{
// DoStuff();
}
}
}
I hope you find it useful.