OL SDK:http://help.infragistics.com/
资料参考:http://blog.csdn.net/andy_212/article/details/4019895
http://blog.tianya.cn/blogger/post_show.asp?BlogID=1862414&PostID=17354963
-----------------------------------------------------------------------------------------------------------
术语:
persist——持续化(保存) property——属性
attribute 特性 setting——设置 Band——数据条带
一、UltraGrid 的基本概念
UltraGrid的属性设计和一般的控件颇为不同。理解其设计思想,有助于你从其浩瀚的属性中快速找到你所需要的东西。在此文中 WinGrid, UltraGrid, UltraWinGrid 是同一个东西。
WinGrid
是一个可展示层级数据的网格控件
数据源实现 IList 或 ITypedList 接口就可以展示(但不一定可以增删)
可展现具有层级关系的数据,如 customers - orders - order details
WinGrid 功能:
· 排序
· 过滤
· 统计
· 行列大小调整
· 冻结列和冻结行
· 列托拽调整位置
· 列互换位置
· 分割视图
· Outlook风格的BroupBy功能(用户可将列拖到分组栏中对数据进行分组)
· 卡片视图
· 数据行的自定义布局
· 单元格可使用多种编辑控件
· 导出到Excel
· 打印
· 其它Infragistics Presentation Layer Framework 的公共特性,如:Apperances, DrawFilters, CreationFilters
WinGrid 数据条带和层级数据
UltraGrid 可表现具有层级关系的数据
每个层级的数据用一个 band(数据条带)来描述
每个 band 具有若干的 column 和 row,类似 DataTable
层级间的关系用外键关联来描述
WinGrid 的外观样式方案
(1)使用 Appearance 对象控制控件的外观和样式
设置 WinGrid 控件的外观
· 并不直接设置其字体背景颜色等属性
· 而是创建或者选择现有的 Appearance 对象(类似Web的css class样式)
· 该 Appearance 对象拥有多种格式相关的属性,如对齐方式、字体、颜色、图像和alpha融合信息
该方式有以下好处:
· 缩减了代码的数量
· 便于控制统一的外观,只需要改 Appearance 对象就可以了
· 对于 Grid 这样具有众多子元素的控件,使用此方式设置外观可有效减少内存消耗
(2)其布局和外观是可持续化保存的
UltraGrid.DisplayLayout 属性(UltraGridLayout类)作为所有可持续化保存的特性和对象的容器
调用该对象的 Load(), Save(), LoadFromXml(), SaveAsXml() 函数可存取外观控制
由于大部分UltraGrid的设置都可以持续化,所以大部分的功能都是通过UltraGridLayout对象进行设置的
(3)样式是可从上级控件继承和重载的
若控件设置其 Appearance 为 Default,该控件将会继承其父控件的样式设置(而不是什么缺省值)
如缺省状态下,cell 使用row的背景色,而row使用band的背景色
Band 对象默认继承上级对象的样式,而使用Override 属性(UltraGridOverride 类)来设置其特殊属性
WinGrid 决定绘制一个对象的外观和行为时
· 先检查该对象的Override属性
· 若该属性内的值被明确修改(非Default),则使用该值
· 否则使用上级对象相应的值(Default)
大部分的属性即可以直接在WinGrid设置,也可以在Band设置,后者会覆盖前者
// 例:默认只能单行选择,而 orders band 允许选择多行
using Infragistics.Win.UltraWinGrid;
UltraGrid1.DisplayLayout.Override.SelectTypeRow = SelectType.Single;
UltraGrid1.DisplayLayout.Bands["Orders"].Override.SelectTypeRow = SelectType.Extended;
卡片视图(Card View)
每条记录用一张卡片来展示,类似表单视图
卡片视图的限制
只能展现最底层的band数据,无法再展示其子层的数据
无法增加新记录?
设置方法
grid.Band[0].CardView = true;
grid.Band[0].CardSettings..... 样式设置
分组视图(GroupBy View)
类似outlook 2007,可将列拖到分组栏中,让数据分组展示
操作方法:
grid.DisplayLayout.ViewStyleBand = ViewStyleBand.OutlookGroupBy;
二、 UltraGrid 设计器操作
UltraWinGrid Designer(UltraGrid设计器项目)
Basic Settings :
Data Schema : 设置绑定列的数据格式
Presets : 从预设中选择一个样式,有三种类型:(1)仅与外观相关;(2)仅与行为相关;(3)两者都有
Manage Presets : 预设管理和设置
Feature Picker : 配置功能。详见后
Appearance Browser : 定制的一些外观样式
Band and Column Settings : 要展示数据集和列设置
Band[0] - ‘Band 0‘ :
Columns : 展示列设置:Data Schema中定义绑定列,非绑定列
Column Arrangement Overview : 列展示位置设置(类似报表设计器)
Column Arrangement Designer : 分两种:Row layout(可用于复杂表头设置), Group and levels
Control Settings : 控件所有的属性设置。其实上面的所有设置都可以在这里找到,只是层次深不易找。详见下。
Feature Picker(UltraGrid功能设置)
AutoFit Style : 列自动适应宽度
CardView : 卡片视图
Column Moving : 列是否可拖动位置
Column Sizing : 列调整宽度的方式
Column Swapping : 是否允许列交换位置
Empty Rows : 是否展示空行,空行的样式
Filtering : 列过滤器
Fixed Headers : 冻结列
Fixed Rows : 冻结行
Header Click Sort Action : 标题列点击排序方式:单列排序 & 多列方式
IDataErrorInfo Support : 数据错误验证方式
Merged Cell : 合并单元格
Outlook Group By : Outlook Group 风格(可由用户定制数据分组)
Row Selectors : 行选择符号(一个小箭头)
Row Siziing : 行调整高度的方式
Scrolling : 滚动条样式
Selection : 行列单元格选择方式
Summaries : 统计单元格
Updating : 是否允许数据行增删改
Control Setting(UltraGrid控件设置·特有属性)
Appearance
Behavior
Data
Design
Layout
DiaplayLayout
AddNewBox
AutoFitStyle
Bands
EnmptyRowSettings
Override
AllowAddNew
AllowDelete
AllowUpdate
RowSizing
ViewStyle : SingleBand | MultiBand
杂项
常用操作
添加Column: Start/Basic Settings/Data Schema/Manually Define a Schema/添加Column,命名用数据库中的字段名。
添加Column Title: Band and Column Settings/Band [0](手动添加Column后)/Columns/选择列/Header/修改Caption属性
排序:Picker/Filtring/Allow
分组:Picker/OutLook GroupBy/Active
编辑:Picker/Update
多行表头:Column Arrangement Designer/Add Group/Add Level/把相应的列拖到组下面,
隐藏列:Column Arrangement Designer/Show Hide
单列不可编辑:Band[0]/Column/cellactivation 设置成NoEdit
单击单元格选择状态:Band[0]/Column/CellClickAction
单元格编辑控件:Band[0]/Column/EditorControl
单元格合并:Band[0]/Column/MergedCell。。。
冻结列:Picker/Fixed Header
三、UltraGrid 外观控制
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ Grid ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
动态转载样式文件
this.ultraGrid1.ApplyPresetFromXml(@"C:/Program Files/Common Files/Infragistics" +
@"/Presets/Win/UltraGridBase/Standard/FlatGreen.xml", true);
存取布局文件(可用这玩意设计报表,动态载入)
this.ultraGrid1.DisplayLayout.SaveAsXml("WinGridLayout.xml");
this.ultraGrid1.DisplayLayout.LoadFromXml(System.IO.Path.Combine(Application.StartupPath,
@"http://www.cnblogs.com/ExtraFiles/WinGridLayout.xml"));
使用Appearance(类似预定义的样式)
this.ultraGrid1.DisplayLayout.Appearances.Add("Highlighted" );
this.ultraGrid1.DisplayLayout.Appearances["Highlighted" ].BackColor = Color.Red;
this.ultraGrid1.DisplayLayout.Appearances["Highlighted" ].BackColor = Color.White;
或者直接给预设Appearance赋值
this.ultraGrid1.DisplayLayout.Override.ActiveRowAppearance.ForeColor = Color.White;
使用操作系统样式
this.ultraGrid1.UseOsThemes = DefaultableBoolean.True;
HotTrack
this.ultraGrid1.DisplayLayout.Override.HotTrackCellAppearance.BackColor = Color.Blue;
this.ultraGrid1.DisplayLayout.Override.HotTrackRowCellAppearance.BackColor =
Color.Yellow;
this.ultraGrid1.DisplayLayout.Override.HotTrackHeaderAppearance.BackColor =
Color.Blue;
this.ultraGrid1.DisplayLayout.Override.HotTrackRowAppearance.ForeColor =
Color.LightGreen;
this.ultraGrid1.DisplayLayout.Override.HotTrackRowSelectorAppearance.BackColor =
Color.Green;
分割滚动视图
设置分割视图(创建SplitBar)
this.ultraGrid1.DisplayLayout.ColScrollRegions[0].Split(0);
this.ultraGrid1.DisplayLayout.RowScrollRegions[0].Split(200);
取消分割视图
this.ultraGrid1.DisplayLayout.MaxColScrollRegions = 1;
this.ultraGrid1.DisplayLayout.MaxRowScrollRegions = 1;
修改Tab键功能
this.ultraGrid1.DisplayLayout.TabNavigation = TabNavigation.NextControl;
TabletPC Ink-Enable
将UltraInkProvider 组件拖到窗体上就可以了
编辑状态的输入框右侧会显示一个小笔按钮,点击后就会弹出手写输入框
若要在非TabletPC上使用该功能,需要安装TabletPC SDK
定义和应用外观样式
this.ultraGrid1.DisplayLayout.Appearances.Add("Highlighted");
this.ultraGrid1.DisplayLayout.Appearances["Highlighted"].BackColor = Color.Red;
this.ultraGrid1.DisplayLayout.Appearances["Highlighted"].BackColor = Color.White;
this.ultraGrid1.DisplayLayout.Override.ActiveRowAppearance =
this.ultraGrid1.DisplayLayout.Appearances["Highlighted"];
this.ultraGrid1.DisplayLayout.Override.RowSelectorAppearance =
this.ultraGrid1.DisplayLayout.Appearances["Highlighted"];
--------------------------
this.ultraGrid1.DisplayLayout.Override.ActiveRowAppearance.BackColor = Color.Red;
this.ultraGrid1.DisplayLayout.Override.ActiveRowAppearance.ForeColor = Color.White;
this.ultraGrid1.DisplayLayout.Override.RowSelectorAppearance.BackColor = Color.Red;
this.ultraGrid1.DisplayLayout.Override.RowSelectorAppearance.ForeColor = Color.White;
GroupBy 视图
this.ultraGrid1.DisplayLayout.ViewStyleBand = ViewStyleBand.OutlookGroupBy;
this.ultraGrid1.DisplayLayout.Bands[0].SortedColumns.Add("Country", false, true);
this.ultraGrid1.DisplayLayout.Bands[0].SortedColumns.Add("City", false, true);
-------------------------------------------------------
this.ultraGrid1.DisplayLayout.ViewStyleBand = ViewStyleBand.OutlookGroupBy;
this.ultraGrid1.DisplayLayout.GroupByBox.Style = GroupByBoxStyle.Compact;
this.ultraGrid1.DisplayLayout.GroupByBox.Appearance.BackColor = Color.White;
this.ultraGrid1.DisplayLayout.GroupByBox.Prompt = "Drag and drop a column to group by
that column.";
this.ultraGrid1.DisplayLayout.GroupByBox.PromptAppearance.ForeColor = Color.Maroon;
this.ultraGrid1.DisplayLayout.GroupByBox.BorderStyle = UIElementBorderStyle.InsetSoft;
this.ultraGrid1.DisplayLayout.GroupByBox.ButtonBorderStyle =
UIElementBorderStyle.RaisedSoft;
this.ultraGrid1.DisplayLayout.GroupByBox.ShowBandLabels = ShowBandLabels.All;
this.ultraGrid1.DisplayLayout.GroupByBox.BandLabelBorderStyle =
UIElementBorderStyle.Solid;
this.ultraGrid1.DisplayLayout.GroupByBox.BandLabelAppearance.BackColor = Color.DarkBlue;
this.ultraGrid1.DisplayLayout.GroupByBox.BandLabelAppearance.ForeColor =
Color.LightYellow;
this.ultraGrid1.DisplayLayout.GroupByBox.ButtonConnectorStyle =
UIElementBorderStyle.Dotted;
this.ultraGrid1.DisplayLayout.GroupByBox.ButtonConnectorColor = Color.Maroon;
卡片视图
grid.Band[0].CardView = true;
grid.Band[0].CardSettings..... 样式设置
展开所有行(子行)
this.ultraGrid1.Rows.ExpandAll(true);
数据过滤器
示例
e.Layout.Override.AllowRowFiltering = DefaultableBoolean.True;
e.Layout.Override.RowFilterAction = RowFilterAction.AppearancesOnly;
e.Layout.Override.FilteredInCellAppearance.ForeColor = Color.DarkGreen;
e.Layout.Override.FilteredOutCellAppearance.ForeColor = Color.DarkRed;
打开过滤器
this.ultraGrid1.DisplayLayout.Override.AllowRowFiltering = DefaultableBoolean.True;
设置过滤器功能
this.ultraGrid1.DisplayLayout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
this.ultraGrid1.DisplayLayout.Override.FilterUIType = FilterUIType.FilterRow;
this.ultraGrid1.DisplayLayout.Override.FilterEvaluationTrigger =
FilterEvaluationTrigger.OnLeaveCell;
this.ultraGrid1.DisplayLayout.Override.FilterOperatorDefaultValue =
FilterOperatorDefaultValue.DoesNotContain;
this.ultraGrid1.DisplayLayout.Override.FilterOperandStyle =
FilterOperandStyle.DropDownList;
this.ultraGrid1.DisplayLayout.Override.FilterOperatorLocation =
FilterOperatorLocation.WithOperand;
this.ultraGrid1.DisplayLayout.Override.FilterOperatorDropDownItems =
FilterOperatorDropDownItems.All;
this.ultraGrid1.DisplayLayout.Override.FilterClearButtonLocation =
FilterClearButtonLocation.Row;
this.ultraGrid1.DisplayLayout.Override.FilterRowPrompt = "Click here to filter
rows...";
this.ultraGrid1.DisplayLayout.Bands[0].SpecialRowPromptField = "Address";
the LogicalOperator property of the ColumnFiltersCollection object.
外观
ultraGrid1.DisplayLayout.Override.FilterRowAppearance
ultraGrid1.DisplayLayout.Override.FilterRowAppearanceActive
ultraGrid1.DisplayLayout.Override.FilterCellAppearance
ultraGrid1.DisplayLayout.Override.FilterRowSelectorAppearance
自定义过滤规则
UltraGridBand band = this.ultraGrid1.DisplayLayout.Bands[2];
band.ColumnFilters["Unit Price"].FilterConditions.Clear( );
band.ColumnFilters["Unit Price"].FilterConditions.Add(
FilterComparisionOperator.GreaterThan, 5 );
band.ColumnFilters["Unit Price"].FilterConditions.Add(
FilterComparisionOperator.LessThan, 10 );
band.ColumnFilters["Unit Price"].LogicalOperator = FilterLogicalOperator.And;
数据错误提示
this.ultraGrid1.DisplayLayout.Override.SupportDataErrorInfo =
SupportDataErrorInfo.RowsAndCells;
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].SupportDataErrorInfo =
DefaultableBoolean.False;
this.ultraGrid1.DisplayLayout.Override.DataErrorCellAppearance.BackColor = Color.Red;
this.ultraGrid1.DisplayLayout.Override.DataErrorRowSelectorAppearance.BackColor =
Color.Red;
this.ultraGrid1.DisplayLayout.Override.DataErrorRowAppearance.BackColor =
Color.LightYellow;
private void ultraGrid1_InitializeRow(object sender, InitializeRowEventArgs e)
{
string rowError = "";
string cellError = "";
Object value = e.Row.Cells["Fax"].Value;
// Set the data error if Fax column value is empty
if(DBNull.Value == value)
{
rowError = "Row contains errors.";
cellError = "Fax can not be empty";
}
DataRowView drv = (DataRowView)e.Row.ListObject;
drv.Row.RowError = rowError;
drv.Row.SetColumnError("Fax", cellError);
}
Tooltip
SummarySettings averageSummary =
e.Layout.Bands[0].Summaries.Add(
"GradeAverage",
SummaryType.Average,
e.Layout.Bands[0].Columns["Grade"] );
averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
averageSummary.DisplayFormat = "Average: {0:.##}";
averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
----------------------------------------
SummarySettings summary =
this.ultraGrid1.DisplayLayout.Bands[0].Summaries.Add(
"sum",
SummaryType.Sum,
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0],
SummaryPosition.UseSummaryPositionColumn );
summary.ToolTipText = string.Format( "Sum of column {0}.",
summary.SourceColumn.Header.Caption );
this.ultraGrid1.Rows.SummaryValues[ "sum" ].ToolTipText = string.Format( "Sum of
column {0}.", summary.SourceColumn.Header.Caption );
AlphaBend
if(this.chkRowAlpha.Checked == true)
{
this.ultraGrid1.DisplayLayout.Override.RowAppearance.BackColorAlpha =
Alpha.UseAlphaLevel;
this.ultraGrid1.DisplayLayout.Override.RowAppearance.AlphaLevel =
short.Parse(this.spnAlphaLevel.Value.ToString());
}
else
{
this.ultraGrid1.DisplayLayout.Override.RowAppearance.BackColorAlpha =
Alpha.Opaque;
this.ultraGrid1.DisplayLayout.Override.RowAppearance.AlphaLevel = 0;
}
------------------------------------------
if (chEnableAlphaBlending.Checked)
{
this.ultraGrid1.DisplayLayout.Appearance.ImageBackground =
Image.FromFile(clsSamplesPath.GraphicsPath + "//Backgrounds//nasa_saturn_montage.jpg");
this.ultraGrid1.DisplayLayout.Appearance.ImageBackgroundOrigin =
Infragistics.Win.ImageBackgroundOrigin.Form;
this.ultraGrid1.DisplayLayout.Appearance.ImageBackgroundStyle =
Infragistics.Win.ImageBackgroundStyle.Tiled;
this.ultraGrid1.AlphaBlendMode = Infragistics.Win.AlphaBlendMode.Optimized;
}
else
{
this.ultraGrid1.AlphaBlendMode = Infragistics.Win.AlphaBlendMode.Disabled;
this.ultraGrid1.DisplayLayout.Appearance.ImageBackground = null;
}
显隐标题
if (chShowCaption.Checked == true)
this.ultraGrid1.Text = "UltraWinGrid CardView Sample";
else
this.ultraGrid1.Text = "";
边框显示
ug.DisplayLayout.BorderStyle = Infragistics.Win.UIElementBorderStyle.Solid;
背景色
ug.DisplayLayout.Appearance.BackColor = Color.White;
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ Band ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
设置数据条带退格宽度
this.ultraGrid1.DisplayLayout.Bands[1].Indentation = 100;
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ Caption ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
表格标题(Caption)
this.ultraGrid1.DisplayLayout.CaptionVisible = DefaultableBoolean.True;
标题
ug.DisplayLayout.CaptionAppearance.TextHAlign = Infragistics.Win.HAlign.Left;
ug.DisplayLayout.CaptionAppearance.BackColor = Color.LightSteelBlue;
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ Head ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
控制标题行的位置
// RepeatOnBreak, FixedOnTop, OncePerRowIsland, OncePerGroupedRowIsland
e.Layout.Override.HeaderPlacement = HeaderPlacement.OncePerGroupedRowIsland;
e.Layout.Bands[0].Override.HeaderPlacement = HeaderPlacement.FixedOnTop;
标题换行展示
this.ultraGrid1.DisplayLayout.Override.WrapHeaderText = true;
Header置顶不动
设置displaylayout中的stationarymargins
标题行样式
this.ultraGrid1.DisplayLayout.Override.AllowColSizing = AllowColSizing.Free;
this.ultraGrid1.DisplayLayout.Bands[0].HeaderVisible = true;
this.ultraGrid1.DisplayLayout.Bands[1].HeaderVisible = true;
this.ultraGrid1.DisplayLayout.Bands[1].Header.Caption = "Orders";
this.ultraGrid1.DisplayLayout.Bands[0].Indentation = 0;
this.ultraGrid1.DisplayLayout.Bands[1].Indentation = 0;
this.ultraGrid1.DisplayLayout.RowConnectorStyle = RowConnectorStyle.None;
this.ultraGrid1.DisplayLayout.Bands[0].Header.Appearance.ThemedElementAlpha =
Alpha.Transparent;
this.ultraGrid1.DisplayLayout.Bands[0].Header.Appearance.BackColor =
SystemColors.ActiveCaption;
this.ultraGrid1.DisplayLayout.Bands[0].Header.Appearance.ForeColor =
SystemColors.ActiveCaptionText;
this.ultraGrid1.DisplayLayout.Bands[1].Header.Appearance.ThemedElementAlpha =
Alpha.Transparent;
this.ultraGrid1.DisplayLayout.Bands[1].Header.Appearance.BackColor = Color.Blue;
this.ultraGrid1.DisplayLayout.Bands[1].Header.Appearance.BackColor2 = Color.Red;
this.ultraGrid1.DisplayLayout.Bands[1].Header.Appearance.ForeColor = Color.White;
this.ultraGrid1.DisplayLayout.Bands[1].Header.Appearance.BackGradientStyle =
GradientStyle.Horizontal;
隐藏标题行
this.UltraGrid1.Text = "";
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ Row ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
行选择方式
e.Layout.Override.SelectTypeRow = SelectType.Single;
e.DisplayLayout.Bands["Orders"].Override.SelectTypeRow = SelectType.Extended;
e.Layout.Override.CellClickAction = CellClickAction.RowSelect;
选择行样式
ug.DisplayLayout.Override.SelectedRowAppearance.BackColor = Color.SteelBlue;
交错行样式
this.ultraGrid1.DisplayLayout.Override.RowAlternateAppearance.BackColor = Color.Red;
激活行样式
this.ultraGrid1.DisplayLayout.Override.ActiveRowAppearance.BackColor = Color.Red;
ug.DisplayLayout.Override.ActiveRowAppearance.BackColor = Color.SteelBlue;
添加行操作提示
private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
this.ultraGrid1.DisplayLayout.Bands[0].AutoPreviewEnabled = true;
}
private void ultraGrid1_InitializeRow(object sender, InitializeRowEventArgs e)
{
e.Row.Description = "Row Description";
}
private void ultraGrid1_AfterRowInsert(object sender, RowEventArgs e)
{
this.ultraGrid1.DisplayLayout.ActiveRow.Description =
"Data changed in this row will not be added to the database" +
" until you press the Update button.";
}
行渐变背景
UltraGridRow objRow = this.ultraGrid1.Rows[10];
this.ultraGrid1.ActiveRow = objRow;
this.ultraGrid1.Rows[10].Appearance.BackColor2 = Color.Blue;
this.ultraGrid1.Rows[10].Appearance.BackGradientStyle = GradientStyle.Circular;
修改特殊行的位置
新增行
this.ultraGrid1.DisplayLayout.Override.AllowAddNew = AllowAddNew.TemplateOnTop;
this.ultraGrid1.DisplayLayout.Override.SequenceFixedAddRow = 2;
过滤行
this.ultraGrid1.DisplayLayout.Override.AllowRowFiltering = DefaultableBoolean.True;
this.ultraGrid1.DisplayLayout.Override.FilterUIType = FilterUIType.FilterRow;
this.ultraGrid1.DisplayLayout.Override.SequenceFilterRow = 1;
统计行
this.ultraGrid1.DisplayLayout.Override.AllowRowSummaries = AllowRowSummaries.True;
this.ultraGrid1.DisplayLayout.Override.SummaryDisplayArea = SummaryDisplayAreas.Top;
this.ultraGrid1.DisplayLayout.Override.SequenceSummaryRow = 3;
行高度调整
e.Layout.Override.DefaultRowHeight = 60;
e.Layout.Override.RowSizing = RowSizing.Free;
this.ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.Free;
行布局(将列分组展示)
ultraGrid1.DisplayLayout.Bands[0].Groups.Add("Name");
ultraGrid1.DisplayLayout.Bands[0].Groups.Add("Address");
ultraGrid1.DisplayLayout.Bands[0].Groups.Add("Phone");
ultraGrid1.DisplayLayout.Bands[0].Columns["CompanyName"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Name"];
ultraGrid1.DisplayLayout.Bands[0].Columns["ContactName"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Name"];
ultraGrid1.DisplayLayout.Bands[0].Columns["ContactTitle"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Name"];
ultraGrid1.DisplayLayout.Bands[0].Columns["CustomerID"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Name"];
ultraGrid1.DisplayLayout.Bands[0].Columns["Address"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Address"];
ultraGrid1.DisplayLayout.Bands[0].Columns["Country"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Address"];
ultraGrid1.DisplayLayout.Bands[0].Columns["City"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Address"];
ultraGrid1.DisplayLayout.Bands[0].Columns["Region"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Address"];
ultraGrid1.DisplayLayout.Bands[0].Columns["PostalCode"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Address"];
ultraGrid1.DisplayLayout.Bands[0].Columns["Phone"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Phone"];
ultraGrid1.DisplayLayout.Bands[0].Columns["Fax"].Group =
ultraGrid1.DisplayLayout.Bands[0].Groups["Phone"];
ultraGrid1.DisplayLayout.Bands[0].LevelCount = 2;
ultraGrid1.DisplayLayout.Bands[0].Columns["City"].Level = 1;
ultraGrid1.DisplayLayout.Bands[0].Columns["Country"].Level = 1;
ultraGrid1.DisplayLayout.Bands[0].Columns["PostalCode"].Level = 1;
ultraGrid1.DisplayLayout.Bands[0].Columns["Fax"].Level = 1;
冻结行
this.ultraGrid1.DisplayLayout.Override.FixedRowStyle = FixedRowStyle.Top;
this.ultraGrid1.Rows.FixedRows.Add(this.ultraGrid1.Rows[0]);
this.ultraGrid1.Rows[0].Fixed = true;
this.ultraGrid1.DisplayLayout.Override.FixedRowIndicator = FixedRowIndicator.Button;
FixedRowAppearance
FixedRowCellAppearance
FixedRowSelectorAppearance
统计行
this.ultraGrid1.DisplayLayout.Override.AllowRowSummaries = AllowRowSummaries.True;
this.ultraGrid1.DisplayLayout.Override.SummaryDisplayArea =
SummaryDisplayAreas.GroupByRowsFooter | SummaryDisplayAreas.TopFixed;
------------------------------------------------------
this.ultraGrid1.DisplayLayout.Bands[0].Summaries.Add(
SummaryType.Minimum,
null,
this.ultraGrid1.DisplayLayout.Bands[0].Columns["Country"],
SummaryPosition.Left,
null
);
this.ultraGrid1.DisplayLayout.Bands[0].Summaries[0].SummaryPosition =
SummaryPosition.Center;
this.ultraGrid1.DisplayLayout.Bands[0].SummaryFooterCaption = "My Sums";
行首显示行号(行选择器)
e.Layout.Override.RowSelectors = DefaultableBoolean.True;
e.Layout.Override.RowSelectorNumberStyle = RowSelectorNumberStyle.VisibleIndex;
e.Layout.Override.RowSelectorWidth = 30;
选中行
this.ultraGrid1.Rows[i].Selected = true;
激活行
this.ultraGrid1.Rows[i].Activate();
this.ultraGrid1.ActiveRow = this.ultraGrid1.Rows[5];
this.ultraGrid1.DisplayLayout.Override.ActiveRowAppearance.BackColor = Color.Aqua;
this.ultraGrid1.ActiveCell = this.ultraGrid1.ActiveRow.Cells["CompanyName"];
遍历行
// 定位到首行
UltraGridRow aRow = this.ultraGrid1.GetRow(ChildRow.First);
// 搜索后继行
if(aRow.HasNextSibling())
{
UltraGridRow NextRow = aRow.GetSibling(SiblingRow.Next);
MessageBox.Show("Has Siblings");
}
// 搜索子行
if(aRow.HasChild())
{
UltraGridRow childRow = aRow.GetChild(Infragistics.Win.UltraWinGrid.ChildRow.First);
MessageBox.Show("Has a Child");
}
判断总行数
this.ultraGrid1.Rows.Count
特殊行外观设置
this.ultraGrid1.DisplayLayout.Override.SpecialRowSeparator =
SpecialRowSeparator.FixedRows;
this.ultraGrid1.DisplayLayout.Override.SpecialRowSeparatorHeight = 25;
this.ultraGrid1.DisplayLayout.Override.BorderStyleSpecialRowSeparator =
UIElementBorderStyle.Dashed;
隐藏行分隔线
e.Layout.Reset();
e.Layout.Override.CellAppearance.BorderAlpha = Alpha.Transparent;
e.Layout.Override.RowAppearance.BorderColor = Color.White;
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ Column ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
UltraGrid内置支持的列编辑类型
Default 缺省类型
Edit 文本框
EditButton 按钮文本框
CheckBox 复选框
TriStateCheckBox 三态复选框
DropDown 组合框(可编辑)
DropDownList 下拉框(只选)
DropDownValidate 组合框(只可输入列表中的数据)
Button 按钮。点击时触发 ClickCellButton 事件
DropDownCalendar 下拉日历控件
Date 日期输入、下拉日历组合控件。可设置 MinValue 和 MaxValue,并对
输入进行掩码校验
DateWithoutDropDown 日期输入
DateWithSpin 类似Date控件,但用spin按钮取代了下拉日历控件
DateTime 日期时间输入控件
DateTimeWithoutDropDown 日期时间输入控件,但取消了下拉按钮
DateTimeWithSpin 日期时间输入控件,使用spin按钮替代下拉按钮
Color 色彩选择
Currency 金额,可修改 MaskInput 属性定制mask
CurrencyNonNegative 金额,不允许负数
CurrencyPositive 金额,只允许正数
Double double。可用 NumberFormatInfo 设置掩码,用 MinValue MaxValue
限制范围
DoubleWithSpin double + spin
DoubleNonNegative double 非负
DoubleNonNegativeWithSpin double 非负 spin
DoublePositive double 正数
DoublePositiveWithSpin double 正数 spin
Font 字体选择框
Image 图像展示(EmbeddableImageRenderer)
ImageWithShadow 图像,阴影效果
Integer 整数
IntegerWithSpin 整数,spin
IntegerPositive 整数,正数
IntegerPositiveWithSpin 整数,正数,spin
IntegerNonNegative 整数,非负
IntegerNonNegativeWithSpin 整数,非负,spin
Time 时间(可用MaskInput 设置掩码,用 Minimum 和 maximum 设置范围
)
TimeWithSpin 时间,spin
TimeZone 时区
URL URL(FormattedLinkEditor)
FormattedText 带格式的文本(FormattedLinkEditor)
设置列编辑类型示例
button
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].Style = ColumnStyle.Button;
checkbox
this.ultraGrid1.DisplayLayout.Bands[0].Columns.Add("CheckBoxColumn");
this.ultraGrid1.DisplayLayout.Bands[0].Columns["CheckBoxColumn"].DataType = typeof
(bool);
this.ultraGrid1.DisplayLayout.Bands[0].Columns["CheckBoxColumn"].Style =
ColumnStyle.CheckBox;
dropdownlist
this.ultraGrid1.DisplayLayout.ValueLists.Add("List1");
this.ultraGrid1.DisplayLayout.ValueLists["List1"].ValueListItems.Add(1, "One");
this.ultraGrid1.DisplayLayout.ValueLists["List1"].ValueListItems.Add(2, "Two");
this.ultraGrid1.DisplayLayout.ValueLists["List1"].ValueListItems.Add(3, "Three");
this.ultraGrid1.DisplayLayout.ValueLists["List1"].DisplayStyle =
ValueListDisplayStyle.DisplayText;
this.ultraGrid1.DisplayLayout.Bands[0].Columns[2].Style = ColumnStyle.DropDownList;
this.ultraGrid1.DisplayLayout.Bands[0].Columns[2].ValueList =
this.ultraGrid1.DisplayLayout.ValueLists["List1"];
手工设置单元格编辑控件
EmbeddableEditorBase editor = null;
DefaultEditorOwnerSettings editorSettings = new DefaultEditorOwnerSettings( );
---------------------------------------
EditorWithText
editorSettings.DataType = typeof( string );
editor = new EditorWithText( new DefaultEditorOwner( editorSettings ) );
ColorPickerEditor
editorSettings.DataType = typeof( Color );
editor = new ColorPickerEditor( new DefaultEditorOwner( editorSettings ) );
FontNameEditor
valueList = new ValueList( );
editorSettings.DataType = typeof( string );
for ( int i = 0; i < System.Drawing.FontFamily.Families.Length; i++ )
valueList.ValueListItems.Add( System.Drawing.FontFamily.Families[i].Name );
editorSettings.ValueList = valueList;
editor = new FontNameEditor( new DefaultEditorOwner( editorSettings ) );
---------------------------------------
EditorWithMarsk (Currency)
editorSettings.DataType = typeof( decimal );
editor = new EditorWithMask( new DefaultEditorOwner( editorSettings ) );
editorSettings.MaskInput = "$ -nn,nnn,nnn.nn";
EditorWithMask (double)
editorSettings.DataType = typeof( double );
editorSettings.MaskInput = "-nnnnnnnn.nnnn";
editor = new EditorWithMask( new DefaultEditorOwner( editorSettings ) );
EditorWithMask(integers)
editorSettings.DataType = typeof( int );
editor = new EditorWithMask( new DefaultEditorOwner( editorSettings ) );
editorSettings.MaskInput = "-nnnnnnnn";
EditorWithMask(IPv4)
editorSettings.DataType = typeof( string );
editor = new EditorWithMask( new DefaultEditorOwner( editorSettings ) );
editorSettings.MaskInput = "nnn//.nnn//.nnn//.nnn";
EditorWithMask(phone numbers)
editorSettings.DataType = typeof( string );
editor = new EditorWithMask( new DefaultEditorOwner( editorSettings ) );
editorSettings.MaskInput = "(###) ###-####";
EditorWithMask (hh:mms:ss tt)
editorSettings.DataType = typeof( DateTime );
editorSettings.MaskInput = "hh:mm:ss tt";
editor = new EditorWithMask( new DefaultEditorOwner( editorSettings ) );
---------------------------------------
EditorWithCombo (Yes No dropdownlist)
editorSettings.DataType = typeof( bool );
valueList = new ValueList( );
valueList.ValueListItems.Add( true, "Yes" );
valueList.ValueListItems.Add( false, "No" );
editorSettings.ValueList = valueList;
editor = new EditorWithCombo( new DefaultEditorOwner( editorSettings ) );
EditorWithCombo (using ValueList)
valueList = new ValueList( );
valueList.ValueListItems.Add( 0, "Zero" );
valueList.ValueListItems.Add( 1, "One" );
valueList.ValueListItems.Add( 2, "Two" );
valueList.ValueListItems.Add( 3, "Three" );
valueList.ValueListItems.Add( 4, "Four" );
valueList.ValueListItems.Add( 5, "Five" );
editorSettings.ValueList = valueList;
editorSettings.DataType = typeof( int );
editor = new EditorWithCombo( new DefaultEditorOwner( editorSettings ) );
EditorWithCombo (using UltraDropDown)
// UltraDropDown : IValueList
UltraDropDown dropDown = new UltraDropDown();
dropDown.Visible = false;
dropDown.DataSource = new Record[]{
new Record("Cust 1"),
new Record("Cust 2"),
new Record("Cust 3"),
new Record("Cust 4")
};
dropDown.ValueMember = "ID"; // Cell values of this column are used as data.
dropDown.DisplayMember = "Data"; // Cell values of this column are dispalyed in the
cells.
dropDown.DisplayLayout.Override.CellAppearance.BackColor = Color.LightYellow;
dropDown.DisplayLayout.Override.CellAppearance.BackColor2 = Color.Yellow;
dropDown.DisplayLayout.Override.CellAppearance.BackGradientStyle =
GradientStyle.ForwardDiagonal;
this.Controls.Add(dropDown);
//
editorSettings.ValueList = dropDown;
editorSettings.DataType = typeof( int );
editor = new EditorWithCombo( new DefaultEditorOwner( editorSettings ) );
---------------------------------------
OptionSetEditor
editorSettings.DataType = typeof( bool );
valueList = new ValueList( );
valueList.ValueListItems.Add( true, "Yes" );
valueList.ValueListItems.Add( false, "No" );
editorSettings.ValueList = valueList;
editor = new OptionSetEditor( new DefaultEditorOwner( editorSettings ) );
---------------------------------------
CheckEditor
editorSettings.DataType = typeof( bool );
editor = new CheckEditor( new DefaultEditorOwner( editorSettings ) );
CheckEditor (ThreeState)
editorSettings.DataType = typeof( bool );
editor = new CheckEditor( new DefaultEditorOwner( editorSettings ) );
((CheckEditor)editor).ThreeState = true;
---------------------------------------
DateTimeEditor
editorSettings.DataType = typeof( DateTime );
editorSettings.MaskInput = "mm/dd/yyyy";
editor = new DateTimeEditor( new DefaultEditorOwner( editorSettings ) );
DateTimeEditor (mm/dd/yy hh:mm:ss)
editorSettings.DataType = typeof( DateTime );
editorSettings.MaskInput = "mm/dd/yy hh:mm:ss";
editor = new DateTimeEditor( new DefaultEditorOwner( editorSettings ) );
---------------------------------------
ProgressBarEditor
editorSettings.DataType = typeof( int );
editor = new Infragistics.Win.UltraWinProgressBar.ProgressBarEditor( new
DefaultEditorOwner( editorSettings ) );
设置 FieldValue 列的控件
private void ultraGrid2_InitializeRow(object sender,
Infragistics.Win.UltraWinGrid.InitializeRowEventArgs e)
{
string fieldType = e.Row.Cells["FieldType"].Text;
EmbeddableEditorBase editor = ...
e.Row.Cells[ "FieldValue" ].Editor = editor;
}
列只读
e.Layout.Override.Rows["xxx"].CellActivation = CellActivation.NoEdit;
隐藏列
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
冻结列
this.ultraGrid1.DisplayLayout.UseFixedHeaders = true;
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].Header.Fixed = true;
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].Header.FixedHeaderIndicator =
FixedHeaderIndicator.None;
this.ultraGrid1.DisplayLayout.Override.FixedHeaderAppearance.BackColor =
Color.LightYellow;
this.ultraGrid1.DisplayLayout.Override.FixedCellAppearance.BackColor = Color.LightYellow;
this.ultraGrid1.DisplayLayout.Override.FixedCellSeparatorColor = Color.Red;
展示列分隔线
this.ultraGrid1.DisplayLayout.Override.CellAppearance.BorderColor = Color.Red;
列允许拖动和切换
this.ultraGrid1.DisplayLayout.Override.AllowColMoving = AllowColMoving.WithinBand;
this.ultraGrid1.DisplayLayout.Override.AllowColSwapping = AllowColSwapping.WithinBand;
列宽调整
e.Layout.AutoFitStyle = AutoFitStyle.ExtendLastColumn;
e.Layout.Override.AllowColSizing = AllowColSizing.Free;
this.ultraGrid1.DisplayLayout.Override.ColumnAutoSizeMode =
ColumnAutoSizeMode.VisibleRows;
this.ultraGrid1.DisplayLayout.Bands[1].Override.ColumnAutoSizeMode =
ColumnAutoSizeMode.AllRowsInBand;
this.ultraGrid1.Rows[0].PerformAutoSize( );
遍历列
grid.Layout.Bands[0].Columns.FromKey("Key")
foreach ( UltraGridColumn column in e.Layout.Bands[0].Columns )
column.Width = 100;
判断某列是否重复
public static bool CheckIfSame(UltraGrid ug, string colname)
{
for(int i = 0; i < ug.Rows.Count; i++)
{
for(int j = i+1; j < ug.Rows.Count; j++)
if(ug.Rows[i].Cells[colname].Text == ug.Rows[j].Cells[colname].Text &&
ug.Rows[i].Cells[colname].Text != "")
return true;
}
return false;
}
添加非绑定列
this.ultraGrid1.DisplayLayout.Bands[0].Columns.Add("CalculatedColumn", "Calculated
Value");
获取子数据条带个数
private int GetNumberofChildBands(Infragistics.Win.UltraWinGrid.UltraGridBand aBand)
{
int GetNumberofChildBands = 0;
foreach(UltraGridColumn aCol in aBand.Columns)
{
if(aCol.IsChaptered)
GetNumberofChildBands = GetNumberofChildBands + 1;
}
return GetNumberofChildBands;
}
不同值可以给以不同的颜色。
Properties-> DisplayLayout->bands->0-XXX->Columns->从弹出窗口中,选择一个列-
>ValueBaseAppearance->添加Conditions,即可。
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ Cell ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
选中单元格样式
ug.DisplayLayout.Override.SelectedCellAppearance.BackColor = Color.SteelBlue;//选中单元格
单元格选择方式
e.Layout.Override.SelectTypeCell = SelectType.Single;
单元格格式
private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
// Fit columns
e.Layout.AutoFitStyle = AutoFitStyle.ExtendLastColumn;
// Create culture objects
CultureInfo cultureENUS = CultureInfo.CreateSpecificCulture("en-us");
CultureInfo cultureDEDE = CultureInfo.CreateSpecificCulture("de-de");
CultureInfo cultureJAJP = CultureInfo.CreateSpecificCulture("ja-jp");
// Set date formats
e.Layout.Bands[0].Columns["OrderDate"].Format = "d";
e.Layout.Bands[0].Columns["OrderDate"].FormatInfo = cultureENUS;
e.Layout.Bands[0].Columns["RequiredDate"].Format = "d";
e.Layout.Bands[0].Columns["RequiredDate"].FormatInfo = cultureDEDE;
e.Layout.Bands[0].Columns["ShippedDate"].Format = "d";
e.Layout.Bands[0].Columns["ShippedDate"].FormatInfo = cultureJAJP;
}
文字过长的裁剪展示方式
this.ultraGrid1.DisplayLayout.Override.CellAppearance.TextTrimming =
TextTrimming.EllipsisCharacter;
修改单元格背景
void UltraGrid1_AfterCellUpdate(...)
{
if(e.Cell.Column.Key == "Column_5")
{
int cellValue = (int)e.Cell.Value;
if(cellValue == 100)
{
e.Cell.Appearance.BackColor = System.Drawing.Color.Red;
}
else
e.Cell.Appearance.BackColor = System.Drawing.Color.White;
}
}
单元格背景图片
private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].CellAppearance.ImageBackground =
Image.FromFile(System.IO.Path.Combine(
Application.StartupPath, @"http://www.cnblogs.com/ExtraFiles/Find in Field.bmp"));
}
单元格按钮样式
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].Style = ColumnStyle.Button;
this.ultraGrid1.DisplayLayout.Override.CellButtonAppearance.Image =
Image.FromFile(System.IO.Path.Combine(
Application.StartupPath, @"http://www.cnblogs.com/ExtraFiles/Find in Field.bmp"));
this.ultraGrid1.DisplayLayout.Bands[0].Override.ButtonStyle =
UIElementButtonStyle.Button3D;
多行单元格
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].CellMultiLine =
DefaultableBoolean.True;
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].VertScrollBar = true;
this.ultraGrid1.DisplayLayout.Override.DefaultRowHeight = 100;
单元格点击处理方式
this.ultraGrid1.DisplayLayout.Override.CellClickAction =
CellClickAction.EditAndSelectText;
单元格值和键
this.ultraGrid1.Rows[0].Cells["字段名"].Value // 单元格的值
cell.Column.Key // 单元格归属的列的键
this.ultraGrid1.Selected.Cells; // 被选中单元格
下拉框单元格
手工设置
在Properties-> DisplayLayout->ValueLists,添加ValueList
Properties-> DisplayLayout->bands->0-XXX->Columns->某个Column->ValueList等于新添加的
ValueList,同时设定Style是DropDown
还要再写个Event Handler,详细其他Style等等可以看这个Link:
http://devcenter.infragistics.com/Support/KnowledgeBaseArticle.Aspx?ArticleID=1708
代码设置
ValueList locValueList = this.ultraGrid.DisplayLayout.ValueLists.Add("Locs");
foreach (DataRow dr in m_ds.Tables["Loc"].Rows)
locValueList.ValueListItems.Add((int)(dr["ID"]), dr["Name"].ToString());
ultraGrid.DisplayLayout.Bands["Customer"].Columns["LocID"].ValueList =
ultraGrid.DisplayLayout.ValueLists["Locs"];
ValueList 示例
ultraGrid1.DisplayLayout.ValueLists.Add("List1");
ultraGrid1.DisplayLayout.ValueLists["List1"].ValueListItems.Add(1, "One");
ultraGrid1.DisplayLayout.ValueLists["List1"].ValueListItems.Add(2, "Two");
ultraGrid1.DisplayLayout.ValueLists["List1"].ValueListItems.Add(3, "Three");
ultraGrid1.DisplayLayout.ValueLists["List1"].DisplayStyle =
ValueListDisplayStyle.DisplayText;
ultraGrid1.DisplayLayout.Bands[0].Columns.Add("Notes");
ultraGrid1.DisplayLayout.Bands[0].Columns["Notes"].ValueList =
this.ultraGrid1.DisplayLayout.ValueLists["List1"];
ultraGrid1.DataBind();
设置特定单元格处于编辑状态
this.ultraGrid1.ActiveCell = this.ultraGrid1.ActiveRow.Cells["CompanyName"];
this.ultraGrid1.Focus();
this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false, false);
合并单元格
合并具有相同值的单元格
this.ultraGrid1.DisplayLayout.Override.MergedCellStyle = MergedCellStyle.Always;
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].MergedCellStyle =
MergedCellStyle.Never;
合并单元格外观设置
this.ultraGrid1.DisplayLayout.Override.MergedCellAppearance.BackColor =
Color.LightYellow;
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].MergedCellAppearance.BackColor =
Color.Blue;
合并逻辑:文本一致就可以合并
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].MergedCellEvaluationType =
MergedCellEvaluationType.MergeSameText;
定制单元格合并逻辑
private void ultraGrid1_InitializeLayout(object sender,
Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
{
e.Layout.Override.MergedCellStyle = MergedCellStyle.Always;
e.Layout.Bands[0].Columns["ShippedDate"].MergedCellEvaluator = new
CustomMergedCellEvaluator();
}
public class CustomMergedCellEvaluator:
Infragistics.Win.UltraWinGrid.IMergedCellEvaluator
{
public CustomMergedCellEvaluator(){}
// 合并日期相同的单元格(无需时间精确相同)
public bool ShouldCellsBeMerged(UltraGridRow row1, UltraGridRow row2,
UltraGridColumn column)
{
DateTime date1 = (DateTime)row1.GetCellValue(column);
DateTime date2 = (DateTime)row2.GetCellValue(column);
return date1.Date == date2.Date;
}
}
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ 自定义单元格编辑控件 ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
EmbeddableEditorBase
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ FULL EXAMPLE ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
//
// UltraDataColumns
//
UltraDataColumn ultraDataColumn1 = new UltraDataColumn("BidId");
UltraDataColumn ultraDataColumn2 = new UltraDataColumn("BidPaperId");
UltraDataColumn ultraDataColumn3 = new UltraDataColumn("BidCompanyName");
UltraDataColumn ultraDataColumn4 = new UltraDataColumn("BidMoney");
UltraDataColumn ultraDataColumn5 = new UltraDataColumn("ValidBidMoney");
UltraDataColumn ultraDataColumn6 = new UltraDataColumn("ValidBidRank");
UltraDataColumn ultraDataColumn7 = new UltraDataColumn("ValidBidRemark");
UltraDataColumn ultraDataColumn8 = new UltraDataColumn("MoneyScore");
UltraDataColumn ultraDataColumn9 = new UltraDataColumn("PaperScore");
UltraDataColumn ultraDataColumn10 = new UltraDataColumn("BusinessScore");
ultraDataColumn1.DataType = typeof(int);
ultraDataColumn2.DataType = typeof(int);
ultraDataColumn5.DataType = typeof(double);
ultraDataColumn8.DataType = typeof(double);
ultraDataColumn9.DataType = typeof(double);
ultraDataColumn10.DataType = typeof(double);
//
// UltraDataSource
//
this.ultraDataSource = new Infragistics.Win.UltraWinDataSource.UltraDataSource
(this.components);
this.ultraDataSource.Band.Columns.AddRange(new object[] {
ultraDataColumn1,
ultraDataColumn2,
ultraDataColumn3,
ultraDataColumn4,
ultraDataColumn5,
ultraDataColumn6,
ultraDataColumn7,
ultraDataColumn8,
ultraDataColumn9,
ultraDataColumn10});
//
// UltraGridColumns
//
UltraGridColumn ultraGridColumn1 = new UltraGridColumn("BidId");
UltraGridColumn ultraGridColumn2 = new UltraGridColumn("BidPaperId");
UltraGridColumn ultraGridColumn3 = new UltraGridColumn("BidCompanyName");
UltraGridColumn ultraGridColumn4 = new UltraGridColumn("BidMoney");
ultraGridColumn1.CellActivation = Infragistics.Win.UltraWinGrid.Activation.NoEdit;
ultraGridColumn1.Header.VisiblePosition = 0;
ultraGridColumn1.Hidden = true;
ultraGridColumn2.CellActivation = Infragistics.Win.UltraWinGrid.Activation.NoEdit;
ultraGridColumn2.Header.Caption = "编号";
ultraGridColumn2.Header.VisiblePosition = 1;
ultraGridColumn2.Hidden = true;
ultraGridColumn3.CellActivation = Infragistics.Win.UltraWinGrid.Activation.NoEdit;
ultraGridColumn3.Header.Caption = "投标公司";
ultraGridColumn3.Header.Fixed = true;
ultraGridColumn3.Header.VisiblePosition = 2;
ultraGridColumn3.Width = 159;
ultraGridColumn4.CellActivation = Infragistics.Win.UltraWinGrid.Activation.NoEdit;
ultraGridColumn4.Header.Caption = "投标金额(万元)";
ultraGridColumn4.Header.VisiblePosition = 3;
ultraGridColumn4.Width = 108;
//
// UltraGridBand
//
UltraGridBand ultraGridBand1 = new UltraGridBand("Band 0", -1);
ultraGridBand1.Columns.AddRange(new object[] {
ultraGridColumn1,
ultraGridColumn2,
ultraGridColumn3,
ultraGridColumn4
});
//
// UltraGrid
//
this.grid = new Infragistics.Win.UltraWinGrid.UltraGrid();
this.grid.DataSource = this.ultraDataSource;
this.grid.DisplayLayout.AutoFitStyle =
Infragistics.Win.UltraWinGrid.AutoFitStyle.ExtendLastColumn;
四、UltraGrid 数据绑定
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ Bind ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
绑定到IList(仅展示,不能添加删除)
this.ultraGrid1.SetDataBinding(myObjectList, "", true);
绑定到平面数据源(DataTable)
private void ultraButton1_Click(object sender, System.EventArgs e)
{
// Declare a DataTable to contain the program generated data
DataTable dataTable = new DataTable("TableTest");
// Create and add a CustomerID column
DataColumn colWork = new DataColumn("CustomerID", System.Type.GetType
("System.Int32"));
dataTable.Columns.Add(colWork);
// Add CustomerID column to key array and bind to DataTable
DataColumn[] Keys = new DataColumn[1];
Keys[0] = colWork;
dataTable.PrimaryKey = Keys;
// Create and add a CustomerName column
colWork = new DataColumn("CustomerName", System.Type.GetType("System.String"));
colWork.MaxLength = 50;
dataTable.Columns.Add(colWork);
// Create and add a LastOrderDate column
colWork = new DataColumn("LastOrderDate", System.Type.GetType("System.DateTime"));
dataTable.Columns.Add(colWork);
// Add a row
DataRow row = dataTable.NewRow();
row["CustomerID"] = 1;
row["CustomerName"] = "Johns Widgets";
row["LastOrderDate"] = System.DateTime.Now;
dataTable.Rows.Add(row);
// Add another row
row = dataTable.NewRow();
row["CustomerID"] = 2;
row["CustomerName"] = "Freds Thingamagigs";
row["LastOrderDate"] = System.DateTime.Now.AddDays(-101);
dataTable.Rows.Add(row);
// Bind the table to the grid
this.ultraGrid1.DataSource = dataTable;
}
绑定到层级数据源(DataSet)
private void ultraButton1_Click(object sender, System.EventArgs e)
{
// Declare DataSet to contain Hierarchical data
// Make Customers DataTable
// Make Orders DataTable
DataSet dataSet = new DataSet();
dataSet.Tables.Add(MakeCustomersDataTable());
dataSet.Tables.Add(MakeOrdersDataTable(dataSet.Tables["Customers"]));
// Create customers/orders relationship and add to DataSet
DataRelation relCustOrder = new DataRelation(
"CustOrder"
, dataSet.Tables["Customers"].Columns["CustomerID"]
, dataSet.Tables["Orders"].Columns["CustomerID"]
);
dataSet.Relations.Add(relCustOrder);
// Bind the DataSet to the Grid
this.ultraGrid1.DataSource = dataSet;
}
// 客户表
private DataTable MakeCustomersDataTable()
{
// Declare a DataTable to contain the program generated data
DataTable dataTable = new DataTable("Customers");
// Create and add a CustomerID column
DataColumn colWork = new DataColumn("CustomerID", System.Type.GetType
("System.Int32"));
dataTable.Columns.Add(colWork);
// Add CustomerID column to key array and bind to DataTable
DataColumn[] Keys = new DataColumn[1];
Keys[0] = colWork;
dataTable.PrimaryKey = Keys;
// Create and add a CustomerName column
colWork = new DataColumn("CustomerName", System.Type.GetType("System.String"));
colWork.MaxLength = 50;
dataTable.Columns.Add(colWork);
// Create and add a L=tOrderDate column
colWork = new DataColumn("L=tOrderDate", System.Type.GetType("System.DateTime"));
dataTable.Columns.Add(colWork);
// Add a row
DataRow row = dataTable.NewRow();
row["CustomerID"] = 1;
row["CustomerName"] = "Johns Widgets";
row["L=tOrderDate"] = System.DateTime.Now;
dataTable.Rows.Add(row);
// Add another row
row = dataTable.NewRow();
row["CustomerID"] = 2;
row["CustomerName"] = "Freds Thingamagigs";
row["L=tOrderDate"] = System.DateTime.Now.AddDays(-101);
dataTable.Rows.Add(row);
return dataTable;
}
// 订单表
private DataTable MakeOrdersDataTable(DataTable v_customersDataTable)
{
// Declare a DataTable to contain the program generated data
DataTable dataTable = new DataTable("Orders");
// Create and add a CustomerID column
DataColumn colWork = new DataColumn("CustomerID", System.Type.GetType
("System.Int32"));
dataTable.Columns.Add(colWork);
// Add CustomerID column to key array
DataColumn[] Keys = new DataColumn[2];
Keys[0] = colWork;
// Create and add OrderID column
colWork = new DataColumn("OrderID", System.Type.GetType("System.String"));
colWork.MaxLength = 15;
dataTable.Columns.Add(colWork);
// Add OrderID column to key array and bind to DataTable
Keys[1] = colWork;
dataTable.PrimaryKey = Keys;
// Create and add a EmployeeID column
colWork = new DataColumn("EmployeeID", System.Type.GetType("System.Int32"));
dataTable.Columns.Add(colWork);
// Create and add a OrderDate column
colWork = new DataColumn("OrderDate", System.Type.GetType("System.DateTime"));
dataTable.Columns.Add(colWork);
// Loop through Customer table and add Order rows
foreach( DataRow custRow in v_customersDataTable.Rows)
{
// Add four rows for each Customer
DataRow row;
for(Int32 intPtr = 1; intPtr <= 4; intPtr++)
{
row = dataTable.NewRow();
row["CustomerID"] = custRow["CustomerID"];
row["OrderID"] = intPtr * ((Int32)custRow["CustomerID"]);
row["EmployeeID"] = intPtr * 10;
row["OrderDate"] = System.DateTime.Now.AddDays(intPtr);
dataTable.Rows.Add(row);
}
}
return dataTable;
}
■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ 窗体控件数据同步 ■■
■■■■■■■■■■■■■■■■■■■■■■■■■■
与窗体控件同步数据
private void DataSourcesandWinGridRows_Load(object sender, System.EventArgs e)
{
this.txtDiscount.DataBindings.Add("Text", this.winGrid1.Order_Details, "Discount");
this.txtQuantity.DataBindings.Add("Text", this.winGrid1.Order_Details, "Quantity");
this.txtUnitPrice.DataBindings.Add("Text", this.winGrid1.Order_Details, "UnitPrice");
}
private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
e.Layout.Override.SelectTypeRow = SelectType.Single;
e.Layout.Override.CellClickAction = CellClickAction.RowSelect;
}
private void ultraGrid1_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
{
// Use CurrencyManager to set position
CurrencyManager currencyManager1;
currencyManager1 = (CurrencyManager)this.BindingContext[this.winGrid1.Order_Details];
currencyManager1.Position = this.ultraGrid1.Selected.Rows[0].Index;
}
同步示例二
private void WinGridasaDataNavigator_Load(object sender, System.EventArgs e)
{
// Set data binding for text boxes
this.txtCompanyName.DataBindings.Add("Text", this.ultraGrid1.DataSource,
"CompanyName");
this.txtContactName.DataBindings.Add("Text", this.ultraGrid1.DataSource,
"ContactName");
this.txtContactTitle.DataBindings.Add("Text", this.ultraGrid1.DataSource,
"ContactTitle");
this.txtAddress.DataBindings.Add("Text", this.ultraGrid1.DataSource, "Address");
this.txtCity.DataBindings.Add("Text", this.ultraGrid1.DataSource, "City");
this.txtRegion.DataBindings.Add("Text", this.ultraGrid1.DataSource, "Region");
this.txtPostalCode.DataBindings.Add("Text", this.ultraGrid1.DataSource,
"PostalCode");
this.txtCountry.DataBindings.Add("Text", this.ultraGrid1.DataSource, "Country");
}
private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
// Hide all but "CustomerID" column
foreach(UltraGridColumn aColumn in e.Layout.Bands[0].Columns)
{
switch (aColumn.Key)
{
case "CustomerID":
aColumn.CellActivation = Activation.NoEdit;
break;
default :
aColumn.Hidden = true;
break;
}
}
// Configure grid
e.Layout.AutoFitStyle = AutoFitStyle.ResizeAllColumns;
e.Layout.Override.SelectTypeCell = SelectType.None;
e.Layout.Override.SelectTypeCol = SelectType.None;
e.Layout.Override.SelectTypeRow = SelectType.None;
}
■■■■■■■■■■■■■■■■■■■■■■■■■
■■ 获取数据 ■■
■■■■■■■■■■■■■■■■■■■■■■■■■
遍历行
遍历子行
UltraGridBand band = this.ultraGrid1.DisplayLayout.Bands[1];
foreach (UltraGridRow row in band.GetRowEnumerator(GridRowType.DataRow))
{
}
遍历所有行,包括子band
foreach ( UltraGridRow row in this.ultraGrid1.Rows.GetRowEnumerator(
GridRowType.DataRow, null, null ) )
{
}
从保护单元格中获取值
private void ultraGrid1_DoubleClickCell(object sender, DoubleClickCellEventArgs e)
{
Point point = Cursor.Position;
point = this.ultraGrid1.PointToClient(point);
UIElement oUI = this.ultraGrid1.DisplayLayout.UIElement.ElementFromPoint(point);
if (oUI == null)
return;
while (oUI != null)
{
if (oUI.GetType() == typeof(CellUIElement))
{
CellUIElement oCellUI = (CellUIElement)oUI;
MessageBox.Show("Cell.Value = " + oCellUI.Cell.Value.ToString());
}
oUI = oUI.Parent;
}
}
获取指定坐标单元格内容
UIElement myUIElement = this.ultraGrid1.DisplayLayout.UIElement.ElementFromPoint(new
Point(e.X, e.Y));
UltraGridCell myCell = (UltraGridCell)myUIElement.GetContext(typeof(UltraGridCell));
MessageBox.Show("You are over a Cell containing " + myCell.Value.ToString());
访问下拉框单元格控件
private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
ValueList vlist=new ValueList();
for(int i=0; i<20; i++)
vlist.ValueListItems.Add(i, "name " + i);
e.Layout.Bands[0].Columns[0].ValueList=vlist;
e.Layout.Bands[0].Columns[0].style = ColumnStyle.DropDown;
EditorWithCombo editor = (EditorWithCombo)this.ultraGrid1.DisplayLayout.Bands
[0].Columns[0].Editor;
editor.HasMRUList = true;
editor.MaxMRUItems = 3;
editor.ButtonAlignment = ButtonAlignment.Left;
}
剪贴板操作
Clipboard.SetDataObject(this.ultraGrid1.Selected.Cells);
this.ultraGrid1.DisplayLayout.Override.AllowMultiCellOperations =
AllowMultiCellOperation.Copy | AllowMultiCellOperation.Paste;
■■■■■■■■■■■■■■■■■■■■■■■■■
■■ CRUD ■■
■■■■■■■■■■■■■■■■■■■■■■■■■
新增行
展现新增行
展现新增行
this.ultraGrid1.DisplayLayout.Override.AllowAddNew = AllowAddNew.TemplateOnTop;
// TemplateOnBottom
提示文本设置
this.ultraGrid1.DisplayLayout.Override.TemplateAddRowPrompt = "Click here to add
rows...";
this.ultraGrid1.DisplayLayout.Bands[0].SpecialRowPromptField = "Address";
新增行样式设置
this.ultraGrid1.DisplayLayout.Override.TemplateAddRowCellAppearance.BackColor =
Color.Yellow;
this.ultraGrid1.DisplayLayout.Override.TemplateAddRowCellAppearance.ForeColor =
Color.LightYellow;
this.ultraGrid1.DisplayLayout.Override.TemplateAddRowSpacingBefore = 5;
this.ultraGrid1.DisplayLayout.Override.TemplateAddRowSpacingAfter = 5;
this.ultraGrid1.DisplayLayout.Override.BorderStyleTemplateAddRow =
UIElementBorderStyle.Inset;
增加行:
this.ultraGrid1.Rows.Band.AddNew();
新增行的值填充
this.ultraGrid1.DisplayLayout.Bands[0].Columns["Country"].DefaultCellValue = "US";
this.ultraGrid1.Rows[this.ultraGrid1.Rows.Count - 1].Cells["REC_ID"].Value =
CommomFun.GetID();
展现新增按钮
this.ultraGrid1.DisplayLayout.AddNewBox.Hidden = false;
private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
e.Layout.AddNewBox.Hidden = false;
}
删除行:
删除选中的行
this.ultraGrid1.DeleteSelectedRows(false);
遍历删除选择行和激活行
bool blnDeleted = false;
for (int i = 0; i < this.ultraGrid1.Rows.Count; i++)
{
if (this.ultraGrid1.Rows[i].Selected || this.ultraGrid1.Rows[i].IsActiveRow)
{
if (this.ultraGrid1.Rows[i].Delete(false))
i--;
blnDeleted = true;
}
}
■■■■■■■■■■■■■■■■■■■■■■■■■
■■ 数据校验 ■■
■■■■■■■■■■■■■■■■■■■■■■■■■
输入校验
对于无效输入:自动恢复为原始值
private void ultraGrid1_InitializeLayout(object sender,
Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
{
// Set the property on the display layout‘s override so it affects the whole
WinGrid.
// You can override the property on a specific column.
e.Layout.Override.InvalidValueBehavior = InvalidValueBehavior.RevertValue;
e.Layout.Bands[0].Columns[0].InvalidValueBehavior =
InvalidValueBehavior.RetainValueAndFocus;
}
使用正则表达式限制输入
this.ultraGrid1.DisplayLayout.Bands[0].Columns[0].RegexPattern = "/d{3}-/d{3}-/d{4}";
private void ultraGrid1_Error(object sender,
Infragistics.Win.UltraWinGrid.ErrorEventArgs e)
{
e.Cancel = true;
if(e.ErrorType == ErrorType.Data)
MessageBox.Show("That is not a valid phone number!!");
}
捕捉输入错误
private void ultraGrid1_CellDataError(object sender,
Infragistics.Win.UltraWinGrid.CellDataErrorEventArgs e)
{
e.RaiseErrorEvent = false; // 阻止弹出错误提示窗口
e.RestoreOriginalValue = true; // 恢复原始值
e.StayInEditMode = true; // 继续保留在编辑模式
}
自定义删除提示框
private void ultraGrid1_BeforeRowsDeleted(object sender, BeforeRowsDeletedEventArgs e)
{
e.DisplayPromptMsg = false;
e.Cancel = (DialogResult.Yes != MessageBox.Show("确定删除该记录?", "删除",
MessageBoxButtons.YesNo));
}
自定义单元格数据错误提示框
private void grid_CellDataError(object sender, CellDataErrorEventArgs e)
{
e.RaiseErrorEvent = false;
e.StayInEditMode = true;
MessageBox.Show("输入数据的格式不正确,请校验");
}
■■■■■■■■■■■■■■■■■■■■■■■■
■■ 导出 ■■
■■■■■■■■■■■■■■■■■■■■■■■■
导出到Excel
(1)将 UltraGridExcelExporter 拖到窗体中
(2)ultraGridExcelExporter1.Export(ultraGrid1, "C://GridData.xls");
(3)可附加控制导出Excel的细节
using Infragistics.Win.UltraWinGrid;
// 修改worksheet名称
private void ultraGridExcelExporter1_BeginExport(object sender,
ExcelExport.BeginExportEventArgs e)
{
e.CurrentWorksheet = e.Workbook.Worksheets.Add("Exported Grid Data");
e.Workbook.ActiveWorksheet = e.CurrentWorksheet;
}
// 阻止导出Owner字段
private void ultraGridExcelExporter1_CellExporting(object sender,
ExcelExport.CellExportingEventArgs e)
{
string sCellType = e.Value.GetType().FullName;
if (sCellType == "System.String")
{
string sCellContents = e.Value.ToString();
if (sCellContents.StartsWith("Owner"))
e.Value = "Position Confidential data *NOT* exported.";
}
}
// 每两列修改一下边框样式
private void ultraGridExcelExporter1_CellExported(object sender,
ExcelExport.CellExportedEventArgs e)
{
if(e.CurrentColumnIndex%2==0)
{
Infragistics.Excel.IWorksheetCellFormat cfCellFmt;
int iRdex = e.CurrentRowIndex;
int iCdex = e.CurrentColumnIndex;
cfCellFmt = e.CurrentWorksheet.Rows[iRdex].Cells[iCdex].CellFormat;
cfCellFmt.BottomBorderStyle =
Infragistics.Excel.CellBorderLineStyle.Double;
}
}
■■■■■■■■■■■■■■■■■■■■■■■■
■■ 接口 ■■
■■■■■■■■■■■■■■■■■■■■■■■■
IDataErrorInfo
// (1) 设置UltraGrid绑定到DataTable
// (2) 在DataTable 的ColumnChanging, RowChanging 事件中检测错误
// (3) 开启UltraGrid错误提示支持:e.Layout.Override.SupportDataErrorInfo =
SupportDataErrorInfo.RowsAndCells;
this.UltraGrid1.SetDataBinding(CreateDataTable(), "" );
-----------------------
e.Layout.Override.SupportDataErrorInfo = SupportDataErrorInfo.RowsAndCells;
e.Layout.Override.DataErrorCellAppearance.ForeColor = Color.Red;
e.Layout.Override.DataErrorRowAppearance.BackColor = Color.LightYellow;
e.Layout.Override.DataErrorRowSelectorAppearance.BackColor = Color.Green;
//--------------------------------------------------
// DataTable events
//--------------------------------------------------
// Create data table
DataTable CreateDataTable()
{
DataTable table = new DataTable("Grades");
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Grade", typeof(int));
table.ColumnChanging += new DataColumnChangeEventHandler
(this.OnTableCellValueChanging);
table.RowChanging += new DataRowChangeEventHandler(this.OnTableRowChanging);
table.Rows.Add(new object[] { "A", 62 });
table.Rows.Add(new object[] { "B", 88 });
table.Rows.Add(new object[] { "C", 94 });
table.Rows.Add(new object[] { "D", -1 });
table.Rows.Add(new object[] { "E", 66 });
table.Rows.Add(new object[] { "F", 46 });
return table;
}
/// <summary>
/// This method is the event handler for the ColumnChanging event of the table which
/// we are using as the data source.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnTableCellValueChanging(object sender, DataColumnChangeEventArgs e)
{
this.ValidateDataRowCell(e.Row, e.Column, e.ProposedValue);
}
/// <summary>
/// This method is the event handler for the ColumnChanging event of the table which
/// we are using as the data source.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnTableRowChanging(object sender, DataRowChangeEventArgs e)
{
this.ValidateDataRowCell(e.Row, e.Row.Table.Columns["Name"], e.Row["Name"]);
this.ValidateDataRowCell(e.Row, e.Row.Table.Columns["Grade"], e.Row["Grade"]);
}
// check cell data
private void ValidateDataRowCell( DataRow row, DataColumn column, object value )
{
switch ( column.ColumnName )
{
case "Name":
{
// Clear the error.
row.SetColumnError( column, "" );
string name = value.ToString( );
if ( 0 == name.Length )
row.SetColumnError( column, "Name cannot be empty."
);
else
{
for ( int i = 0; i < name.Length; i++ )
{
if ( ! char.IsLetter( name, i ) )
{
row.SetColumnError( column, "Name can
not contain non-alphabet characters." );
break;
}
}
}
break;
}
case "Grade":
{
// Clear the error.
row.SetColumnError( column, "" );
if ( DBNull.Value == value )
row.SetColumnError( column, "Name cannot be empty."
);
else
{
int grade = (int)value;
if ( grade < 0 )
row.SetColumnError( column, "Grade cannot be
less than 0." );
else if ( grade > 100 )
row.SetColumnError( column, "Grade cannot be
greater than 100." );
}
break;
}
}
bool invalidName = row.GetColumnError( "Name" ).Length > 0;
bool invalidGrade = row.GetColumnError( "Grade" ).Length > 0;
if ( invalidName && invalidGrade )
row.RowError = "Invalid name and grade.";
else if ( invalidName )
row.RowError = "Invalid name.";
else if ( invalidGrade )
row.RowError = "Invalid grade.";
else
row.RowError = "";
}
IEditorDataFilter ?
public class DayOfWeekToDateConverter : IEditorDataFilter
{
object IEditorDataFilter.Convert( EditorDataFilterConvertArgs conversionArgs )
{
switch (conversionArgs.Direction )
{
case ConversionDirection.DisplayToEditor:
{
string value = conversionArgs.Value as string;
if (value != null)
{
if (value.ToLower().Equals("today"))
{
conversionArgs.Handled = true;
conversionArgs.IsValid = true;
return DateTime.Today;
}
}
break;
}
case ConversionDirection.EditorToDisplay:
{
if (conversionArgs.Value is DayOfWeek)
{
DayOfWeek dayOfWeek = (DayOfWeek)
conversionArgs.Value;
DateTime theDate = this.GetDateFromDayOfWeek
(dayOfWeek);
if (theDate == DateTime.Today)
{
string[] daysOfWeekNames =
CultureInfo.CurrentCulture.
DateTimeFormat.DayNames;
conversionArgs.Handled = true;
conversionArgs.IsValid = true;
return daysOfWeekNames[(int)dayOfWeek] +
" (Today)";
}
}
break;
}
case ConversionDirection.EditorToOwner:
{
if (conversionArgs.Value is DayOfWeek)
{
DayOfWeek dayOfWeek = (DayOfWeek)
conversionArgs.Value;
DateTime theDate = this.GetDateFromDayOfWeek
(dayOfWeek);
conversionArgs.Handled = true;
conversionArgs.IsValid = true;
return theDate;
}
break;
}
case ConversionDirection.OwnerToEditor:
{
if (conversionArgs.Value is DateTime)
{
DateTime theDate = (DateTime)conversionArgs.Value;
conversionArgs.Handled = true;
conversionArgs.IsValid = true;
return theDate.DayOfWeek;
}
break;
}
}
return conversionArgs.Value;
}
private DateTime GetDateFromDayOfWeek(DayOfWeek dayOfWeek)
{
for (int i = 0; i < 7; i ++)
{
DateTime theDate = DateTime.Today.AddDays((double)i);
if (theDate.DayOfWeek == dayOfWeek)
return theDate;
}
return DateTime.Today;
}
}
五、UltraGrid 绑定到 IList 示例
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UltraBid.DAL;
using Infragistics.Win;
using Infragistics.Win.UltraWinDataSource;
using Infragistics.Win.UltraWinGrid;
namespace UltraBid.Controls
{
public partial class BidCompanyForm : UserControl, IShowBidInfo
{
Bid _bid;
IList _list;
public void ShowInfo(Bid bid)
{
_bid = bid;
if (_bid != null)
{
_list = BidPaper.ListByBidId(bid.BidId);
ultraDataSource.Rows.SetCount(_list.Count);
this.grid.DataSource = ultraDataSource;
//this.grid.SetDataBinding(_list, "", true);
}
}
//---------------------------------------
// Init
//---------------------------------------
public BidCompanyForm()
{
InitializeComponent();
}
private void BidCompanyForm_Load(object sender, EventArgs e)
{
}
//-----------------------------------------------------
// ultraDataSource
//-----------------------------------------------------
private void ultraDataSource_RowAdding(object sender, RowAddingEventArgs e)
{
BidPaper paper = new BidPaper();
paper.BidId = _bid.BidId;
_list.Add(paper);
}
private void ultraDataSource_RowDeleting(object sender, RowDeletingEventArgs e)
{
(_list[e.Row.Index] as BidPaper).Remove();
_list.RemoveAt(e.Row.Index);
}
private void ultraDataSource_CellDataRequested(object sender,
CellDataRequestedEventArgs e)
{
BidPaper paper = _list[e.Row.Index] as BidPaper;
if (paper == null) return;
switch (e.Column.Key)
{
case "BidPaperId":
e.Data = paper.BidPaperId;
break;
case "BidId":
e.Data = paper.BidId;
break;
case "BidCompanyName":
e.Data = paper.BidCompanyName;
break;
case "BidCompanyAsset":
e.Data = paper.BidCompanyAsset;
break;
case "BidManager":
e.Data = paper.BidManager;
break;
case "BidContact":
e.Data = paper.BidContact;
break;
case "BidTel":
e.Data = paper.BidTel;
break;
case "BidDeposit":
e.Data = paper.BidDeposit;
break;
case "BidRemark":
e.Data = paper.BidRemark;
break;
}
}
private void ultraDataSource_CellDataUpdating(object sender,
CellDataUpdatingEventArgs e)
{
BidPaper paper = _list[e.Row.Index] as BidPaper;
if (paper == null) return;
switch (e.Column.Key)
{
case "BidCompanyName":
paper.BidCompanyName = Convert.ToString(e.NewValue);
break;
case "BidCompanyAsset":
paper.BidCompanyAsset = Convert.ToString(e.NewValue);
break;
case "BidManager":
paper.BidManager = Convert.ToString(e.NewValue);
break;
case "BidContact":
paper.BidContact = Convert.ToString(e.NewValue);
break;
case "BidTel":
paper.BidTel = Convert.ToString(e.NewValue);
break;
case "BidDeposit":
paper.BidDeposit = Convert.ToDouble(e.NewValue);
break;
case "BidRemark":
paper.BidRemark = Convert.ToString(e.NewValue);
break;
}
paper.Persist();
}
//---------------------------------------
// Grid
//---------------------------------------
private void grid_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
//e.Layout.Override
e.Layout.Override.AllowAddNew = AllowAddNew.TemplateOnBottom;
e.Layout.Override.TemplateAddRowAppearance.BackColor = Color.FromArgb(245, 250,
255);
e.Layout.Override.TemplateAddRowAppearance.ForeColor = SystemColors.GrayText;
e.Layout.Override.AddRowAppearance.BackColor = Color.LightYellow;
e.Layout.Override.AddRowAppearance.ForeColor = Color.Blue;
e.Layout.Override.SpecialRowSeparator = SpecialRowSeparator.TemplateAddRow;
e.Layout.Override.SpecialRowSeparatorAppearance.BackColor = SystemColors.Control;
e.Layout.Override.TemplateAddRowPrompt = "点此添加新记录...";
e.Layout.Override.TemplateAddRowPromptAppearance.ForeColor = Color.Maroon;
e.Layout.Override.TemplateAddRowPromptAppearance.FontData.Bold =
DefaultableBoolean.True;
}
private void grid_AfterCellUpdate(object sender, CellEventArgs e)
{
//BidPaper paper = _list[e.Cell.Row.Index] as BidPaper;
//paper.Persist();
}
private void grid_BeforeRowsDeleted(object sender, BeforeRowsDeletedEventArgs e)
{
e.DisplayPromptMsg = false;
e.Cancel = (DialogResult.Yes != MessageBox.Show("确定删除该记录?", "删除",
MessageBoxButtons.YesNo));
}
private void grid_CellDataError(object sender, CellDataErrorEventArgs e)
{
e.RaiseErrorEvent = false;
e.StayInEditMode = true;
MessageBox.Show("输入数据的格式不正确,请校验");
}
}
}
六、UltraGrid 事件处理
■■■■■■■■■■■■■■■■■■■■■■■■■
■■ Grid Events ■■
■■■■■■■■■■■■■■■■■■■■■■■■■
按键受理
private void ultraGrid1_KeyPress(object sender, KeyPressEventArgs e)
{
// For the OrderDate column, change the periods to slashes
switch (this.ultraGrid1.ActiveCell.Column.Key)
{
case "OrderDate":
if(e.KeyChar.ToString() == ".")
{
e.Handled = true;
SendKeys.Send("/");
}
break;
}
}
InitializeLayout
private void UltraGrid1_InitializeLayout(object sender,
Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
{
e.Layout.Override.AllowAddNew = AllowAddNew.FixedAddRowOnTop;
e.Layout.Override.TemplateAddRowAppearance.BackColor = Color.FromArgb( 245,
250, 255 );
e.Layout.Override.TemplateAddRowAppearance.ForeColor = SystemColors.GrayText;
e.Layout.Override.AddRowAppearance.BackColor = Color.LightYellow;
e.Layout.Override.AddRowAppearance.ForeColor = Color.Blue;
e.Layout.Override.SpecialRowSeparator = SpecialRowSeparator.TemplateAddRow;
e.Layout.Override.SpecialRowSeparatorAppearance.BackColor =
SystemColors.Control;
e.Layout.Override.TemplateAddRowPrompt = "Click here to add a new record...";
e.Layout.Override.TemplateAddRowPromptAppearance.ForeColor = Color.Maroon;
e.Layout.Override.TemplateAddRowPromptAppearance.FontData.Bold =
DefaultableBoolean.True;
e.Layout.Bands[0].SpecialRowPromptField = e.Layout.Bands[0].Columns[0].Key;
e.Layout.Bands[0].Columns[5].DefaultCellValue = "(DefaultValue)";
e.Layout.ScrollStyle = ScrollStyle.Immediate;
e.Layout.ScrollBounds = ScrollBounds.ScrollToFill;
// Initialize controls
this.LoadAllowAddNewCombo( this.ultraComboEditorAllowAddNew );
this.LoadEnumCombo( this.ultraComboEditorSpecialRowSeparatorBorderStyle,
typeof( UIElementBorderStyle ) );
this.LoadColumnsCombo( this.ultraComboEditorSpecialRowPromptField,
e.Layout.Bands[0] );
// Initialize the controls to their values.
this.ultraComboEditorAllowAddNew.Value = e.Layout.Override.AllowAddNew;
this.ultraComboEditorSpecialRowSeparatorBorderStyle.Value =
e.Layout.Override.BorderStyleSpecialRowSeparator;
this.ultraNumericEditorAddRowSpacingAfter.Value =
e.Layout.Override.TemplateAddRowSpacingAfter;
this.ultraNumericEditorAddRowSpacingBefore.Value =
e.Layout.Override.TemplateAddRowSpacingBefore;
this.ultraNumericEditorSeparatorHeight.Value =
e.Layout.Override.SpecialRowSeparatorHeight;
this.ultraCheckEditorAddNewBox.Checked = ! e.Layout.AddNewBox.Hidden;
this.ultraCheckEditorCardView.Checked = e.Layout.Bands[0].CardView;
this.ultraCheckEditorSeparator.Checked = 0 != (
SpecialRowSeparator.TemplateAddRow & e.Layout.Override.SpecialRowSeparator );
this.ultraTextEditorAddRowPrompt.Value =
e.Layout.Override.TemplateAddRowPrompt;
}
■■■■■■■■■■■■■■■■■■■■■■■■
■■ Mouse Events ■■
■■■■■■■■■■■■■■■■■■■■■■■■
确定用户点击的数据条带
private void ultraGrid1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Declare and retrieve a reference to the UIElement
UIElement aUIElement =
this.ultraGrid1.DisplayLayout.UIElement.ElementFromPoint(new Point(e.X,
e.Y));
if(aUIElement == null)
return;
UltraGridBand aBand = null;
// Look for a row
UltraGridRow aRow = (UltraGridRow)aUIElement.GetContext(typeof(UltraGridRow));
if(aRow != null)
aBand = this.ultraGrid1.DisplayLayout.Bands[aRow.Band.Index];
if(aBand == null)
{
// Look for a column
UltraGridColumn aColumn =
(UltraGridColumn)aUIElement.GetContext(typeof(UltraGridColumn));
if(aColumn != null)
aBand = this.ultraGrid1.DisplayLayout.Bands[aColumn.Band.Index];
}
// If a band was found display the band index
if(aBand != null)
this.ultraTextEditor1.Text = "Band(" + aBand.Index.ToString() + ")";
else
this.ultraTextEditor1.Text = "* no band associcated with this location";
}
■■■■■■■■■■■■■■■■■■■■■■■■
■■ Row Events ■■
■■■■■■■■■■■■■■■■■■■■■■■■
给每一行展示一个说明
this.ultraGrid1.DisplayLayout.Bands[0].AutoPreviewEnabled = true;
private void datagrid1_InitializedRow(....)
{
e.row.Description = "My description";
}
■■■■■■■■■■■■■■■■■■■■■■■■
■■ Cell Events ■■
■■■■■■■■■■■■■■■■■■■■■■■■
单元格数据修改后事件
ultraGrid1_AfterCellUpdate
当前单元格变动事件
private void datagrid1_CurrentCellChanged(object sender, System.EventArgs e)
{
int inumber = this.datagrid1.currentcell.rownumber;
string smyid = this.datagrid1[inumber, 0].tostring();//获取到第i行第一列的值
}
■■■■■■■■■■■■■■■■■■■■■■■■
■■ Scroll ■■
■■■■■■■■■■■■■■■■■■■■■■■■
滚动到首行
private void ultraButton1_Click(object sender, System.EventArgs e)
{
// If there are no rows this method will not work
if(this.ultraGrid1.Rows.Count <= 0)
return;
this.ultraGrid1.ActiveRow = this.ultraGrid1.Rows[0];
}
上滚一行
// If no ActiveRow this procedure will not work
if(this.ultraGrid1.ActiveRow == null)
return;
// Retrieve reference to current ActiveRow and look for a previous row
UltraGridRow aRow = this.ultraGrid1.ActiveRow;
// Look to see if this row has a Previous Sibling
if(aRow.HasPrevSibling() == true)
{
// Set ActiveRow to this row to make it visible
this.ultraGrid1.ActiveRow = aRow.GetSibling(SiblingRow.Previous);
// Look to see if this row has children
if(this.ultraGrid1.ActiveRow.HasChild())
{
// Look for lowest child in hierarchy
aRow = this.ultraGrid1.ActiveRow;
while(aRow.HasChild() != false)
{
aRow = aRow.GetChild(ChildRow.Last);
}
this.ultraGrid1.ActiveRow = aRow;
}
return;
}
// Look to see if this row has a Parent
if(aRow.HasParent(aRow.Band.ParentBand) == true)
this.ultraGrid1.ActiveRow = aRow.ParentRow;
下滚一行
if(this.ultraGrid1.ActiveRow == null)
return;
// Retrieve reference to current ActiveRow
UltraGridRow aRow = this.ultraGrid1.ActiveRow;
// Look to see if this row has a child row
if(aRow.HasChild() == true)
{
aRow = aRow.GetChild(ChildRow.First);
this.ultraGrid1.ActiveRow = aRow;
return;
}
// Look to see if this row has a next sibling
if(aRow.HasNextSibling() == true)
{
aRow = aRow.GetSibling(SiblingRow.Next);
this.ultraGrid1.ActiveRow = aRow;
return;
}
// Look for next sibling of parent
aRow = aRow.ParentRow;
if(aRow != null)
{
if(aRow.HasNextSibling() == true)
{
aRow = aRow.GetSibling(SiblingRow.Next);
this.ultraGrid1.ActiveRow = aRow;
return;
}
}
if(aRow != null)
this.ultraGrid1.ActiveRow = aRow;
滚到最后一行
if(this.ultraGrid1.ActiveRow == null)
return;
// Retrieve last row in band(0)
UltraGridRow aRow = this.ultraGrid1.GetRow(ChildRow.Last);
// Look for last child of last child
while(aRow.HasChild() != false)
{
aRow = aRow.GetChild(ChildRow.Last);
}
// Back up as many as three rows so we can see what is above this row
UltraGridRow topRow = aRow;
int intCount = 3;
while(intCount <= 0 || topRow.HasPrevSibling() == false)
{
intCount -= 1;
topRow = topRow.GetSibling(SiblingRow.Previous);
}
// Set topRow as active row to position it to top of Grid
this.ultraGrid1.ActiveRow = topRow;
// Set aRow as Active Row
this.ultraGrid1.ActiveRow = aRow;
滚动到父band的首行
private void ultraGrid1_BeforeRowActivate(object sender, RowEventArgs e)
{
// Determine which row should be the top row
UltraGridRow rowTop;
if(e.Row.Band.Index == 0)
rowTop = e.Row;
else
rowTop = e.Row.ParentRow;
// Scroll the row into RowScrollRegion
this.ultraGrid1.DisplayLayout.RowScrollRegions[0].ScrollRowIntoView(rowTop);
// Turn off display refresh during update
this.ultraGrid1.BeginUpdate();
// Scroll the top row to the top
while(this.ultraGrid1.DisplayLayout.RowScrollRegions[0].VisibleRows[0].Row != rowTop)
{
this.ultraGrid1.DisplayLayout.RowScrollRegions[0].Scroll(
RowScrollAction.LineDown);
}
// Turn display refresh back on
this.ultraGrid1.EndUpdate();
}
七、UltraGrid Actions
■■■■■■■■■■■■■■■■■■■■■■■■■
■■ Actions ■■
■■■■■■■■■■■■■■■■■■■■■■■■■
KeyActionMappings(按键动作映射)
// 使用Enter切换到下一个单元格
using Infragistics.Win.UltraWinGrid;
this.ultraGrid1.KeyActionMappings.Add(
new GridKeyActionMapping(
Keys.Enter, // 按下回车键时
UltraGridAction.NextCell, // 跳转到下一单元格
UltraGridState.IsCheckbox, // 单元格不能为checkbox
UltraGridState.Cell, // 选中单元格时
0, // 不禁止特殊键
0 // 不需要特殊键
)
);
// 按下H键导航到表格的第一行
this.ultraGrid1.KeyActionMappings.Add(
new GridKeyActionMapping(
Keys.H, // 按下H键
UltraGridAction.FirstRowInGrid, // 定位到网格的首行
UltraGridState.InEdit, // 此时网格不处于编辑状态
0, // 无附加状态需求
Infragistics.Win.SpecialKeys.Alt, // 此时Alt键没有按下
0 // 无附加特殊按键需求
)
);
PerformActions(执行预设动作)
switch (e.Tool.Key)
{
case "Undo":
this.ultraGrid1.PerformAction(UltraGridAction.Undo);
break;
case "Redo":
this.ultraGrid1.PerformAction(UltraGridAction.Redo);
break;
case "Copy":
this.ultraGrid1.PerformAction(UltraGridAction.Copy);
break;
case "Paste":
this.ultraGrid1.PerformAction(UltraGridAction.Paste);
break;
case "Cut":
this.ultraGrid1.PerformAction(UltraGridAction.Cut);
break;
case "Delete":
this.ultraGrid1.PerformAction(UltraGridAction.DeleteCells);
break;
case "Select All":
foreach (UltraGridRow row in this.ultraGrid1.Rows.GetRowEnumerator
(GridRowType.DataRow, null, null))
{
row.Selected = true;
}
break;
}
// 响应键盘事件
private void ultraGrid1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
switch(e.KeyCode)
{
case Keys.Up:
this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
false);
this.ultraGrid1.PerformAction(UltraGridAction.AboveCell, false,
false);
e.Handled = true;
this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
false);
break;
case Keys.Down:
this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
false);
this.ultraGrid1.PerformAction(UltraGridAction.BelowCell, false,
false);
e.Handled = true;
this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
false);
break;
case Keys.Right:
this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
false);
this.ultraGrid1.PerformAction(UltraGridAction.NextCellByTab, false,
false);
e.Handled = true;
this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
false);
break;
case Keys.Left:
this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
false);
this.ultraGrid1.PerformAction(UltraGridAction.PrevCellByTab, false,
false);
e.Handled = true;
this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
false);
break;
}
}
// 设置激活单元格背景色
private void ultraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
this.ultraGrid1.DisplayLayout.Override.ActiveCellAppearance.BackColor = Color.Red;
}
// Set ActiveRow and ActiveCell on grid entry
private void ultraGrid1_Enter(object sender, System.EventArgs e)
{
if(this.ultraGrid1.ActiveRow == null)
this.ultraGrid1.ActiveRow = this.ultraGrid1.GetRow(ChildRow.First);
if(this.ultraGrid1.ActiveCell == null)
this.ultraGrid1.ActiveCell = this.ultraGrid1.ActiveRow.Cells[2];
}