How to handle different Events from different Controls in one method? - c#

I have a ListView SelectionChanged event and a DatePicker SelectedDateChanged event, both named "Changes".
private void Changes(object sender, SelectionChangedEventArgs e)
{
//Process selected Items from ListView an Date from DatePicker
}
So both events are handled using the same method, which is exactly what I want. However, if I try the same thing with a TextBox SelectionChanged event, Visual Studio creates a new event handler (probably because of the different types of the e argument?). Is it possible to call my Changes method when I write text in the TextBox?

You can assign any of methods as any event handler, via lambda expression:
listView1.SelectionChanged += Changes;
datePicker1.SelectedDateChanged += Changes;
textBox1.SelectionChanged += (sender, e) => Changes(sender, null);
If you are using SelectionChangedEventArgs inside of method, you will need to create it manually with needed data inside which may be harder than creating multiple handlers.

Related

what means "object sender, RoutedEventArgs e" in c#? [duplicate]

What do sender and eventArgs mean/refer to? How can I make use of them (for the scenario below)?
Scenario:
I'm trying to build a custom control with a delete function, and I want to be able to delete the control that was clicked on a page that contains many of the same custom control.
The sender is the control that the action is for (say OnClick, it's the button).
The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.
What Chris is saying is you can do this:
protected void someButton_Click (object sender, EventArgs ea)
{
Button someButton = sender as Button;
if(someButton != null)
{
someButton.Text = "I was clicked!";
}
}
sender refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.
EventArgs is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.
When you implement your own events, use an EventHandler or EventHandler<T> as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).
Manually cast the sender to the type of your custom control, and then use it to delete or disable etc. Eg, something like this:
private void myCustomControl_Click(object sender, EventArgs e)
{
((MyCustomControl)sender).DoWhatever();
}
The 'sender' is just the object that was actioned (eg clicked).
The event args is subclassed for more complex controls, eg a treeview, so that you can know more details about the event, eg exactly where they clicked.
'sender' is called object which has some action perform on some
control
'event' its having some information about control which has
some behavoiur and identity perform
by some user.when action will
generate by occuring for event add
it keep within array is called event
agrs
FYI, sender and e are not specific to ASP.NET or to C#. See Events (C# Programming Guide) and Events in Visual Basic.

Fire an event within another event

I need help on firing an event within C#
Basically I have a onclick event that fires when you click on a checkbox
void OnClick(object sender, RoutedEventArgs e)
{
...
}
I need help on firing an event within C#
Basically I have a onclick event that fires when you click on a checkbox
void OnClick(object sender, RoutedEventArgs e)
{
...
}
However, I need to fire this event once another event has been fired, so within this new event, is it possible I can fire the above one?
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
switch(dataGrid.Name)
{
case "Customer"
//fire OnCLick Event
break;
}
}
I have tried something like
??? += new MouseEventHandler(OnClick);
But I am not sure if this will actually work.
Yes you can, but only if the event is in your own class. You can't even raise a base class' event. You have a put a method in the base class to raise the event, and then call that.
The code you put there is adding another event handler, not raising an event; you don't need to do that.
If it's a button, use btnDoSomething.PerformClickEvent (winforms)
If the handler is in your code, you can call it without raising the event (commenters assume that this is what you want to do but in reaslity there are many cases where you'd need more than this) btnDoSomething_Click(null, null) - null usually works because handler code rarely cares about the sender or arguments and if you don't reference them, you don't need them.
If you can use #4, you can also refactor as mentioned. Usually not needed. But usually so easy to do you it's worth doing for clarity anyway.
For objects that map from Windows widgets of anysort, check out the SendMessage and PostMessage API calls. Wayyyy beyond the scope of this answer, though. Doesn't apply to non-windows-backed objects (but your sample implies windows).

How to generate events automatically for buttons without creating manually from properties if there are 'n' number of buttons?

IDE: Visual Studio 2010
Language: c# .net
I am generating events for buttons manually from properties. But, its becoming very lengthy process if there are suppose 20 buttons doing the same task like 'Mouse Hover' and 'Mouse Leave' . So, is there a way to copy events for all the other buttons ?
You can subscribe all your buttons to same event handler:
foreach(var button in Controls.OfType<Button>())
{
button.MouseHover += Button_MouseHover; // add handler
button.MouseLeave += Button_MouseLeave;
}
In that handler you can determine which exact button raised even by casting event source to button type:
private void Button_MouseHover(object sender, EventArgs e)
{
var button = (Button)sender; // sender is one of buttons
// use button.Name
}
Code above subscribes to events of all buttons. But if you want to filter them (e.g. by name) you can add filtering:
Controls.OfType<Button>().Where(b => b.Name.StartsWith("foo"))
Buttons can all share the same event, there's no need to have a seperate event for each button if they're doing similar tasks. (The object sender parameter will give you the Control which was clicked.
IF you select all the buttons (by keeping the ctrl key pressed) in the designer, you can then easily assign 1 event to all 20 buttons
In life you will not find shortcuts for everything,
In short there is no shortcut, but yes as mentioned in other post if you have same event handler and same action to be taken then this will help you reduce your work.
You don't have to do this manually, you can add event handlers from code as well. Also, if the logic is quite similar for all the buttons then you can use single event handler for all of them. Every event handler has sender property what will be set to the button that caused event.
Simple example would be something like this:
//at first assign event handlers
button1.Click += new EventHandler(Button_Click);
button2.Click += new EventHandler(Button_Click);
//single event handler
private void Button_Click(object sender, System.EventArgs e)
{
// Add event handler code here.
Debug.WriteLine("You clicked: {0}", sender);
}

How to raise list controls SelectedIndexChanged event in codebehind?

How to raise the SelectedIndexChanged event of an asp.net List control in a codebehind using C#?
If you're asking how to manually fire the event so that it can run whatever logic is attached: don't.
Your event handlers should be slim. If you need to perform the same operation from multiple places, then extract that functionality into its own method and have the event handler invoke that. For example:
private void CountryListBox_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateStates(ListBox1.SelectedItem.Text);
}
private void UpdateStates(string country)
{
StateListBox.DataSource = GetStates(country);
StateListBox.DataBind();
}
Now instead of trying to fire the SelectedIndexChanged event, you just invoke the method that this event handler refers to, i.e.
private void Page_Load(object sender, EventArgs e)
{
UpdateStates("USA");
}
Don't put complex logic in event handlers and try to raise those events from unexpected places. Instead, put the complex logic in its own method, so that you can perform the associated actions from elsewhere.
It is raised automatically.
Go in the Events section, lightening
bolt in properties window
alt text http://img704.imageshack.us/img704/6100/listbox.jpg
double click the place holder next to
event. This is what you will get.
protected void ListBox1_SelectedIndexChanged(object
sender, EventArgs e)
{
}
if you want to raise this event from another code block then, call
ListBox1_SelectedIndexChanged(sender,
e);
If what you want is more than just executing the code behaviour coded for the selected index (like listed in the previous answer), the short answer is there is no easy way. You can write a simple code that on prerender or render to explicitly define the control id variable in your rendered HTML and then use javascript to set the selected index. This will cause the postback that trigger the event. Alternatively you can register an ajax call back method and have the client calls that either when some event happened or by automatic timer.

ASP.NET Composite Control raise event to parent form

Say I have a composite control in ASP.NET (C#) which includes a drop down list. I need to be able to bubble the event back to the parent form so that other code can be executed based on its SelectedItem.
How do I expose the OnSelectedItemChanged event to the application?
Do I need to create my own delegate and raise it when the internal drop down list item is changed?
I've created control which contains a button and I'm using same approach; create a delegate and raise events on button's click.
public delegate void IndexChangeEventHandler(object sender, EventArgs e);
public event IndexChangeEventHandler SelectedIndexChanged = delegate { };
//this is in your composite control, handling ddl's index change event
protected void DDL_SelectedIndexchanged(object sender, EventArgs e)
{
SelectedIndexChanged(this, e);
}
Correct... You would want to create your own event for SelectedItem and write an event handler for the dropdown list's SelectedItem and inside the method raise your event.

Categories

Resources