THINK

that’s how i naturally know

Archive for the ‘csharp’ tag

IEumerable cannot be used as a single object datasource

without comments

In the case of binding a an object and its property to, say, a control using the feature

control.DataBindings.Add("Text", myObject, "PropertyName");

will always work except when myObject is of the IEnumerable type. Once that happens, the data binding architecture will attempt to use the list of objects returned by the Enumerator for updating of UI and data source, which is not desirable for our purposes. For example, with

 public class MyObject : Hashtable
{
    public string PropertyName { get; set; }
} 

the DataBinding will fail logically because Hashtable is in fact an IEnumerable in disguise! Unfortunately there seems to be no way of telling .NET that we want it to treat MyObject as a single object, not unless we wrap it in another BindingSource or IEnumerable

Written by Jake

August 16th, 2011 at 10:02 am

Posted in Programming

Tagged with ,

ObjectGridView – An easier way to use DataGridView

without comments

With a project that I am currently working on, I frequently need to display object information in a DataGridView. However, the values that needs to be displayed does not always directly belong to the bounded objects, instead, it is often a value related to the objects. Furthermore the DataGridView only accepts an IList of objects and it translates the properties of each object in the IList to the displayed values in the DataGridView. There are times when the IList readily available is not the list of objects we need to display information for, but rather another related or parent object.

In order to fill my needs, I ended up writing an extended version of the DataGridView, which is in some ways inspired by the amazing ObjectListView. The following code shows what is possible with ObjectGridView.

public class House
{
    public string GetAddress();
}

public class Person
{
    public string FirstName { get; set; }
    public string Street { set; }
    public Car Car { get; set; }
}

public class Car
{
   public string Model { get; set; }
}

public static main()
{
    var persons = new BindingList<Person>();
    var houses = new Dictionary<Person, House>();

    ObjectGridView ogv = new ObjectGridView();
    ObjectGridViewTextBoxColumn colName, colModel, colAddress;
    // ...

    // regular DataGridView data association
    colName.DataPropertyName = "FirstName";

    // display a sub object of the bounded object
    colModel.ValueGetter = delegate(object model)
    {
       Person p = (Person)model;
       return p.Car.Model;
    }

    // display related information via a method call
    colAddress.ValueGetter = delegate(object model)
    {
       return houses[(Person)model].GetAddress();
    }

    // customised value setting when cell is being edited
    colAddress.ValueSetter = delegate(object model, object value)
    {
        Person p = (Person)model;
        p.Street = Convert.ToString(value);
    }

    // regular DataGridView databinding for 2 way updating of UI and datasource
    ogv.DataSource = new BindingSource(persons, null);
}

Download JakeSee.Winforms.ObjectGridView

Written by Jake

August 15th, 2011 at 7:29 pm

Highlight Selected Row in DataGridView

without comments

To make the entire DataGridViewRow highlighted when the row selected is set to true,
set the DataGridView.SelectionMode to FullRowSelect.

Written by Jake

April 27th, 2011 at 12:11 pm

Posted in Programming

Tagged with ,

C# Lambda Operator =>

without comments

Using a constructor as a delegate:

x => new MyClass(x);

if follows that this allows for C# generics to enable parameterized constructor of type T to be called within the generic class, thus bypassing the constraints.

Normally, one would delcare

public class MyClass<T> where T : new()
{
   // the above definition allows constructor call of
  void SomeFunction()
   {
       T myvar = new T();
   }
}

but if T does not have a parameterless constructor, then we can

public class MyClass<T>
{
     void SomeFunction(func<int, T> del)
      {
            int i = 10;
            T myvar = new del(i); // assume our constructor takes a single int as parameter
      }
}

and we invoke it by calling

myClass.SomeFunction(x => new apple(x));

Written by Jake

February 9th, 2011 at 12:28 pm

Posted in Programming

Tagged with ,

C# Mixins with Interfaces and Extension Methods

without comments

This is my first post on C#. Funny why I cannot create “C#” category, have to use “C Sharp” instead. Wells…

Following up on my previous discussion about C++ Mixins, I went on to see if C# was able to do it as well. I then realized that this capability has been sitting in my computer for ages just waiting for today to be discovered by myself!

Incidentally, mixins could be implemented using Interfaces and Extension Methods introduced in C# 3.0 which is the version of VS2008 i am currently using. Furthermore, it seems that the implementation in C# is even more powerful.

Let’s first take a look at mixins in C#.

class Program
{
    static void Main(string[] args)
    {
        // our Son can do all the daily stuff a happy child can do.
        Son son = new Son();
        son.Talk();
        son.Eat();
        son.Walk();
        son.Kick();
        son.Jump();
    }
}

// We demostrate in C# where a class can derive from a parent class
// and also from multiple Interfaces.
// this multi-interface is the fundamentally how mixin is possible.
public class Father { }
public class Son : Father, IMouth, ILeg { }
// by implementing the IMouth and ILeg interfaces,
// our Son gains the respective abilities
// through extension methods below

// The mouth interface and extension method
public interface IMouth {}
public static class Mouth
{
    public static void Talk(this IMouth mouth)
    {
        Console.WriteLine("Talking");
    }

    public static void Eat(this IMouth mouth)
    {
        Console.WriteLine("Eating");
    }
}

// The leg interface and extension method
public interface ILeg {}
public static class Leg
{
    public static void Walk(this ILeg leg)
    {
        Console.WriteLine("Walking");
    }

    public static void Kick(this ILeg leg)
    {
        Console.WriteLine("Kicking");
    }

    public static void Jump(this ILeg leg)
    {
        Console.WriteLine("Jumping");
    }
}

Unlike C++, C# cannot take an unknown class type as base class, hence Extension Methods seems to be the only way we know so far. However, the C# implementation offers some unique benefits that C++ does not have.

In our previous C++ examples in here, notice that our mixin classes have no knowledge of its base class, hence, they have no way to access base methods and variables. Basically, the Mouth and Leg in C++ always act on their own without control from the Son.

In C#, things get a little bit better. Due to the fact that our Son implements the IMouth and ILeg interfaces, the Extension Method can interface with the Son. Take for example the following code.

class Program
{
    static void Main(string[] args)
    {
        Son son = new Son();
        son.Eat(); // Chewing
        son.Talk(); // I Like Minced Beef
    }
}

public class Father { }
public class Son : Father, IMouth
{
    // Son implements the IMouth interface to give some access to the Mouth mixin
    private String mFood;
    public Son() { mFood = "Beef"; }
    public String food { get { return mFood; } set { mFood = value; } }
}

// the IMouth interface enforces the requirement for the food property
public interface IMouth
{
    String food { get; set; }
}
public static class Mouth
{
    // the food property is used and the value is provided
    // by the implementing class
    public static void Eat(this IMouth mouth)
    {
        Console.WriteLine("Chewing");
        mouth.food = String.Concat("Minced ", mouth.food);
    }

    public static void Talk(this IMouth mouth)
    {
        Console.WriteLine("I Like " + mouth.food);
    }
}

Now, not only our Son gets new abilities, our Son can also excercise control over its new abilities. “With great powers comes great responsibilities”!

Written by Jake

April 23rd, 2009 at 9:08 am