需求:
1)很多时候我们需要的类属性并不能预先完全确定,而是需要用户自己定义,所以很多时候我们使用NOSQL数据库更合适;
2)某些列是通过计算得来的,不是绑定某些属性直接获取;
因此,我们的表格不能预先绑定类的各个属性。也就是说,列绑定的fieldname不一定在类中预先定义好,
gridView实现了一个定制函数可以实现对自定义列,在回调函数中,我们再设置数据。
步骤一、我们定义一个用户类,实现后期绑定若干个数据,数据使用键值对描述:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace testUnbound16
{
public class User
{
public String Id { set; get; }
public String Name {set; get; }
private Hashtable table = new Hashtable();
public Object GetClientProperty(String key)
{
return table[key];
}
public void SetClientPropery(String key, Object o)
{
table.Add(key, o);
}
}
}
步骤二、通过设计器为gridview绑定一个定制函数:
private void OnCustomUnboundDate(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
{
String key = e.Column.FieldName;
int index = e.ListSourceRowIndex;
User user = list[index];
if (e.IsGetData)
{
Object value1 = user.GetClientProperty(key);
e.Value = value1;
}
else
{
Object value1 = e.Value;
user.SetClientPropery(key, value1);
}
}
步骤三、修改列属性:
通过设计器或者直接写代码,如果是列需要用户设计并绑定,则需要代码来设置
this.gridColumn3.UnboundType = DevExpress.Data.UnboundColumnType.Object;
this.gridColumn4.UnboundType = DevExpress.Data.UnboundColumnType.Object;
this.gridColumn5.UnboundType = DevExpress.Data.UnboundColumnType.Object;
步骤四、我们添加一个列表,测试一下
List<User> list = new List<User>();
public Form1()
{
InitializeComponent();
this.gridColumn3.UnboundType = DevExpress.Data.UnboundColumnType.Object;
this.gridColumn4.UnboundType = DevExpress.Data.UnboundColumnType.Object;
this.gridColumn5.UnboundType = DevExpress.Data.UnboundColumnType.Object;
User user = new User();
user.Id = "2021";
user.Name = "robin";
user.SetClientPropery("Key1", "test1");
user.SetClientPropery("Key2", DateTime.Now);
user.SetClientPropery("Key3", 12345);
list.Add(user);
gridControl1.DataSource = list;
}
显示效果: