C# – Global exception event handlers

There are two global exception events available in all .NET applications: You wire up these event handlers in Main() (before anything else has executed), like this: Note: If you’re using top-level statements, put these statements at the top of the ‘entry point’ file. This outputs the following before crashing: Notice the FirstChanceException event fired first. … Read more

WinForms – How to remove checked items from CheckedListBox

Normally the items in a CheckedListBox are hardcoded or added programmatically (from an enum or from binding a data source). But sometimes you may want to allow the user to add and remove items from a CheckedListItem. In this article I’ll show how to add items and remove them. I’ll be working with text, and … Read more

C# – DataGridView index out of range exception

Problem When you’re using WinForms and click a DataGridView column header, you get an exception like this: Index was out of range. Must be non-negative and less than the size of the collection. This problem is caused by the column header “row” triggering a click event (such as CellContentClick) with event args containing RowIndex of … Read more

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Problem In a WinForms project, if you try to call Invoke/BeginInvoke before the window handle is created, you’ll get the following exception: System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created Because this exception happens while the form is initializing, it typically results in the form not … Read more

WinForms: How to handle DataGridViewButtonColumn click event

Here’s how to handle the DataGridViewButtonColumn button click event: In this article I’ll show a step-by-step example of how to handle the button click. Example DataGridView with a button column When I click the button I want it to say Hi to the person. 1 – Set the DataSource to BindingList<Person> 2 – Add ClickHandler(Person … Read more

C# – Monitor data changes with SQL Server query notifications

You can use SQL Server query notifications to send push notifications to your code when data changes. This is an alternative to polling the database for changes. In this article, I’ll show how to configure this feature and work with it in the code. 1 – Enable Service Broker and configure permissions You need to … Read more

C# – Example of using events

Events are an implementation of the observer pattern and consists of two parts: There are three simple steps to using events, which I’ll show below. 1 – Add an event field The first step is to add an event field to a class with the event keyword and a delegate type (such as the generic … Read more