1. 程式人生 > >Dev GridControl

Dev GridControl

idv res for tty 無法 bind void type reat

(1)、gridView.AddNewRow()

(2)、實現 gridView_InitNewRow 事件

註:使用泛型集合綁定數據源,在GridView中實現自動添加行時,AddNewRow()方法不起效。在獲取數據行時,
GetDataRow()方法無法獲取數據,如果使用gridcontrol用於只呈現數據可以使用泛型集合作為數據源,如果涉及到增、刪、改建議使用
DataTable作為數據源,這樣以上兩個方法可以正常使用。

方法1(綁定DataTable作為數據源):

Step1:綁定數據源

  gridControl.DataSource=dataTable;

Step2:gridView_InitNewRow 事件

  DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
//DataRow dr = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
//初始化賦值
view.UpdateCurrentRow();

Step3:添加行觸發事件

  gridView.AddNewRow()

方法2(綁定List<T>作為數據源)

Step1:綁定數據源

  List<DepartmentInfo> source=GetDepartmentList();            //獲取泛型數據列表

  gridControl.DataSource=new BindingList<DepartmentInfo>(source);    //泛型類型轉換

Step2:gridView_InitNewRow 事件

  DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
//DataRow dr = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);

//初始化賦值
view.UpdateCurrentRow();

Step3:添加行觸發事件

  gridView.AddNewRow()

方法2初始化賦值優化:

//獲取類型默認值

public static object DefaultForType(Type targetType)
{
return targetType.IsValueType? Activator.CreateInstance(targetType) : null;
}

初始化--gridView_InitNewRow

private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
{
DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;

object destinationRow = gridView1.GetFocusedRow();
object sourceRow = gridView1.GetRow(0); //獲取數據源第一行作為模板原型
System.Reflection.PropertyInfo[] propertyCollection = sourceRow.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo propertyInfo in propertyCollection)
{
//獲取第一行數據
//object aa = sourceRow.GetType().GetProperty(propertyInfo.Name).GetValue(sourceRow, null);
object aa = DefaultForType(sourceRow.GetType());
destinationRow.GetType().GetProperty(propertyInfo.Name).SetValue(destinationRow, aa, null);

}

view.UpdateCurrentRow();
}

Dev GridControl