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();
}
Related
I've been looking for a solution for days now.
Currently have 2 Forms. Main Form has multiple buttons, lets say (1-10).
All buttons will open up my 2nd Form (say I press Button 4). On my 2nd Form I have a ComboBox with different names and a confirm button. When I choose a name from the ComboBox, then press the confirm button.
I want the name selected in the ComboBox to be displayed as the new button text from my Main form (So name3 from Form 2 ComboBox will replace Button text (Button 4) on Main Form).
Any suggestions on how I can achieve this?
I can get the text from ComboBox to Main Form into a Label or a Button of my choosing, but I can't do it from the pressed button on Main Form which opened Form 2.
I've tried changing the button pressed on Main Form to a buttonTemp name, then letting the text from ComboBox change buttonTemp text, but it's coming up as it doesn't exist on Form 2.
Form 1 code:
public void b1111_Click(object sender, EventArgs e)
{
b1111.BackColor = Color.Red;
buttonTemp.Name = "bTemp2";
b1111.Name = "buttonTemp";
Classroom f4 = new Classroom();
f4.Show();
}
this is on Form 2:
private void button1_Click(object sender, EventArgs e)
{
temp1 = comboBox1.Text;
// trying to figure out the label text
foreach (Term1 Form1 in Application.OpenForms.OfType<Term1>())
{
Form1.buttonTemp.Text = comboBox1.Text;
}
this.Close();
}
Do not operate on the controls of other forms. Instead operate with values.
In your case when you finished and closed Form2 you can return a value back to the Form1 and update button text with a returned value.
In Form2 create public property which will be populated before you close Form2.
public string SelectedName { get; set; }
private void selectNameButton_Click(object sender, EventArgs e)
{
SelectedName = comboBox1.Text;
this.Close();
}
In Form1 use .ShowDialog() method to display form in modal form
public void openForm2Button_Click(object sender, EventArgs e)
{
openForm2Button.BackColor = Color.Red;
using (var form = new Classroom())
{
form.ShowDialog();
// next line will be execute after form2 closed
openForm2Button.Text = form.SelectedName; // update button text
}
}
Suggested by #Enigmativity in the comments:
// Form 2
public string SelectedName => comboBox1.Text;
private void selectNameButton_Click(object sender, EventArgs e)
{
this.Close();
}
// Form 1 remains same
There is many ways to get your goal.
I hope you try to use event.
You can make your own event as below.
private void Form1_Load(object sender, EventArgs e)
{
//define listen event from custom event handler
_form2.OnUserSelectNewText += new Form2.TextChangeHappen(_form2_OnUserSelectNewText);
}
When you have member variable for remember which button clicked by user.
private Control activeControl = null;
and you can get text that user's choice from your custom event at Form2.
//to make simple code, centralize all buttons event to here.
private void button_Click(object sender, EventArgs e)
{
//to remeber which button is clicked.
activeControl = (Button)sender;
_form2.ShowDialog();
}
and then you just change text of "activeControl".
private void _form2_OnUserSelectNewText(string strText)
{
activeControl.Text = strText;
}
please refer this, how to make custom event with delegate.
public partial class Form2 : Form
{
//you can expand your own custom event, string strText can be Control, DataSet, etc
public delegate void TextChangeHappen(string strText); //my custom delegate
public event TextChangeHappen OnUserSelectNewText; //my custom event
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// to prevent null ref exception, if there is no event handler.
if (OnUserSelectNewText != null)
{
OnUserSelectNewText(this.comboBox1.Text);
}
this.Close();
}
}
I'm work on a project in Asp.net (C#), I've the following code (C#) that generate dynamically html buttons (for each item in my list) at run time:
In my .aspx file:
<div id="myDiv" runat="server" ...></div>
In my .aspx.cs file:
List<Item> list;
private void Display()
{
foreach (Item item in list)
AddButton(item);
}
private void AddButton(Item item)
{
HtmlButton button = new HtmlButton();
button.InnerText = item.Content;
button.ID = item.name;
button.ServerClick += new EventHandler(Item_Click);
myDiv.Controls.Add(button);
}
private void Item_Click(Object sender, EventArgs e)
{
// HERE I WANT TO DO SOMETHING ON THE SPECIFICALLY
// CLICKED BUTTON,
// THE PROBLEM IS THAT I CAN'T KNOW WHICH BUTTON OF
// THE DYNAMICALLY ADDED BUTTONS (BY THE AddButton()
// FUNCTION) IS CLICKED, NOTE: I HAVE MORE THAN 10 ITEMS IN
// list. I MEAN I CAN'T PASS THE CLICKED BUTTON AS A
// PARAMETER TO THIS Item_Click FUNCTION, IN GENERAL, WHAT I
// WANT IS SOMETHING LIKE:
// Item_Click(Object sender, EventArgs e, HtmlButton clickedButton)
// WITH SUCH DECLARATION OF Item_Click FUNCTION I CAN DO WHAT
// I WANT ON THE CLICKED BUTTON, BUT IT DOESN'T WORK THAT
// WAY, BECAUSE EventHandler's PARAMETERS ARE: Object,
// EventArgs, AND IT WOULD NOT HELP ME TO CREATE MY CUSTOM
// EVENTHANDLER BECAUSE HtmlButton.ServerClikc IS OF TYPE
// EventHandler.
}
Any suggestions?
Thanks for Help!
You must fill list in page_load without if(!IsPostBack)
void Page_Load(object sender, EventArgs e )
{
// don`t use if(!IsPostBack) because every postback your contols leave and you must register your controls.
list=new List<Item>();
list.Add(...);
list.Add(...);
list.Add(...);
}
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");
}
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
}
}
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.