当前位置: 首页 > 工具软件 > Express Combo > 使用案例 >

Developer Express .NET Winform3 - GridControl控件

计光赫
2023-12-01

XtraGrid的关键类就是:GridControl和GridView。GridControl本身不显示数据,数据都是显示在GridView/CardView/XXXXView中。GridControl是各种View的容器。所以要控制显示,要从GridView这些类入手。

 

DevExpress控件组中的GridControl控件不能使横向滚动条有效。现象:控件中的好多列都挤在一起,列宽都变的很小,根本无法正常浏览控件单元格中的内容。

解决:

gridView1.OptionsView.ColumnAutoWidth属性是true,即各列的宽度自动调整,你把它设成false,就会出现了。


使单元格不可编辑。

gridcontrol -->gridview-->OptionsBehavior -->Editable=false

 

去除"Drag a Column Header Here To Group by that Column"

属性Gridview->OptionView->Show Group Panel=false,就好了

 

选择某行数据触发时间

gridView2.RowClick += newDevExpress.XtraGrid.Views.Grid.RowClickEventHandler(gridView2_RowClick);

这样设置以后必须点击最左边的行编号才可以触发事件,需要设置gridcontrol-->gridview -->OptionsBehavior -->Editable=false即可点击任意单元格触发事件。


获取当前选择行对象

GridView gv = this.gridControlUserList.FocusedView as GridView;
gv.GetRow((this.gridControlUserList.MainView as ColumnView).FocusedRowHandle); 


选择某行后获取当前表格数据

this.textBox1.Text =gridView2.GetDataRow(e.RowHandle)["列名"].ToString();

 

设置奇、偶行交替颜色

(1) OptionsView.EnableAppearanceEvenRow= true;OptionsView.EnableAppearanceOddRow= true;

(2) 设置Appearance.EvenRow.BackColor和Appearance.OddRow.BackColor

 

在每行第一列显示行号

(1)this.gridView2.IndicatorWidth = 30;//设置显示行号的列宽

(2)设置动作gridView2.CustomDrawRowIndicator += newDevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventHandler(gridView2_CustomDrawRowIndicator);

//添加行号
void gridView2_CustomDrawRowIndicator(object sender, 
DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgse)
{
 if(e.Info.IsRowIndicator && e.RowHandle>= 0)
{
 e.Info.DisplayText = (e.RowHandle +1).ToString();
}
 }

 gridView2.PopulateColumns();



焦点单元格显示方式
GrideView默认的焦点单元格显示方式是整行选中,焦点单元格高亮。可以调整以下属性进行修改

gridView1.FocusRectStyle :焦点绘画方式 默认DrawFocusRectStyle.CellFocus(单元格)/ DrawFocusRectStyle.RowFocus(行)/ DrawFocusRectStyle.None(不绘画)
bool gridView1.OptionsSelection.EnableAppearanceFocusedCell :是否焦点显示选中的单元格
bool gridView1.OptionsSelection.EnableAppearanceFocusedRow :是否焦点显示选中的行
bool gridView1.OptionsSelection.InvertSelection :是否反显示
bool gridView1.OptionsSelection.MultiSelect:是否使用多选

 

增加新行用InitNewRow事件,给新行某字段赋值。后结束编辑。

private void grdView_InitNewRow(object sender,DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
   {
    DevExpress.XtraGrid.Views.Grid.GridView view = senderas DevExpress.XtraGrid.Views.Grid.GridView;
    view.SetRowCellValue(e.RowHandle,view.Columns["EnterID"], this.dS_MEnterStoreView.MEnterStore[0].ID);
    this.grdControl.EmbeddedNavigator.Buttons.EndEdit.DoClick();
    this.grdView.UpdateCurrentRow();
   }


 

在Grid上编辑数据
 
修改属性gridView1.OptionsView.NewItemRowPosition,设为Top或Bottom可以在Grid上添加数据。

(在demo中原文:a record object must be inherited from theIEditableObject class if you need the ability to cancel newly added records viathe grid)
 
译:如果你需要通过gird取消新建的记录,你的记录对象必须实现IEditableObject
 
(注:在测试中,感觉不需要继承IEditableObject,在grid编辑后也能实现取消。demo通过实现IEditableObject的BeginEdit、CancelEdit方法,数据编辑后恢复特定数据。不使用grid直接修改数据,可以考虑这种恢复原数据的方法。)
 
修改列(Column)格式
DevExpress.XtraGrid.Columns.GridColumn col = gridView1.Columns[0];
数据对齐方式col.AppearanceCell.TextOptions.HAlignment, 默认值Default,可选值Default/Near/Center/Far。
说明:以下情况是基于从左到右的文字排列;若是从右到左,用法相反。
Default:数据默认的对齐方式
Near:左对齐
Center:居中对齐
Far:右对齐
列标题 col.Caption
对应绑定数据的属性 col.FieldName
排列顺序col.VisibleIndex
格式化显示数据
Col.DisplayFormat.FormatType
Col.DisplayFormat.Format
Col.DisplayFormat.FormatString
 
区别:FormatType/FormatString使用当前系统的语言区域设置,Format使用特定的[url=ms-help://MS.VSCC.v80/MS.VSIPCC.v80/DevExpress.NETv8.2/DevExpress.XtraData/DevExpressUtilsFormatInfo_FormatTypetopic.htm##]System.IFormatProvider[/url]设置。

(原文注释:Use theFormatType and[url=ms-help://MS.VSCC.v80/MS.VSIPCC.v80/DevExpress.NETv8.2/DevExpress.XtraData/DevExpressUtilsFormatInfo_FormatStringtopic.htm]FormatString[/url]properties to format values based on the current language and regional settings(culture). FormatType specifies the type of values to be formatted.[url=ms-help://MS.VSCC.v80/MS.VSIPCC.v80/DevExpress.NETv8.2/DevExpress.XtraData/DevExpressUtilsFormatInfo_FormatStringtopic.htm]FormatString[/url]specifies a format pattern appropriate for the current FormatType value. Youcan refer to the Standard Numeric Format Strings and Date and Time FormatStrings topics in MSDN for information on format specifiers.

Setting the FormatType property changes the format provider used whenformatting values by the[url=ms-help://MS.VSCC.v80/MS.VSIPCC.v80/DevExpress.NETv8.2/DevExpress.XtraData/DevExpressUtilsFormatInfo_GetDisplayTexttopic.htm]GetDisplayText[/url]function. Format providers supply information such as the character to use asthe decimal point when formatting numeric strings and the separation characterto use when formatting a [url=ms-help://MS.VSCC.v80/MS.VSIPCC.v80/DevExpress.NETv8.2/DevExpress.XtraData/DevExpressUtilsFormatInfo_FormatTypetopic.htm##]System.DateTime[/url]object. The[url=ms-help://MS.VSCC.v80/MS.VSIPCC.v80/DevExpress.NETv8.2/DevExpress.XtraData/DevExpressUtilsFormatInfo_Formattopic.htm]Format[/url]property specifies the format provider to use.

You can change the[url=ms-help://MS.VSCC.v80/MS.VSIPCC.v80/DevExpress.NETv8.2/DevExpress.XtraData/DevExpressUtilsFormatInfo_Formattopic.htm]Format[/url]property explicitly by assigning a [url=ms-help://MS.VSCC.v80/MS.VSIPCC.v80/DevExpress.NETv8.2/DevExpress.XtraData/DevExpressUtilsFormatInfo_FormatTypetopic.htm##]System.IFormatProvider[/url]object. This can be useful if you wish to format values according to a specificculture (not the current one). In this case, you also need to set theFormatType property to[url=ms-help://MS.VSCC.v80/MS.VSIPCC.v80/DevExpress.NETv8.2/DevExpress.XtraData/DevExpressUtilsFormatTypeEnumtopic.htm]FormatType.Custom[/url].)
 
使用Grid内置导航栏
gridControl1.UseEmbeddedNativgator=True
设定内置导航栏按钮其他属性gridControl1.EmbeddedNavigator
 
GridView内置方式编辑数据
禁止编辑数据gridView1.OptionsBehavior.Editable = False,默认是True 可编辑。
Gridview内置数据编辑器显示方式gridView1.OptionsBehavior.EditorShowMode,可选值Default/ MouseDown/MouseUp/ Click。
说明:
Default 多选Cell相当于Click,单选Cell相当于MouseDown
MouseDown 在单元格内按下鼠标键时打开内置编辑器
MouseUp 在单元格内释放鼠标键时打开内置编辑器

Click 在不是编辑状态,但获得焦点的单元格中点击时打开编辑器。点击非焦点单元格时,首先会切换焦点,再点击时才打开编辑器

设定GrideView单元格的内置编辑器

在Run Designer的Columns选中需要变更编辑方式的Column,在ColumnEdit 属性的下拉菜单中选择编辑数据使用的控件。

例1:Person表的CountryID字段的值来自Country表,使用下拉列表显示CountryName编辑
修改CountryIDColumn.ColumnEdit值,选new->LookupEdit,默认命名为repositoryItemLookUpEdit1。展开ColumnEdit属性,将DisplayMember 设为CountryName,DropDownRows是下拉列表的行数,ValueMember设为CountryID。

 代码中添加:
//init data
repositoryItemLookUpEdit1.DataSource = ds.Tables[Country];
例2:字段Age是整型,需要使用SpinEdit编辑

修改AgeColumn.ColumnEdit值,选new->SpinEdit。展开ColumnEdit属性,修改MaxValue、MinValue设定最大、最小值。运行时Age的取值只能在MaxValue至MinValue之间选值。s

GridView调节行高显示大文本

默认情况下gridview已单行方式显示,过长的文本只能显示开头部分,鼠标停留在单元格上方有ToolTip显示所有文本。在文本单元格的右边两个按钮供切换显示上下行。若需要在单元格变更行高显示所有文本。使用

gridView1.OptionsView.RowAutoHeight = True;
gridView1.LayoutChanged();也可以通过事件判断文本内容改变行高
private void gridView1_CalcRowHeight(objectsender,DevExpress.XtraGrid.Views.Grid.RowHeightEventArgs e)
{
if(e.RowHandle >= 0)
e.RowHeight =(int)gridView1.GetDataRow(e.RowHandle)["RowHeight"];
}



数据导出

XtraGrid支持Html、Xml、Txt、Xsl导出,对应的导出器是ExportHtmlProvider、ExportXmlProvider、ExportTxtProvider、ExportXslProvider

例:使用html格式导出数据

……

IExportProvider provider = new ExprotHtmlProvider(filename);

ExportTo(provider);

……

private void ExportTo(IExportProvider provider) {
            CursorcurrentCursor = Cursor.Current;
           Cursor.Current = Cursors.WaitCursor;

           this.FindForm().Refresh();
           BaseExportLink link = gridView1.CreateExportLink(provider);
            (linkas GridViewExportLink).ExpandAll = false;
           link.Progress += newDevExpress.XtraGrid.Export.ProgressEventHandler(Export_Progress);//进度条事件
            link.ExportTo(true);
           provider.Dispose();
           link.Progress -= new DevExpress.XtraGrid.Export.ProgressEventHandler(Export_Progress);

           Cursor.Current = currentCursor;
}



焦点单元格显示方式
GrideView默认的焦点单元格显示方式是整行选中,焦点单元格高亮。可以调整以下属性进行修改

gridView1.FocusRectStyle :焦点绘画方式 默认DrawFocusRectStyle.CellFocus(单元格)/ DrawFocusRectStyle.RowFocus(行)/ DrawFocusRectStyle.None(不绘画)
bool gridView1.OptionsSelection.EnableAppearanceFocusedCell :是否焦点显示选中的单元格
bool gridView1.OptionsSelection.EnableAppearanceFocusedRow :是否焦点显示选中的行
bool gridView1.OptionsSelection.InvertSelection :是否反显示
bool gridView1.OptionsSelection.MultiSelect:是否使用多选


显示非数据源的数据

可以在GrideView上增加数据源没有的列,如合计、日期、序号或其他数据源等。

方法一:实现CustomColumnDisplayText事件(只能用于显示)

以下例子在bandedGridColumn1上显示 FirstName+LastName

bandedGridColumn1.OptionsColumn.AllowEdit = false;
private void bandedGridView1_CustomColumnDisplayText(object sender,DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
  {
     if(e.Column.Equals(bandedGridColumn1))
{
         DataRow row =bandedGridView1.GetDataRow(e.RowHandle);
         e.DisplayText =string.Format("{0} {1}", row["FirstName"],row["LastName"]);
     }
}


方法二: 设定列的UnboundType,并实现CustomUnboundColumnData事件(可修改值)

以下例子演示DateTime/Int/String绑定到数据列上显示。当修改 GrideView上的值时,将修改同步到原数组中。

bandedGridColumn4.UnboundType =DevExpress.Data.UnboundColumnType.DateTime;
bandedGridColumn5.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
bandedGridColumn6.UnboundType = DevExpress.Data.UnboundColumnType.String;

private void bandedGridView1_CustomUnboundColumnData(object sender,DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e) {
             if(array == null) return;
             if(e.ListSourceRowIndex >= array.Count) return;
             Record rec = array[e.ListSourceRowIndex] as Record;
             if(rec == null) return;
             switch(e.Column.UnboundType) {
                  case UnboundColumnType.DateTime:
                      if(e.IsGetData)
                           e.Value = rec.Date;
                      else rec.Date = (DateTime)e.Value;
                      break;
                  case UnboundColumnType.Integer:
                      if(e.IsGetData)
                           e.Value = rec.Count;
                      else rec.Count = (Int32)e.Value;
                      break;
                  case UnboundColumnType.String:
                      if(e.IsGetData)
                           e.Value = rec.Comment;
                      else rec.Comment = e.Value.ToString();
                      break;
             }
         }




-------------------------------------------------------------

提交当前行的修改
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using System.Data.Common;
//...
public void UpdateDatasource(GridControl grid) {
    //Save the latest changes to the bound DataTable
    ColumnView view = (ColumnView)grid.FocusedView;
    view.CloseEditor();
    if(!view.UpdateCurrentRow()) return;
   
    //Update the database's Suppliers table to whicholeDBDataAdapter1 is connected
    DoUpdate(oleDbDataAdapter1,dataSet11.Tables["Suppliers"]);
    //Update the database's Products table to which theoleDbDataAdapter2 is connected
    DoUpdate(oleDbDataAdapter2,dataSet11.Tables["Products"]);
}
 
public void DoUpdate(DbDataAdapter dataAdapter, System.Data.DataTabledataTable) {
    try {
        dataAdapter.Update(dataTable);
    } catch(Exception ex) {
        MessageBox.Show(ex.Message);
    }
}


从非绑定数据源得到数据
private void Form1_Load(object sender, System.EventArgs e) {
   // ...
 
   // Create an unbound column.
   GridColumn unbColumn =gridView1.Columns.Add("Total");
   unbColumn.VisibleIndex = gridView1.Columns.Count;
   unbColumn.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
   // Disable editing.
   unbColumn.OptionsColumn.AllowEdit = false;
   // Specify format settings.
   unbColumn.DisplayFormat.FormatType =DevExpress.Utils.FormatType.Numeric;
   unbColumn.DisplayFormat.FormatString = "c";
   // Customize the appearance settings.
   unbColumn.AppearanceCell.BackColor = Color.LemonChiffon;
}
 
// Returns the total amount for a specific row.
decimal getTotalValue(ColumnView view, int rowHandle) {
   decimal unitPrice =Convert.ToDecimal(view.GetRowCellValue(rowHandle, "UnitPrice"));
   decimal quantity =Convert.ToDecimal(view.GetRowCellValue(rowHandle, "Quantity"));
   decimal discount =Convert.ToDecimal(view.GetRowCellValue(rowHandle, "Discount"));
   return unitPrice * quantity * (1 - discount);
}
 
// Provides data for the Total column.
private void gridView1_CustomUnboundColumnData(object sender,DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e) {
   if(e.Column.FieldName == "Total" && e.IsGetData) e.Value = getTotalValue(sender as ColumnView, e.RowHandle);
}

 

运行时绑定到实现Ilist接口的数据源
public class Record {
   int id, age;
   string name;
   public Record(int id, string name, int age) {
      this.id = id;
      this.name = name;
      this.age = age;
   }
   public int ID { get { return id; } }
   public string Name {
      get { return name; }
      set { name = value; }
   }
   public int Age {
      get { return age; }
      set { age = value; }
   }
}

ArrayList listDataSource = new ArrayList();
listDataSource.Add(new Record(1, "Jane", 19));
listDataSource.Add(new Record(2, "Joe", 30));
listDataSource.Add(new Record(3, "Bill", 15));
listDataSource.Add(new Record(4, "Michael", 42));
gridControl1.DataSource = listDataSource;
gridControl1.MainView.PopulateColumns();

自定义列:
[C#]
DevExpress.XtraGrid.Views.Base.ColumnView view = gridControl1.MainView asDevExpress.XtraGrid.Views.Base.ColumnView;
DialogResult answer = MessageBox.Show("Do you want to create columnsfor all fields?", "Confirmation", MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (answer == DialogResult.Yes)
   view.PopulateColumns();
else {
   string[] fieldNames = new string[] {"ProductID","ProductName", "QuantityPerUnit", "UnitPrice"};
   DevExpress.XtraGrid.Columns.GridColumn column;
   view.Columns.Clear();
   for (int i = 0; i < fieldNames.Length; i++) {
      column = view.Columns.Add(fieldNames[i]);
      column.VisibleIndex = i;
   }
}


GridColumn主要属性
Property
 Description
 
GridColumn.Name
 设计时定义的列名
 
GridColumn.FieldName
 绑定到的数据源中的列名
 
GridColumn.AbsoluteIndex
 在grid中的绝对位置索引
 
GridColumn.ColumnHandle
 指定关联数据源列名的标识,它不一定是唯一的,因为一个数据源列可以关联到一个Grid中的多个列.
 

 
手动创建Band
// obtaining the main view and clearing its bands collection
BandedGridView view = gridControl1.MainView as BandedGridView;
view.Bands.Clear();
// creating the bands layout
GridBand bandGeneral = view.Bands.Add("General Info");
GridBand bandTechnical = view.Bands.Add("Technical Info");
GridBand bandEngine = bandTechnical.Children.Add("Engine Info");
GridBand bandTransmission = bandTechnical.Children.Add("TransmissionInfo");
// assigning columns to bands
colTrademark.OwnerBand = bandGeneral;
colModel.OwnerBand = bandGeneral;
colLiter.OwnerBand = bandEngine;
colCylinders.OwnerBand = bandEngine;
colSpeedCount.OwnerBand = bandTransmission;
colTransmission.OwnerBand = bandTransmission;



 

如何定位和查找指定列显示值的行(注意是列的实显示值,而不是关联数据源列值)
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Columns;
// ...
 
string searchText = "Japan";
// obtaining the focused view
ColumnView view = (ColumnView)gridControl1.FocusedView;
// obtaining the column bound to the Country field
GridColumn column = view.Columns["Country"];
if(column != null) {
// locating the row
//如果用数据源中的列值,请用ColumnView.LocateByValue
    int rhFound =view.LocateByDisplayText(view.FocusedRowHandle + 1, column, searchText);
    // focusing the cell
    if(rhFound != GridControl.InvalidRowHandle) {
        view.FocusedRowHandle =rhFound;
        view.FocusedColumn = column;
    }
}



另一个查找示例

DevExpress.XtraGrid.Views.Base.ColumnView view = gridControl1.MainView asDevExpress.XtraGrid.Views.Base.ColumnView;
view.BeginUpdate();
try {
   int rowHandle = 0;
   DevExpress.XtraGrid.Columns.GridColumn col =view.Columns["Category"];
   while(true) {
      // locating the next row
      rowHandle = view.LocateByValue(rowHandle,col, "SPORTS");
      // exiting the loop if no row is found
      if (rowHandle ==DevExpress.XtraGrid.GridControl.InvalidRowHandle)
         break;
      // perform specific operations on the rowfound here
      // ...
      rowHandle++;
   }
} finally { view.EndUpdate(); }
 

将特定编辑框绑定到列
默认的cell编辑框是不可以改变的,即使是在运行时,因为它们是动态创建和注销的。
要想定制,就在设计时修改ColumnEdit吧。
using DevExpress.XtraEditors.Repository;
 
//Create a repository item for a combo box editor
RepositoryItemComboBox riCombo = new RepositoryItemComboBox();
riCombo.Items.AddRange(new string[] {"London","Berlin", "Paris"});
//Add the item to the internal repository
gridControl1.RepositoryItems.Add(riCombo);
//Now you can define the repository item as an in-place column editor
colCity.ColumnEdit =  riCombo;



另一个运行时绑定列编辑框示例
private void gridView1_CustomRowCellEdit(object sender,DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e) {
   if (e.Column.FieldName == "FieldName") return;
   DevExpress.XtraGrid.Views.Grid.GridView gv = sender asDevExpress.XtraGrid.Views.Grid.GridView;
   string fieldName = gv.GetRowCellValue(e.RowHandle,gv.Columns["FieldName"]).ToString();
   switch (fieldName) {
      case "Population":
         e.RepositoryItem =repositoryItemSpinEdit1;
         break;
      case "Country":
         e.RepositoryItem =repositoryItemComboBox1;
         break;
      case "Capital":
         e.RepositoryItem =repositoryItemCheckEdit1;
         break;
   }          
}




检验录入数据是否有效

using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
 
public bool isValidDate(int day, int month, int year) {
    return (day > 0) && (month > 0)&& (month <= 12) && (year > 1980) && (year <2100) && (day <= DateTime.DaysInMonth(year, month));
}
 
private void gridView1_ValidateRow(object sender,DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e) {
    GridView view = sender as GridView;
    GridColumn colDay = view.Columns["Day"];
    GridColumn colMonth = view.Columns["Month"];
    GridColumn colYear = view.Columns["Year"];
    int day = (int)view.GetRowCellValue(e.RowHandle,colDay);
    int month = (int)view.GetRowCellValue(e.RowHandle,colMonth);
    int year = (int)view.GetRowCellValue(e.RowHandle,colYear);
    e.Valid = isValidDate(day, month, year);
    if(!e.Valid) {
        view.SetColumnError(colDay,"Check the day");
        view.SetColumnError(colMonth,"Check the month");
        view.SetColumnError(colYear,"Check the year");
    }
}


 MouseMove捕捉
private void Grid_MouseMove(object sender,System.Windows.Forms.MouseEventArgs e)
  {
  ShowHitInfo(this.gridView1.CalcHitInfo(new Point(e.X, e.Y)));
  }

  private void ShowHitInfo(DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfohi)
  {
   DevExpress.XtraGrid.Views.Base.ColumnView cgv =
   (DevExpress.XtraGrid.Views.Base.ColumnView)Grid.MainView;

   string columnName = hi.Column == null ? "No column": hi.Column.Caption;
   switch(columnName)
   {
       case "账号":
     txtUserName.Text =cgv.GetRowCellDisplayText(hi.RowHandle,hi.Column);
     break;
    case "密码":
     txtPassword.Text =cgv.GetRowCellDisplayText(hi.RowHandle,hi.Column);
     break;
    case "真实姓名":
     txtRealName.Text =cgv.GetRowCellDisplayText(hi.RowHandle,hi.Column);
     break;
    case "电子邮件":
     txtEmail.Text =cgv.GetRowCellDisplayText(hi.RowHandle,hi.Column);
     break;
    case "角色":
     cbRole.Text =cgv.GetRowCellDisplayText(hi.RowHandle,hi.Column);
     break;
    default:
     txtUserName.Text = "Null";
     txtPassword.Text = "Null";
     txtRealName.Text = "Null";
     txtEmail.Text = "Null";
     cbRole.Text = "Null";
     break;
   }



一,主从表的设置

代码
        

   DataTable dt = pb.GetItemInfoList(Port).Copy(); //返回一个TABLE
           dt.TableName = "ItemInfo";
           ds.Tables.Add(dt);
           DataTable dt2 = pb.GetBuildingInfoList(Port).Copy(); //返回一个TABLE
           dt2.TableName = "BuildingInfo";
           ds.Tables.Add(dt2);
           DataColumn keyColumn =ds.Tables["ItemInfo"].Columns["ITEMINFO_ID"];
           DataColumn foreignKeyColumn =ds.Tables["BuildingInfo"].Columns["ITEMINFOID"];
           ds.Relations.Add("itembuildinginfo", keyColumn, foreignKeyColumn);
           gridControl1.DataSource = ds.Tables["ItemInfo"];


 
二,获取主表的当前选择行的某一列(如第0列)

三、获取从表的当前选择行的某一列(如ID列)
     这个时候再使用获取主表当前选择行的某一列的方法是不行的,因为所得到的seletedrowscount=0。使用如下方法得到:
  在MASTER表的展开事件中得到detail有的view.然后就可以利用它了。例: 
代码
//主表的masterrowexpanded事件 
private void gridView1_MasterRowExpanded(object sender,DevExpress.XtraGrid.Views.Grid.CustomMasterRowEventArgs e)
        {
           detailView = gridView1.GetDetailView(e.RowHandle, e.RelationIndex) asDevExpress.XtraGrid.Views.Grid.GridView;
        }
 
//取得从表的当前行
int[] i = detailView.GetSelectedRows();
           DataRowView dt = (DataRowView)detailView.GetRow(i[0]);
 
//获得当前行某列的值可以使用

dt["列名"].ToString();

//获得当那个列的值。

 


 类似资料: