DevExpress GridControl 控件是经常会用到 加组 加行功能
扩展方法
public static class Tools
{
/// <summary>
/// 加组
/// </summary>
/// <param name="GroupFieldName">分组的数据源名称</param>
public static DevExpress.XtraGrid.GridControl AddGroup(this DevExpress.XtraGrid.GridControl _GridControl, string GroupFieldName)
{
DataTable _Dt = (DataTable)_GridControl.DataSource;
if (_Dt.Rows.Count <= 0)
{
ExtensionMethods.AddItem(_GridControl,GroupFieldName);
return _GridControl;
}
string GroupColumn = _Dt.Rows[_Dt.Rows.Count - 1][GroupFieldName].ToString();
if (GroupColumn == "")
{
_Dt.Rows[_Dt.Rows.Count - 1][GroupFieldName] = "0";
GroupColumn = "0";
}
DataRow _Dr = _Dt.NewRow();
_Dr[GroupFieldName] = GroupColumn.GetInt() + 1;
_Dt.Rows.Add(_Dr);
_GridControl.DataSource = _Dt;
_GridControl.RefreshDataSource();
if (_Dt.Rows.Count - 1 >= 0)
{
DevExpress.XtraGrid.Views.Grid.GridView _GridView = (DevExpress.XtraGrid.Views.Grid.GridView)_GridControl.MainView;
_GridView.OptionsNavigation.AutoFocusNewRow = true;
_GridView.SelectRow(_Dt.Rows.Count - 1);
}
return _GridControl;
}
/// <summary>
/// 为分组添加一行
/// 选中那行,添加到之后
/// </summary>
public static DevExpress.XtraGrid.GridControl AddItem(this DevExpress.XtraGrid.GridControl _GridControl, string GroupFieldName)
{
//判断选中的是哪个Tab,
DevExpress.XtraGrid.Views.Grid.GridView _GridView = (DevExpress.XtraGrid.Views.Grid.GridView)_GridControl.MainView;
int Selct = ((GridView)_GridControl.MainView).FocusedRowHandle;
int Index = Selct;
if (Selct > -2147483647 && Selct < 0)
{
bool IsGroup = _GridView.IsGroupRow(Selct);
if (IsGroup)
{
Index = _GridView.GetChildRowHandle(Selct, 0);
}
}
string GroupColumn = _GridView.GetRowCellValue(Index, GroupFieldName).GetString();
_GridView.SetRowCellValue(Index, GroupFieldName, GroupColumn == "" ? (GroupColumn = "0") : GroupColumn);
DataTable _Dt = (DataTable)_GridControl.DataSource;
DataRow _Dr = _Dt.NewRow();
_Dr[GroupFieldName] = GroupColumn == "" ? "0" : GroupColumn;
_Dt.Rows.Add(_Dr);
_GridControl.DataSource = _Dt;
_GridControl.RefreshDataSource();
_GridView.RefreshData();
if (Index >= 0)
{
_GridView.OptionsNavigation.AutoFocusNewRow = true;
_GridView.SelectRow(Index);
}
return _GridControl;
}
}
调用 加组
#region 加组
private void AddGroupButton_Click(object sender, EventArgs e)
{
try
{
_GridControl.AddGroup("GROUPING");
}
catch (Exception) { }
}
#endregion
调用 加行
#region 加行
private void AddItemButton_Click(object sender, EventArgs e)
{
try
{
_GridControl.AddItem("GROUPING");
}
catch (Exception) { }
}
#endregion