ShareThis

Showing posts with label WinForms. Show all posts
Showing posts with label WinForms. Show all posts

Sunday, August 4, 2013

[C#] WinForms - How to add your own methods to Control functions [with anonymous methods]

Adding your own methods to event handlers on controls is super easy.


Example 1
txtDataReceived.Click += delegate { foo(localVariable1,localVariable2); };
Example 2
imgbtn.Click += delegate { lbl.Visible = false; DoPostBack(); }; 

Wednesday, December 19, 2012

[C#] Get ONLY filename and extension from OpenDialog in C# WinForms

All you need to do in order to get the filename from an OpenDialog in C# is to use this method:

OpenFileDialog.SafeFileName

Example of an OpenFileDialog's FileName attribute: C://fakepath//item.txt
Example of an OpenFileDialog's SafeFileName attribute: item.txt

Tuesday, December 18, 2012

[C#][FIX] Cross-thread operation not valid in Winforms with threads.

A common problem using WinForms in Visual Studio is syncing between logic threads and UI threads. Most winform applications should use a method to sync between both; otherwise, you will see the Form freeze while waiting for the logic to complete.

The following shows an example of calling a function that creates a delegate to do cross-thread operations.

Code:

private void ThreadSafeFunction(int intVal, bool boolVal)
{
    if (this.InvokeRequired)
    {
        this.Invoke(
            new MethodInvoker(
            delegate() { yourMethod(intVal, boolVal); }));
    }
    else
    {
        //use intval and boolval
    }
}   

To use this method of cross-thread operations, call the ThreadSafeFunction in your logic thread.

In the curly brackets if the new delegate (), place any UI logic that needs to be done (i.e. yourTextbox.Text = intVal)

After you have updated the code to work with your WinForm, try it out and let us know how it goes!

Thursday, July 19, 2012

WinForms - Open Dialog *.xls | *.xlsx Filter example

To set your open dialog so only excel files can seen, use the following code on the Filter property:

(*.xls;*.xlsx;)|*.xls;*.xlsx;|All Files (*.*)|*