Search Results

Search found 461 results on 19 pages for 'eventhandler'.

Page 1/19 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • C#/.NET Little Wonders: The EventHandler and EventHandler<TEventArgs> delegates

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. In the last two weeks, we examined the Action family of delegates (and delegates in general), and the Func family of delegates and how they can be used to support generic, reusable algorithms and classes. So this week, we are going to look at a handy pair of delegates that can be used to eliminate the need for defining custom delegates when creating events: the EventHandler and EventHandler<TEventArgs> delegates. Events and delegates Before we begin, let’s quickly consider events in .NET.  According to the MSDN: An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. So, basically, you can create an event in a type so that users of that type can subscribe to notifications of things of interest.  How is this different than some of the delegate programming that we talked about in the last two weeks?  Well, you can think of an event as a special access modifier on a delegate.  Some differences between the two are: Events are a special access case of delegates They behave much like delegates instances inside the type they are declared in, but outside of that type they can only be (un)subscribed to. Events can specify add/remove behavior explicitly If you want to do additional work when someone subscribes or unsubscribes to an event, you can specify the add and remove actions explicitly. Events have access modifiers, but these only specify the access level of those who can (un)subscribe A public event, for example, means anyone can (un)subscribe, but it does not mean that anyone can raise (invoke) the event directly.  Events can only be raised by the type that contains them In contrast, if a delegate is visible, it can be invoked outside of the object (not even in a sub-class!). Events tend to be for notifications only, and should be treated as optional Semantically speaking, events typically don’t perform work on the the class directly, but tend to just notify subscribers when something of note occurs. My basic rule-of-thumb is that if you are just wanting to notify any listeners (who may or may not care) that something has happened, use an event.  However, if you want the caller to provide some function to perform to direct the class about how it should perform work, make it a delegate. Declaring events using custom delegates To declare an event in a type, we simply use the event keyword and specify its delegate type.  For example, let’s say you wanted to create a new TimeOfDayTimer that triggers at a given time of the day (as opposed to on an interval).  We could write something like this: 1: public delegate void TimeOfDayHandler(object source, ElapsedEventArgs e); 2:  3: // A timer that will fire at time of day each day. 4: public class TimeOfDayTimer : IDisposable 5: { 6: // Event that is triggered at time of day. 7: public event TimeOfDayHandler Elapsed; 8:  9: // ... 10: } The first thing to note is that the event is a delegate type, which tells us what types of methods may subscribe to it.  The second thing to note is the signature of the event handler delegate, according to the MSDN: The standard signature of an event handler delegate defines a method that does not return a value, whose first parameter is of type Object and refers to the instance that raises the event, and whose second parameter is derived from type EventArgs and holds the event data. If the event does not generate event data, the second parameter is simply an instance of EventArgs. Otherwise, the second parameter is a custom type derived from EventArgs and supplies any fields or properties needed to hold the event data. So, in a nutshell, the event handler delegates should return void and take two parameters: An object reference to the object that raised the event. An EventArgs (or a subclass of EventArgs) reference to event specific information. Even if your event has no additional information to provide, you are still expected to provide an EventArgs instance.  In this case, feel free to pass the EventArgs.Empty singleton instead of creating new instances of EventArgs (to avoid generating unneeded memory garbage). The EventHandler delegate Because many events have no additional information to pass, and thus do not require custom EventArgs, the signature of the delegates for subscribing to these events is typically: 1: // always takes an object and an EventArgs reference 2: public delegate void EventHandler(object sender, EventArgs e) It would be insane to recreate this delegate for every class that had a basic event with no additional event data, so there already exists a delegate for you called EventHandler that has this very definition!  Feel free to use it to define any events which supply no additional event information: 1: public class Cache 2: { 3: // event that is raised whenever the cache performs a cleanup 4: public event EventHandler OnCleanup; 5:  6: // ... 7: } This will handle any event with the standard EventArgs (no additional information).  But what of events that do need to supply additional information?  Does that mean we’re out of luck for subclasses of EventArgs?  That’s where the generic for of EventHandler comes into play… The generic EventHandler<TEventArgs> delegate Starting with the introduction of generics in .NET 2.0, we have a generic delegate called EventHandler<TEventArgs>.  Its signature is as follows: 1: public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e) 2: where TEventArgs : EventArgs This is similar to EventHandler except it has been made generic to support the more general case.  Thus, it will work for any delegate where the first argument is an object (the sender) and the second argument is a class derived from EventArgs (the event data). For example, let’s say we wanted to create a message receiver, and we wanted it to have a few events such as OnConnected that will tell us when a connection is established (probably with no additional information) and OnMessageReceived that will tell us when a new message arrives (probably with a string for the new message text). So for OnMessageReceived, our MessageReceivedEventArgs might look like this: 1: public sealed class MessageReceivedEventArgs : EventArgs 2: { 3: public string Message { get; set; } 4: } And since OnConnected needs no event argument type defined, our class might look something like this: 1: public class MessageReceiver 2: { 3: // event that is called when the receiver connects with sender 4: public event EventHandler OnConnected; 5:  6: // event that is called when a new message is received. 7: public event EventHandler<MessageReceivedEventArgs> OnMessageReceived; 8:  9: // ... 10: } Notice, nowhere did we have to define a delegate to fit our event definition, the EventHandler and generic EventHandler<TEventArgs> delegates fit almost anything we’d need to do with events. Sidebar: Thread-safety and raising an event When the time comes to raise an event, we should always check to make sure there are subscribers, and then only raise the event if anyone is subscribed.  This is important because if no one is subscribed to the event, then the instance will be null and we will get a NullReferenceException if we attempt to raise the event. 1: // This protects against NullReferenceException... or does it? 2: if (OnMessageReceived != null) 3: { 4: OnMessageReceived(this, new MessageReceivedEventArgs(aMessage)); 5: } The above code seems to handle the null reference if no one is subscribed, but there’s a problem if this is being used in multi-threaded environments.  For example, assume we have thread A which is about to raise the event, and it checks and clears the null check and is about to raise the event.  However, before it can do that thread B unsubscribes to the event, which sets the delegate to null.  Now, when thread A attempts to raise the event, this causes the NullReferenceException that we were hoping to avoid! To counter this, the simplest best-practice method is to copy the event (just a multicast delegate) to a temporary local variable just before we raise it.  Since we are inside the class where this event is being raised, we can copy it to a local variable like this, and it will protect us from multi-threading since multicast delegates are immutable and assignments are atomic: 1: // always make copy of the event multi-cast delegate before checking 2: // for null to avoid race-condition between the null-check and raising it. 3: var handler = OnMessageReceived; 4: 5: if (handler != null) 6: { 7: handler(this, new MessageReceivedEventArgs(aMessage)); 8: } The very slight trade-off is that it’s possible a class may get an event after it unsubscribes in a multi-threaded environment, but this is a small risk and classes should be prepared for this possibility anyway.  For a more detailed discussion on this, check out this excellent Eric Lippert blog post on Events and Races. Summary Generic delegates give us a lot of power to make generic algorithms and classes, and the EventHandler delegate family gives us the flexibility to create events easily, without needing to redefine delegates over and over.  Use them whenever you need to define events with or without specialized EventArgs.   Tweet Technorati Tags: .NET, C#, CSharp, Little Wonders, Generics, Delegates, EventHandler

    Read the article

  • Invoking EventHandler generic, TargetParameterCountException

    - by Am
    Hi, I have a DirectoryMonitor class which works on another thread. It has the following events declared: public class DirectoryMonitor { public event EventHandler<MonitorEventArgs> CreatedNewBook; public event EventHandler ScanStarted; .... } public class MonitorEventArgs : EventArgs { public Book Book { get; set; } } There is a form using that monitor, and upon receiving the events, it should update the display. Now, this works: void DirectoryMonitor_ScanStarted(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(this.DirectoryMonitor_ScanStarted)); } else {...} } But this throws TargetParameterCountException: void DirectoryMonitor_CreatedNewBook(object sender, MonitorEventArgs e) { if (InvokeRequired) { Invoke(new EventHandler<MonitorEventArgs>(this.DirectoryMonitor_CreatedNewBook)); } else {...} } What am I missing?

    Read the article

  • wpf c# remove eventhandler from scrollviewer

    - by rubentjeuh
    I've got this: <ScrollViewer x:Name="svBegin" CanContentScroll="True"> <Grid x:Name="gGegevensGrid" KeyDown="gGegevensGrid_KeyDown" ScrollViewer.VerticalScrollBarVisibility="Visible"></Grid> As you can see I've got a KeyDown eventhandler on the grid. But when I press the downkey, the scrollviewer scrolls down. Even when I try this, it doesn't work: svBegin.KeyDown += new KeyEventHandler(svBegin_KeyDown); svBegin.KeyDown -= new KeyEventHandler(svBegin_KeyDown); Anybody who knows how to solve this problem? Thanks!

    Read the article

  • remove eventhandler from wpf scrollviewer

    - by rubentjeuh
    I've got this: <ScrollViewer x:Name="svBegin" CanContentScroll="True"> <Grid x:Name="gGegevensGrid" KeyDown="gGegevensGrid_KeyDown" ScrollViewer.VerticalScrollBarVisibility="Visible"></Grid> </ScrollViewer> As you can see I've got a KeyDown eventhandler on the grid. But when I press the downkey, the scrollviewer scrolls down. Even when I try this, it doesn't work: svBegin.KeyDown += new KeyEventHandler(svBegin_KeyDown); svBegin.KeyDown -= new KeyEventHandler(svBegin_KeyDown); Anybody who knows how to solve this problem?

    Read the article

  • When i am adding eventHandler on combo in datagridview, its adding eventHandler to all other combo o

    - by Rajesh Rolen- DotNet Developer
    i am using VS2005 (c#.net desktop application). when i am adding eventHandler to a combo of datagridview, its automatically adding same eventhandler to all other combos of same datagridview.. my code: private void dgvtstestdetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { DataGridView grid = (sender as DataGridView); if (grid.CurrentCell.OwningColumn == grid.Columns["gdvtstd_TestParameter"]) { ComboBox cb = (e.Control as ComboBox); cb.SelectedIndexChanged -= new EventHandler(dvgCombo_SelectedIndexChanged); cb.SelectedIndexChanged += new EventHandler(dvgCombo_SelectedIndexChanged); } }

    Read the article

  • calling .ajax() from an eventHandler c# asp.ent

    - by ibininja
    Good day...! In the code behind (upload.aspx) I have an event that returns the number of bytes being streamed; and as I debug it, it works fine. I wanted to reflect the numbers returned from the eventHandler on a progress bar and this is where I got lost. I tried using jQuery's .ajax() function. this is how I implemented it: In the EventHandler in my code behind I added this code to call the .ajax() function: Page.ClientScript.RegisterStartupScript(this.GetType(), "UpdateProgress", "<script type='text/javascript'>updateProgress();</script>"); My plan is whenever the eventHandler function changes the values of bytes being streamed it calls the javascript function "updateProgress()" The .ajax() function "UpdateProgress()" is as: function updateProgress() { $.ajax({ type: "POST", url: "upload.aspx/GetData", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", async: true, success: function (msg) { $("#progressbar").progressbar("option", "value", msg.d); } }); } I made sure that the function GetData() is [System.Web.Services.WebMethod] and that it is static as well. so the workflow of what I am trying to implement is as: - Click On Upload button - The Behind code starts executing and EventHandler triggers - The EventHandler calls .ajax() function - The .ajax() function retrieves the bytes being streamed and updates progress bar. When I ran the code; all runs well except that the .ajax() is only executed when upload is finished (and progress bar also updates only when finished upload); even though I call .ajax() function every time in the eventHandler function as reflected above... What am I doing wrong? Am I thinking of this right? is there anything else I should add maybe an updatePanel or something? thank you

    Read the article

  • How to subscribe to EventHandler of a private control outside of Form

    - by randooom
    Hi all, maybe my design is not good, or I don't see the obvious solution, but I want to subscribe to a buttonClick EventHandler of Form1 from outside form1. For example I have a Controller and Form1 who are both instanced in the main function. Now I want to subscribe a function from Controller to the buttonClick event from Button1_Click in Form1. But the button1 is declarded private, so i can't do form1->Button1->Click += gcnew EventHandler(controller->function) Is there any way to get around this? Ok I could write a setter or something in Form1, but is there any other solution? I read some examples, but they are all calling events from within the same class so they don't address my specific problem.

    Read the article

  • BPEL, initialize variable and repeating onAlarm eventHandler

    - by Michael
    I have a little problem I can't solve so far. In BPEL I want to create an onAlarm eventHandler which fires immediatly (i.e. the "for" element is set to 'PT0S') and repeats every 2 seconds. This eventHandler shall contain a counter which increments every time the alarm fires. The question is: How to initialize the counter? If the variable will be initialized within the onAlarm scope the value would not increment anymore. In the "normal" control flow the value also cannot be initialized, because it is not defined if the process or the onAlarm scope runs first. So I would get every now and then an uninitializedVariable exception. My solution would be to not initialize the variable neither in the process scope nor in the onAlarm scope, but create a faultHandler wherein the variable will be initialized and afterwards the onAlarm flow will be executed. Problem is every uninitializedVariable execution will be caught now by this faultHandler and there may be another too. So is there another possibility to deal with this problem or can I somehow find out which variable wasn't initialized properly so the faultHandler can get two control flows? The solution should work on every BPEL engine. Thanks, Michael

    Read the article

  • How to implement an EventHandler to update controls

    - by Bill
    May I ask for help with the following? I am attempting to connect and control three pieces of household electronic equipment by computer through a GlobalCache GC-100 and iTach. As you will see in the following code, I created a class-instance of GlobalCacheAdapter that communicates with each piece of equipment. Although the code seems to work well in controlling the equipment, I am having trouble updating controls with the feedback from the equipment. The procedure "ReaderThreadProc" captures the feedback; however I don't know how to update the associated TextBox with the feedback. I believe that I need to create an EventHandler to notify the TextBox of the available update; however I am uncertain as to how an EventHandler like this would be implemented. Any help wold be greatly appreciated. using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { // Create three new instances of GlobalCacheAdaptor and connect. // GC-100 (Elan) 192.168.1.70 4998 // GC-100 (TuneSuite) 192.168.1.70 5000 // GC iTach (Lighting) 192.168.1.71 4999 private GlobalCacheAdaptor elanGlobalCacheAdaptor; private GlobalCacheAdaptor tuneSuiteGlobalCacheAdaptor; private GlobalCacheAdaptor lutronGlobalCacheAdaptor; public Form1() { InitializeComponent(); elanGlobalCacheAdaptor = new GlobalCacheAdaptor(); elanGlobalCacheAdaptor.ConnectToDevice(IPAddress.Parse("192.168.1.70"), 4998); tuneSuiteGlobalCacheAdaptor = new GlobalCacheAdaptor(); tuneSuiteGlobalCacheAdaptor.ConnectToDevice(IPAddress.Parse("192.168.1.70"), 5000); lutronGlobalCacheAdaptor = new GlobalCacheAdaptor(); lutronGlobalCacheAdaptor.ConnectToDevice(IPAddress.Parse("192.168.1.71"), 4999); elanTextBox.Text = elanGlobalCacheAdaptor._line; tuneSuiteTextBox.Text = tuneSuiteGlobalCacheAdaptor._line; lutronTextBox.Text = lutronGlobalCacheAdaptor._line; } private void btnZoneOnOff_Click(object sender, EventArgs e) { elanGlobalCacheAdaptor.SendMessage("sendir,4:3,1,40000,4,1,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,800" + Environment.NewLine); } private void btnSourceInput1_Click(object sender, EventArgs e) { elanGlobalCacheAdaptor.SendMessage("sendir,4:3,1,40000,1,1,20,179,20,179,20,179,20,179,20,179,20,179,20,179,20,278,20,179,20,179,20,179,20,780" + Environment.NewLine); } private void btnSystemOff_Click(object sender, EventArgs e) { elanGlobalCacheAdaptor.SendMessage("sendir,4:3,1,40000,1,1,20,184,20,184,20,184,20,184,20,184,20,286,20,286,20,286,20,184,20,184,20,184,20,820" + Environment.NewLine); } private void btnLightOff_Click(object sender, EventArgs e) { lutronGlobalCacheAdaptor.SendMessage("sdl,14,0,0,S2\x0d"); } private void btnLightOn_Click(object sender, EventArgs e) { lutronGlobalCacheAdaptor.SendMessage("sdl,14,100,0,S2\x0d"); } private void btnChannel31_Click(object sender, EventArgs e) { tuneSuiteGlobalCacheAdaptor.SendMessage("\xB8\x4D\xB5\x33\x31\x00\x30\x21\xB8\x0D"); } private void btnChannel30_Click(object sender, EventArgs e) { tuneSuiteGlobalCacheAdaptor.SendMessage("\xB8\x4D\xB5\x33\x30\x00\x30\x21\xB8\x0D"); } } } public class GlobalCacheAdaptor { public Socket _multicastListener; public string _preferredDeviceID; public IPAddress _deviceAddress; public Socket _deviceSocket; public StreamWriter _deviceWriter; public bool _isConnected; public int _port; public IPAddress _address; public string _line; public GlobalCacheAdaptor() { } public static readonly GlobalCacheAdaptor Instance = new GlobalCacheAdaptor(); public bool IsListening { get { return _multicastListener != null; } } public GlobalCacheAdaptor ConnectToDevice(IPAddress address, int port) { if (_deviceSocket != null) _deviceSocket.Close(); try { _port = port; _address = address; _deviceSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _deviceSocket.Connect(new IPEndPoint(address, port)); ; _deviceAddress = address; var stream = new NetworkStream(_deviceSocket); var reader = new StreamReader(stream); var writer = new StreamWriter(stream) { NewLine = "\r", AutoFlush = true }; _deviceWriter = writer; writer.WriteLine("getdevices"); var readerThread = new Thread(ReaderThreadProc) { IsBackground = true }; readerThread.Start(reader); _isConnected = true; return Instance; } catch { DisconnectFromDevice(); MessageBox.Show("ConnectToDevice Error."); throw; } } public void SendMessage(string message) { try { var stream = new NetworkStream(_deviceSocket); var reader = new StreamReader(stream); var writer = new StreamWriter(stream) { NewLine = "\r", AutoFlush = true }; _deviceWriter = writer; writer.WriteLine(message); var readerThread = new Thread(ReaderThreadProc) { IsBackground = true }; readerThread.Start(reader); } catch { MessageBox.Show("SendMessage() Error."); } } public void DisconnectFromDevice() { if (_deviceSocket != null) { try { _deviceSocket.Close(); _isConnected = false; } catch { MessageBox.Show("DisconnectFromDevice Error."); } _deviceSocket = null; } _deviceWriter = null; _deviceAddress = null; } private void ReaderThreadProc(object state) { var reader = (StreamReader)state; try { while (true) { var line = reader.ReadLine(); if (line == null) break; _line = _line + line + Environment.NewLine; } // Need to create EventHandler to notify the TextBoxes to update with _line } catch { MessageBox.Show("ReaderThreadProc Error."); } } }

    Read the article

  • += new EventHandler(Method) vs += Method

    - by mafutrct
    There are two basic ways to subscribe to an event: SomeEvent += new EventHandler<ArgType> (MyHandlerMethod); SomeEvent += MyHandlerMethod; What is the difference, and when should I chose one over the other? Edit: If it is the same, then why does VS default to the long version, cluttering the code? That makes no sense at all to me.

    Read the article

  • how to get linkbutton id that is genrated dynamically from code behind in the eventhandler

    - by Ranjana
    i have create two linkbuttons dynamically: for (int i = 0; i < 2; i++) { LinkButton lb = new LinkButton(); lb.ID = "lnk" + FileName; lb.Text = FileName; Session["file"] = FileName; lb.CommandArgument = FileName; lb.Click += new EventHandler(Lb_Click); Panel1.Controls.Add(lb); Panel1.Controls.Add(new LiteralControl("<br />")); } i have got two links namely: File11 File22 void Lb_Click(object sender, EventArgs e) { string id=lb.ID; i.e //--Here how to get link button id which is clicked (either File11 id or File22 id)-------------------- }

    Read the article

  • WPF: Exception if i add a eventhandler to a MenuItem (in a ListBox)

    - by user437899
    Hi, i wanted a contextmenu for my ListBoxItems. So i created this: <ListBox Name="listBoxName"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding UserName}" /> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="ContextMenu"> <Setter.Value> <ContextMenu> <MenuItem Header="View" Name="MenuItemView" /> </ContextMenu> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> </ListBox> This works great. I have the contextmenu for all items, but if i want to add a click-eventhandler to the menuitem, like this: <MenuItem Header="View" Name="MenuItemView" Click="MenuItemView_Click" /> I get a XamlParseException when the window is created. InnerException: The Object System.Windows.Controls.MenuItem cannot be converted to type System.Windows.Controls.Grid It throws only the exception if i add a event-handler. The event-method is empty.

    Read the article

  • Get a button in itemscontrol and add eventhandler to its click event

    - by rockdale
    I have a custom control shows a customer info with an itemscontrol shows this customer's invoices. within the itemscontrol, I have button, in my code behind I want to wire the button's click event to my host window, but do now know how. //public event RoutedEventHandler ViewDetailClick; public static readonly RoutedEvent ButtonViewClickEvent = EventManager.RegisterRoutedEvent( "ButtonViewClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(custitem)); public event RoutedEventHandler ButtonViewClick { add { AddHandler(ButtonViewClickEvent, value); } remove {RemoveHandler(ButtonViewClickEvent, value);} } public override void OnApplyTemplate() { base.OnApplyTemplate(); this.lstInv = GetTemplateChild("lstInv") as ItemsControl; lstInv.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged); } private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e) { if (lstInv.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) { lstInv.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged; for (int i = 0; i < this.lstInv.Items.Count; i++) { ContentPresenter c = lstInv.ItemContainerGenerator.ContainerFromItem(lstInv.Items[i]) as ContentPresenter; DataTemplate dt = c.ContentTemplate; Grid grd = dt.LoadContent() as Grid; Button btnView = grd.FindName("btnView") as Button; if (btnView != null) { btnView.Click += new RoutedEventHandler(ButtonView_Click); //btnView.Click+= delegate(object senderObj, RoutedEventArgs eArg) //{ // if (this.ViewDetailClick != null) // { // this.ViewDetailClick(this, eArg); // } //}; } } private void ButtonView_Click(object sender, RoutedEventArgs e) { MessageBox.Show("clicked"); //e.RoutedEvent = ButtonViewClickEvent; //e.Source = sender; //RaiseEvent(e); } I succeed getting the btnView, then attach the click event, but the click event never get fired. Thanks in advance -rockdale

    Read the article

  • Question regarding to value/reference type of events

    - by Petr
    Hi, On the MSDN, I have found following: public event EventHandler<MyEventArgs> SampleEvent; public void DemoEvent(string val) { // Copy to a temporary variable to be thread-safe. EventHandler<MyEventArgs> temp = SampleEvent; if (temp != null) temp(this, new MyEventArgs(val)); } I do not understand, "copy to temporary variable", isnt it reference type?

    Read the article

  • Calling Sub from EventHandler

    - by madlan
    I'm using the below to update controls from another thread (works great) How would I call a Sub (Named UpdateList)? The UpdateList updates a listview with a list of databases on a selected SQL instance, requires no arguments. Private Sub CompleteEventHandler(ByVal sender As Object, ByVal e As Microsoft.SqlServer.Management.Common.ServerMessageEventArgs) SetControlPropertyValue(Label8, "text", e.ToString) UpdateList() MessageBox.Show("Restore Complete") End Sub Delegate Sub SetControlValueCallback(ByVal oControl As Control, ByVal propName As String, ByVal propValue As Object) Private Sub SetControlPropertyValue(ByVal oControl As Control, ByVal propName As String, ByVal propValue As Object) If (oControl.InvokeRequired) Then Dim d As New SetControlValueCallback(AddressOf SetControlPropertyValue) oControl.Invoke(d, New Object() {oControl, propName, propValue}) Else Dim t As Type = oControl.[GetType]() Dim props As PropertyInfo() = t.GetProperties() For Each p As PropertyInfo In props If p.Name.ToUpper() = propName.ToUpper() Then p.SetValue(oControl, propValue, Nothing) End If Next End If End Sub Based On: http://www.shabdar.org/cross-thread-operation-not-valid.html

    Read the article

  • Using argument (this) passed via element eventhandler

    - by Kel
    Hey guys, I want to use the argument I pass (this) in a JS function and treat it as an jQuery variable. Example: <script> function useMe(obj){ $(obj).val(); ... ... ... } </script> <select id="selectid" onChange="useMe(this)"> <option>......</option> </select> Is there a possibility to treat the passed argument as a jQuery element? Btw. I need to do it this way, because the select-element isn't created on load. The select element will be created later asynchronously. So, this won't work: $("select").each(function (i){ var select_id = $(this).attr("id"); $(this).change(function(e){ because it doesn't exist yet. Thanks for your help.

    Read the article

  • [JS/jQuery] Using argument (this) passed via element eventhandler

    - by Kel
    Hey guys, I want to use the argument I pass (this) in a JS function and treat it as an jQuery variable. Example: <script> function useMe(obj){ $(obj).val(); ... ... ... } </script> <select id="selectid" onChange="useMe(this)"> <option>......</option> </select> Is there a possibility to treat the passed argument as a jQuery element? Btw. I need to do it this way, because the select-element isn't created on load. The select element will be created later asynchronously. So, this won't work: $("select").each(function (i){ var select_id = $(this).attr("id"); $(this).change(function(e){ because it doesn't exist yet. Thanks for your help.

    Read the article

  • C# How to find if an event is hooked up

    - by Nick
    I want to be able to find out if an event is hooked up or not. I've looked around, but I've only found solutions that involved modifying the internals of the object that contains the event. I don't want to do this. Here is some test code that I thought would work: // Create a new event handler that takes in the function I want to execute when the event fires EventHandler myEventHandler = new EventHandler(myObject_SomeEvent); // Get "p1" number events that got hooked up to myEventHandler int p1 = myEventHandler.GetInvocationList().Length; // Now actually hook an event up myObject.SomeEvent += m_myEventHandler; // Re check "p2" number of events hooked up to myEventHandler int p2 = myEventHandler.GetInvocationList().Length; Unfort the above is dead wrong. I thought that somehow the "invocationList" in myEventHandler would automatically get updated when I hooked an event to it. But no, this is not the case. The length of this always comes back as one. Is there anyway to determine this from outside the object that contains the event?

    Read the article

  • c# winforms events restore textbox contents on escape

    - by aj3jr
    Using c# in 2008 Express. I have a textbox containing a path. I append a "\" at the end on Leave Event. If the user presses 'Escape' key I want the old contents to be restored. When I type over all the text and press 'Escape' I hear a thump and the old text isn't restored. Here what I have so far ... public string _path; public string _oldPath; this.txtPath.KeyPress += new System.Windows.Forms.KeyPressEventHandler(txtPath_CheckKeys); this.txtPath.Enter +=new EventHandler(txtPath_Enter); this.txtPath.LostFocus += new EventHandler(txtPath_LostFocus); public void txtPath_CheckKeys(object sender, KeyPressEventArgs kpe) { if (kpe.KeyChar == (char)27) { _path = _oldPath; } } public void txtPath_Enter(object sender, EventArgs e) { //AppendSlash(sender, e); _oldPath = _path; } void txtPath_LostFocus(object sender, EventArgs e) { //throw new NotImplementedException(); AppendSlash(sender, e); } public void AppendSlash(object sender, EventArgs e) { //add a slash to the end of the txtPath string on ANY change except a restore this.txtPath.Text += @"\"; } Thanks in advance,

    Read the article

  • C#: Need one of my classes to trigger an event in another class to update a text box

    - by Matt
    Total n00b to C# and events although I have been programming for a while. I have a class containing a text box. This class creates an instance of a communication manager class that is receiving frames from the Serial Port. I have this all working fine. Every time a frame is received and its data extracted, I want a method to run in my class with the text box in order to append this frame data to the text box. So, without posting all of my code I have my form class... public partial class Form1 : Form { CommManager comm; public Form1() { InitializeComponent(); comm = new CommManager(); } private void updateTextBox() { //get new values and update textbox } . . . and I have my CommManager class class CommManager { //here we manage the comms, recieve the data and parse the frame } SO... essentially, when I parse that frame, I need the updateTextBox method from the form class to run. I'm guessing this is possible with events but I can't seem to get it to work. I tried adding an event handler in the form class after creating the instance of CommManager as below... comm = new CommManager(); comm.framePopulated += new EventHandler(updateTextBox); ...but I must be doing this wrong as the compiler doesn't like it... Any ideas?!

    Read the article

  • Why does my sharepoint web part event handler lose the sender value on postback?

    - by vishal shah
    I have a web part which is going to be a part of pair of connected web parts. For simplicity, I am just describing the consumer web part. This web part has 10 link buttons on it. And they are rendered in the Render method instead ofCreateChildControls as this webpart will be receiving values based on input from the provider web part. Each Link Button has a text which is decided dynamically based on the input from provider web part. When I click on any of the Link Buttons, the event handler is triggered but the text on the Link Button shows up as the one set in CreateChildControls. When I trace the code, I see that the CreateChildControls gets called before the event handler (and i think that resets my Link Buttons). How do I get the event handler to show me the dynamic text instead? Here is the code... public class consWebPart : Microsoft.SharePoint.WebPartPages.WebPart { private bool _error = false; private LinkButton[] lkDocument = null; public consWebPart() { this.ExportMode = WebPartExportMode.All; } protected override void CreateChildControls() { if (!_error) { try { base.CreateChildControls(); lkDocument = new LinkButton[101]; for (int i = 0; i < 10; i++) { lkDocument[i] = new LinkButton(); lkDocument[i].ID = "lkDocument" + i; lkDocument[i].Text = "Initial Text"; lkDocument[i].Style.Add("margin", "10 10 10 10px"); this.Controls.Add(lkDocument[i]); lkDocument[i].Click += new EventHandler(lkDocument_Click); } } catch (Exception ex) { HandleException(ex); } } } protected override void Render(HtmlTextWriter writer) { writer.Write("<table><tr>"); for (int i = 0; i < 10; i++) { writer.Write("<tr>"); lkDocument[i].Text = "LinkButton" + i; writer.Write("<td>"); lkDocument[i].RenderControl(writer); writer.Write("</td>"); writer.Write("</tr>"); } writer.Write("</table>"); } protected void lkDocument_Click(object sender, EventArgs e) { string strsender = sender.ToString(); LinkButton lk = (LinkButton)sender; } protected override void OnLoad(EventArgs e) { if (!_error) { try { base.OnLoad(e); this.EnsureChildControls(); } catch (Exception ex) { HandleException(ex); } } } private void HandleException(Exception ex) { this._error = true; this.Controls.Clear(); this.Controls.Add(new LiteralControl(ex.Message)); } }

    Read the article

  • There is no web named - Sharepoint Event Hander

    - by Roosh Malai
    I activated following code with feature (web level scope). Now when i add an item to any document library it should create a folder "". No folder is created and no error is given either. can anyone see what's is going on? I got the following from the log file. I found similar code all over google so I am kinda puzzled why is not working in my environment. Thanks using System; using System.Collections.Generic; using System.Text; using Microsoft.SharePoint; namespace AddaFolder { class clAddaFolder : SPItemEventReceiver { public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); using (SPSite currentSite = new SPSite(SPContext.Current.Site.Url)) using (SPWeb currentWeb = currentSite.OpenWeb(SPContext.Current.Web.Url)) { try { //SPListTemplateCollection coll = currentWeb.ListTemplates; //Get the current document library link SPList newList = currentWeb.GetList(SPContext.Current.Web.Url); //.Site.Url); //newList = currentWeb.Lists.Add("My TEST Folder",SPFileSystemObjectType.Folder); //newList.Lists.Items.Add("My TEST Folder", SPFileSystemObjectType.Folder); //newList.Update(); SPListItem newListItem; //newListItem = newList.Folders.Add("", SPFileSystemObjectType.Folder, "My Test Folder"); newListItem = newList.Folders.Add(newList.ToString(), SPFileSystemObjectType.Folder, "My Test Folder"); newListItem.Update(); } catch (SPException spEx) { throw spEx; } } } } } 04/03/2010 17:52:44.25 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Shared Documents/Forms/AllItems.aspx". 04/03/2010 17:52:44.26 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/My TEST Doc Library/Forms/AllItems.aspx". 04/03/2010 17:52:44.27 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Calendar/calendar.aspx". 04/03/2010 17:52:44.29 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Tasks/AllItems.aspx". 04/03/2010 17:52:44.30 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Team Discussion/AllItems.aspx". 04/03/2010 17:52:44.31 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Shared Documents/Forms/AllItems.aspx". 04/03/2010 17:52:44.32 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/My TEST Doc Library/Forms/AllItems.aspx". 04/03/2010 17:52:44.34 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Calendar/calendar.aspx". 04/03/2010 17:52:44.35 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Tasks/AllItems.aspx". 04/03/2010 17:52:44.36 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Team Discussion/AllItems.aspx". 04/03/2010 17:52:51.33 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Shared Documents/Forms/AllItems.aspx". 04/03/2010 17:52:51.34 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/My TEST Doc Library/Forms/AllItems.aspx". 04/03/2010 17:52:51.35 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Calendar/calendar.aspx". 04/03/2010 17:52:51.37 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Tasks/AllItems.aspx". 04/03/2010 17:52:51.38 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Team Discussion/AllItems.aspx". 04/03/2010 17:52:51.39 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Shared Documents/Forms/AllItems.aspx". 04/03/2010 17:52:51.40 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/My TEST Doc Library/Forms/AllItems.aspx". 04/03/2010 17:52:51.41 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Calendar/calendar.aspx". 04/03/2010 17:52:51.43 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Tasks/AllItems.aspx". 04/03/2010 17:52:51.44 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Team Discussion/AllItems.aspx". 04/03/2010 17:53:02.69 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Shared Documents/Forms/AllItems.aspx". 04/03/2010 17:53:02.71 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/My TEST Doc Library/Forms/AllItems.aspx". 04/03/2010 17:53:02.72 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Calendar/calendar.aspx". 04/03/2010 17:53:02.73 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Tasks/AllItems.aspx". 04/03/2010 17:53:02.74 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Team Discussion/AllItems.aspx". 04/03/2010 17:53:02.75 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Shared Documents/Forms/AllItems.aspx". 04/03/2010 17:53:02.76 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/My TEST Doc Library/Forms/AllItems.aspx". 04/03/2010 17:53:02.77 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Calendar/calendar.aspx". 04/03/2010 17:53:02.78 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Tasks/AllItems.aspx". 04/03/2010 17:53:02.79 w3wp.exe (0x00C0) 0x0C88 Windows SharePoint Services General 8kh7 High There is no Web named "/sites/myDevSiteColl/myDevWeb/Lists/Team Discussion/AllItems.aspx".

    Read the article

  • Custom Event Handler

    - by Dremation
    I have a function that I'm using while(true) to repeatedly scan memory addresses of an application to detect change. I sleep the thread 1 second between iterations and this helps performance. However, is there a way to create a custom event handler to do away with the loops?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >