views:

234

answers:

2

I have written an Extension Method off of DataGridView called HideColumns.

public static class Extensions
{
    public static void HideColumns(this DataGridView dataGridView, params string[] columnNames)
    {
        foreach (string str in columnNames)
        {
            if (dataGridView.Columns[str] != null)
            {
                dataGridView.Columns[str].Visible = false;
            }
        }
    }

}

I pass my grid into an IronRuby script as a variable called main_grid

When my script calls main_grid.HideColumns("FirstName","LastName") the script blows up with Error in Script undefined method 'HideColumns' for System.Windows.Forms.DataGridView:System::Windows::Forms::DataGridView

The extension methods seem to work okay from C#. What gives?

+1  A: 

The extension method is just syntatic sugar, you will need to call it as:

Extensions.HideColumns(main_grid, "FirstName", "LastName")

alternatively create a new class in C# which derives from DataGridView and add the method:

public class DataGridViewExt : DataGridView  
{
    public void HideColumns(params string[] columnNames)
    {
        foreach (string str in columnNames)
        {
            if (this.Columns[str] != null)
            {
                this.Columns[str].Visible = false;
            }
        }
    }        
}

and use this class rather than the System.Windows.Forms class on your form.

JDunkerley
Can I extend the DataGridView (add sugar) from the Ruby side in 3.5? How do I go about this?
tyndall
Dont believe so, the easiest way would be to derive a class from DataGridView in C# and add the extension method in as a normal instance method (will update answer)
JDunkerley
Hmmm. Ok. I'll try that. +1 - I always get a little nervous about extending classes with visual representations. Do you know much about .NET 4.0 and IronRuby interop? Will I have other options then?
tyndall
Don't think it would help that way, I think the dynamic stuff is more for C# calling onto dynamic languages rather than the otherway round.
JDunkerley
A: 

Since you mentioned it in the comments to JDunkeryly's answer, here's how you'd extend the grid from the ruby side. Just open the class and add a method (only works from the ruby side).

class System::Windows::Forms::DataGridView
  def hide_columns(*columnNames)
    column_names.each do |cn|
      self.columns[cn].visible = false
    end
  end
end

As far as the suggestion to use the extension method directly, the params keyword is painful to IronRuby. You need to build a typed array with your arguments and pass it. You can't just wrap your ruby strings in a ruby array. I've pulled this off earlier today in a blog post. But if you have a smoother way to handle that, please let me know.

Ball