tags:

views:

195

answers:

1

I am a C# newbie and have a class that needs to pass row information to a grid in the windows form. What is the best way to do it? I have put in some example code for better understanding.

public class GUIController
{   
    private My_Main myWindow;


    public GUIController( My_Main window )
    {
        myWindow = window;
    }

    public void UpdateProducts( List<myProduct> newList )
    {
        object[] row = new object[3];

        foreach (myProduct product in newList)
        {
            row[0] = product.Name;
            row[1] = product.Status;
            row[2] = product.Day;

            //HOW DO I USE BeginInvoke HERE?
       }
    }
}

And the form class below:

public class My_Main : Form
{
    //HOW DO I GO ABOUT USING THIS DELEGATE?
    public delegate void ProductDelegate( string[] row );
    public static My_Main theWindow = null;

    static void Main(  )
    {            
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        theWindow = new My_Main();
        Application.Run(theWindow);

    }

    private void My_Main_Load( object sender, EventArgs e )
    {            

        /// Create GUIController and pass the window object
        gui = new GUIController( this );
     }

    public void PopulateGrid( string[] row )
    {
        ProductsGrid.Rows.Add(row);
        ProductsGrid.Update();

    }
}
+1  A: 

Like this:

myWindow.BeginInvoke(new My_Main.ProductDelegate(myWindow.PopulateGrid), new object[] { row });

However, you should only use Invoke / BeginInvoke if your code is running on a background thread.

If your UpdateProducts method runs on the UI thread, you don't need BeginInvoke; you can simply call the method normally, like this:

myWindow.PopulateGrid(row);

If you do call BeginInvoke, you need to create a separate array instance in each iteration by moving the declaration of row inside the loop.

SLaks
Thanks! I have tried BeginInvoke as suggested by you earlier and have got a "Parameter count mismatch" error in Application.Run(theWindow);in Main().I also tried calling the method normally as in myWindow.PopulateGrid(row) and I get the following error:Cross-thread operation not valid: Control 'ProductsGrid' accessed from a thread other than the thread it was created on. I guess thats because they are on two different threads.
Bi
See my edit to resolve that error. Are you using multiple threads?
SLaks
Thanks - worked!
Bi
You _need_ to declare the array inside the loop, or you'll get strange and unreproducible problems.
SLaks