I am using a DataGrid to show the contents of an underlying DataTable,
generated at runtime (not bound to a database table or anything).
Everything works well when binding the DataColumn's of my table to
simple types, but I have problems binding a column to a custom class,
MyClass (see code below). The values of this column displays nicely (due
to th ToString method), but I am not able to modify the contents of the
column. All other columns are editable, and the underlying value of
objects in each cell are changed when I edit the cell value.
How do I make columns bound to custom classes editable???
Any help will be appreciated,
Ole Storm.
Code sample:
(...)
// Initializing the DataTable
DataTable dt = new DataTable("Table1");
dt.Columns.Add("First_Col", typeof(string));
dt.Columns.Add("Second_Col", typeof(int));
dt.Columns.Add("Thrid", typeof(double));
dt.Columns.Add("Fourth", typeof(System.DateTime));
DataColumn col = new DataColumn("Fifth", typeof(MyClass));
col.ReadOnly = false;
dt.Columns.Add(col);
Object[] obs = new Object[5]{"test", 2, 3.14, new DateTime(1969,5,5),
new MyClass("one")};
dt.Rows.Add(obs);
obs = new Object[5]{"abcdef", 17, 3.14*2.71, new DateTime(1967,6,26),
new MyClass("two")};
dt.Rows.Add(obs);
obs = new Object[5]{"defg", 37, 3.14*2.71, new DateTime(1967,6,26), new
MyClass("aaaabbb")};
dt.Rows.Add(obs);
DataView dv = new DataView(dt);
dv.AllowNew = false;
dv.AllowDelete = false;
dataGrid1.SetDataBinding(dv, "");
(...)
public struct MyClass : IComparable
{
private string s;
public MyClass(string a)
{
s=a+a;
}
public string Val
{
get
{
return s;
}
set
{
s=value;
}
}
public override string ToString()
{
return s;
}
#region IComparable Members
public int CompareTo(object obj)
{
if(obj is MyClass)
{
return this.s.Length.CompareTo(((MyClass)obj).s.Length);
}
else
throw new Exception("Incompatible objects");
return 0;
}
#endregion