Intercept button click on page load - c#

I need to write a code that can intercept a click of some button (asp button) than execute some code, and if a method return true, call the original click.
So the points are:
1- I don´t know how to save the original click.
2- Identify the button that was clicked.
Ex:
protected void Page_Load(object sender, EventArgs e)
{
var b = getButtonThatWasClicked();
var originalClick = b.Click;
if(callSomeMethod(b))
originalClick(null,null);
}
EDIT:
Ok managed to get the button who made the click doing this...Now i need to prevent the original Click to get called. The method bellow didn't worked. Even overriding the original click to a new Handler the old Handler got called and executed. I thing ASP.NET read it and make something like a call stack of events to get called.Even if the handler change the old still in the stack.
public void ButtonsTestMethod()
{
var listOfButtons = listaDeBotes.Where(b => b.CommandName != "");
foreach (var button in listOfButtons)
{
if (Request.Form[button.UniqueID] != null)
{
var buttonFromRequest = Request.Form[button.UniqueID];
if (buttonFromRequest == null)
continue;
if (button.CommandName != "xxx")
{
//validate things
//if(TemPermissao(Tela,GetAcaoDoBotao(botao.CommandName)))
//if(!canexecuteSomething())
button.Click += new EventHandler(defaultClick);
}
}
}
}
void defaultClick(object sender, EventArgs e)
{
//show error
}
protected void Page_Load(object sender, EventArgs e)
{
//other code
ButtonsTestMethod();
}
I don´t know if its possible but would appreciate some help =/
Thanks.

To get the control name, you can try the following in the page load:
protected void Page_Load(object sender, EventArgs e)
{
if( IsPostBack )
{
string senderControl = Request.Params["__EVENTTARGET"].ToString();
//senderControl will contain the name of the button/control responsible for PostBack
}
}

The first argument in the button click event handler is the sender. You can cast that sender as a Button object and then you should be able to identify which button that was based on that object. That way, you can eliminate having that function to figure out which is clicked.
void GreetingBtn_Click(Object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
if(clickedButton.Text == "bla")
{
//Do stuff
}
}

Related

Fire Menu Strip Item Click Event Dynamically in C# Windows Form

I have already added a menu strip controller and added click events for those menu items.
Ex:
private void mnuaddTestingBuyersForFigures_Click(object sender, EventArgs e)
{
frmAddTestingBuyersForFigure obj = new frmAddTestingBuyersForFigure();
objUserManagerBll.SetAccess(obj, User.UserID);
IsAlreadyLoded(obj);
}
private void mnuOperatorIncentive_Click(object sender, EventArgs e)
{
frmOperatorIncentive obj = new frmOperatorIncentive();
objUserManagerBll.SetAccess(obj, User.UserID);
IsAlreadyLoded(obj);
}
private void mnuSetUpIncentiveMonthProcess_Click(object sender, EventArgs e)
{
frmSetUpWeeksForIncentiveMonth obj = new frmSetUpWeeksForIncentiveMonth();
objUserManagerBll.SetAccess(obj, User.UserID);
IsAlreadyLoded(obj);
}
Here I want fire above click event from another event. I just want to pass the menu strip name as parameter to the method and fire corresponding event of it.
Ex :
ShowMe("mnuSetUpIncentiveMonthProcess");
//Out put open the frmSetUpWeeksForIncentiveMonth form
ShowMe("mnuOperatorIncentive");
//Out put open the frmOperatorIncentive form
Without using conditional statements
You can find the control by its name and then call its PerformClick() method:
private void ShowMe(string name)
{
var item = (MenuStripItem)this.Controls[name];
item.PerformClick();
}

Why textbox click event not firing

I have a textbox and it's readonly. When I click on I want it to call my button click event:
private void tbFile_Click(object sender, EventArgs e)
{
//btnBrowse_Click(sender, e);
MessageBox.Show("test");
}
When click on the textbox, nothing happens. How do I fix it?
Update:
private void btnBrowse_Click(object sender, EventArgs e)
{
openFile();
}
private void tbFile_Click(object sender, EventArgs e)
{
//btnBrowse_Click(sender, e);
if (tbFile.Text != "")
{
openFile();
}
}
public void openFile()
{
var FD = new System.Windows.Forms.OpenFileDialog();
FD.Filter = "DBF Files|*.DBF";
FD.InitialDirectory = #"C:\";
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileToOpen = FD.FileName;
tbFile.Text = fileToOpen;
}
}
When I hit browse button and select a file, the browse file window comes up again. So it's appearing twice now and the textbox click is still not working.
There is no reason that can be inferred from the information you provided why you shouldn't trigger the openFile() method when you click on the tbFile control.
The fact that the textbox is set to readonly does not stop it from raising the click event in any way.
The only possibility is that the method is not assigned to the click event of the control.
Make sure in the event properties of the control that the click event is indeed assigned to the "tbFile_Click" method.
Just because there exsits a method that's called the same as a control but has "_Click" added does not make it get executed unless you specifically tell c# you want to associate that method with the click event of the control.
When you assign the method through the event window, C# generates a code file behind the scenes that adds the callback to that specific event.
You should use the btnBrowse.PerformClick() method to simulate a user click, instead of calling the handler.
The default I got from VS 2013 was a 'MouseClick' function so this works:
private void btnBrowse_Click(object sender, EventArgs e)
{
MyAwesomeFunction(sender);
}
private void tbFile_MouseClick(object sender, MouseEventArgs e)
{
MyAwesomeFunction(sender);
}
private void MyAwesomeFunction(object sender)
{
MessageBox.Show("test");
}

Can't call Click Event on dynamic button

I want to create a method in code behind that creates a button and places it in a PlaceHolder. I want this button to have a Click event.
After calling the "test" method button is placed correctly but the click event is not called.
private void test()
{
Button linkBtn1 = new Button();
linkBtn1.Text = "linkBtn1";
linkBtn1.OnClientClick = "return false;";
linkBtn1.Click += new EventHandler(linkBtn1_Click);
PagesPlaceHolder.Controls.Add(linkBtn1);
}
void linkBtn1_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
Removing the OnClientClick = "return false;" is necessary but not sufficient to get this to work. If you want the event handler on the dynamically added button to be triggered, you'll need to add this button every time the page loads.
One simple way would be to save the fact that the button has been added in ViewState, and then check that on PageLoad, and re-add the button if needed.
Here's a sample that works for me (and throws the exception when clicked)
protected void Page_Load(object sender, EventArgs e)
{
//if the button was added previously, add it again
if (ViewState["Added"] != null && (bool)ViewState["Added"])
addButton();
}
//this is the method that adds the button
protected void add_Click(object sender, EventArgs e) {
ViewState["Added"] = true;
addButton();
}
private void addButton() {
Button linkBtn1 = new Button();
linkBtn1.Text = "linkBtn1";
linkBtn1.Click += new EventHandler(linkBtn1_Click);
placeholder1.Controls.Add(linkBtn1);
}
void linkBtn1_Click(object sender, EventArgs e) {
throw new Exception("Button Click Event Triggered. Hello yellow screen!!!");
}
As #oleksii points out, have the clientside code is returning false so the form never gets submitted. You need to comment this out, then your event handler should fire.

Calling page event when ASP.NET user control event is invoked

Suppose there is a user control in a page called Paging.ascx that is embedded in PageWithResults.aspx. This control has the necessary properties to keep track of various details about what page you're on (ie: CurrentPage, TotalRecordsInResults, RecordsPerPage, etc..). It also contains events that fire off when you click on a hyperlink ("next page" or "previous page"). Example below. I need to tell PageWithResults.aspx that one of these LinkButton web controls was clicked. I think I need to assign a delegate in the page, so that when this user control event is called (hyperlink is clicked), it also calls some other method/event in the page class. That way I can quickly check what the new value of CurrentPage is (based on what was called in the event below) and get a new result set for the new page (based on the CurrentPage property). But I'm not sure of the best approach. I'm thinking this will require a delegate, but I'm not sure how to wire it up. If you need more details, please ask.
protected void btnNext_Click(object sender, EventArgs e)
{
this.CurrentPage = this.CurrentPage + 1;
if (OnPageChanged != null) OnPageChanged(this.CurrentPage);
}
I'm thinking I have to put my delegate here somewhere. ??
protected void btnNext_Click(object sender, EventArgs e)
{
this.CurrentPage = this.CurrentPage + 1;
if (OnPageChanged != null) OnPageChanged(this.CurrentPage);
//delegate to call object.method or something
}
Using an event would work fine.
You would create the event within your UserControl like so:
public event EventHandler ButtonClicked;
Then invoke the event when required:
protected void Button1_Click(object sender, EventArgs e)
{
if (ButtonClicked != null)
ButtonClicked(this, new EventArgs());
}
In your page you would need to assign an event handler:
protected void Page_Load(object sender, EventArgs e)
{
UserControl1.ButtonClicked += new EventHandler(UserControl1_ButtonClicked);
}
void UserControl1_ButtonClicked(object sender, EventArgs e)
{
}
As well as using the above approach you can also cast the Page reference in the UserControl and call a public method directly:
MyPage page = (MyPage)Page;
page.AMethod();
Hope this helps.

Determine source of event

I have a dropdown list and radio button. If something is selected from the dropdown by the user, I want the radio button cleared. If the radio button is selected I want the selection of the dropdown cleared. Unfortunately, this creates events that cancel each other out. I tried using the sender as shown below to determine if the value was being changed by code or by the user, but that doesn't work. How do I make these events only work if the user is the source of the action?
private void rbBlank_Checked(object sender, RoutedEventArgs e)
{
// Verify source of event
if (sender is RadioButton)
{
// Display
comboBoxTitles.SelectedIndex = -1;
}
}
private void comboBoxTitles_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
// Verify source of event
if (sender is ComboBox)
{
// Display
rbBlank.IsChecked = false;
}
}
You won't be able to tell the difference between the two since the source will be the same instance for both occasions.
This doesn't answer the question directly but if you compare the SelectedIndex of comboBoxTitles in the SelectionChanged event handler, your problem should be solved
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (comboBoxTitles.SelectedIndex != -1)
{
rbBlank.IsChecked = false;
}
}
Try to compare if sender == instance of a control instead of is type of.
private void rbBlank_Checked(object sender, RoutedEventArgs e)
{
// Verify source of event
if (sender == rbBlank)
{
// Display
comboBoxTitles.SelectedIndex = -1;
}
}
private void comboBoxTitles_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
// Verify source of event
if (sender == comboBoxTitles)
{
// Display
rbBlank.IsChecked = false;
}
}
If you know the IDs of those controls, you can try something like this:
System.Web.UI.WebControls.WebControl webControl = (System.Web.UI.WebControls.WebControl) sender;
if( webControl.ID == <comboboxId>)
{
//Do something
}
I havent tried this, but I guess it might work.

Categories