四、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];
}
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■ 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];
}
相关推荐
整理对Infragistics netadvantage UltraGrid的一些应用!
Infragistics NetAdvantage Ultimate 2011 Vol. 2 下载地址和序列号 Infragistics NetAdvantage Ultimate 2011 Vol. 2 ============================== 下载地址: NetAdvantage 2011 Vol. 2 Platform Installer ...
Infragistics NetAdvantage Ultimate 2011 Vol 1
Infragistics NetAdvantage 2008 vol 2 key
文档详细记叙了 第三方控件 UltraGrid 中 属性 方法 等 中文介绍 对英文不太好的同学可以参考
infragistics NetAdvantage_2008 vol 2 sn
Infragistics NetAdvantage for Windows Forms 2009 Vol 2 Samples Part2(2009年9月5日的版本 包含Key)
Infragistics NetAdvantage for Windows Forms 2014 Volume 2第二部分
Infragistics NetAdvantage for Windows Forms 2010 Vol 2 Source(2010年7月7日的版本)
Infragistics NetAdvantage for .NET 2009 Volume 1注册码
Infragistics NetAdvantage select 2010 Key for winform\for asp.net
Infragistics NetAdvantage 2007 Vol.3 用于.NET framework 2.0 ASP.NET的源代码 版本号是v7.3.20073.1043
Infragistics NetAdvantage for Windows Forms 2008 Vol.2 CLR 2.0 Source
Infragistics NetAdvantage for Windows Forms 2008 Vol.3 英文版 测试可用
Infragistics NetAdvantage for asp.net help 2011 Vol1 part2
Infragistics NetAdvantage for ASP.NET 2010 Vol 2 Source(2010年7月6日的版本)
Infragistics NetAdvantage UltraWebGrid使用技巧 Infragistics ASP.NET控件用法总结 UltraWebGrid的基本用法 WebCombo的基本用法 等等 转自:vbchina.net
Infragistics NetAdvantage for WPF 2008 Vol 1.part1
Infragistics NetAdvantage 2010 vol 2 key
Infragistics NetAdvantage ASP.NET_20111 Vol1 Samples