亲宝软件园·资讯

展开

XtraGrid控件用法

springsnow 人气:0

设计数据源并绑定字段:

数据源可以是实现下列接口之一的任何类型:

修改也是同步的

DataTable dataTable = new DataTable();
dataTable.Columns.Add("Name", System.Type.GetType("System.String"));
dataTable.Columns.Add("Sex", System.Type.GetType("System.String"));
dataTable.Columns.Add("Age", System.Type.GetType("System.String"));

DataRow row = dt.NewRow(); ;
row["Name"] = "mathilda";
row["Sex"] = "loli";
row["Age"] = "12";
dataTable.Rows.Add(row);

// 绑定字段
gridView1.Columns[1].FieldName = "Sex";
gridView1.Columns[2].FieldName = "Age";
gridView1.Columns[0].FieldName = "Name";

gridControl1.DataSource = dataTable;

根据数据源自动产生列

gridView2.PopulateColumns();

表格数据与数据源的数据同步

XtraGrid与Windows自带的DataGridView在数据源方面不同的是,对grid里的数据进行任何改动(增、删、改)之后,原本的数据源也相应的改动。通过下面例子可以得出此结论,在窗体添加删,改两个按钮并绑定下面相应的事件。

/// <summary>
/// 更改
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btEdit_Click(object sender, EventArgs e)
{
    Person p = (Person)gridView1.GetRow(gridView1.FocusedRowHandle);
}

/// <summary>
/// 删除
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btDelete_Click(object sender, EventArgs e)
{
    if (gridView1.SelectedRowsCount != 0)
        gridView1.DeleteSelectedRows();
    MessageBox.Show(people.Count.ToString());
}

只要对grid的数据经过改动之后,单击相应的按钮就可以查看数据源的信息。

新增一条记录,添加行

(1)、gridView.AddNewRow()、gridView.UpdateCurrentRow()

数据源DataSource如果是DataTable可以用AddNewRow方法,然后UpdateCurrentRow。

但是如果DataSource的来源是List<T>,用AddNewRow是不起作用的,这时候需要将List<T>转换为BindingList<T>,才可以采用AddNewRow。

然后使用gridView.UpdateCurrentRow()将更改同步到数据源DataTable或BindingList中。

(2)、实现 gridView_InitNewRow 事件

删除选中行

删除选中行, 可通过DeleteSelectedRows()方法,

然后使用gridView.UpdateCurrentRow()将更改同步到数据源DataTable或BindingList中。

具体示例代码如下:

if (gridView1.SelectedRowsCount > 0)
{
     gridView1.DeleteSelectedRows();
     gridView.UpdateCurrentRow()
}

获取选定行,指定列单元格的内容

gridView1.GetRowCellValue(pRows[0], ColumName).ToString ();

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

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

Get/Set 单元格的值

通过调用GetRowCellValue获取单元格的值。

public override object GetRowCellValue(int rowHandle, GridColumn column);

rowHandle是行的索引,column列的对象。

通过调用SetRowCellValue设置单元格的值

public void SetRowCellValue(int rowHandle, GridColumn column, object _value);

rowHandle是行的索引,column列的对象。_value是单元格新的值。

以peopleList为例

int englishS=Convert.ToDouble(0,gridView1.Columns["English"])+60;
SetRowCellValue(0,gridView1.Columns["English"],englishS);

在XtraGrid有另一种方式,就是直接设置数据源的值。对于上面这个例子,直接找到grid里第一行数据对应的Person对象,设置它的English值。

选中行改变绑定行数据到对应控件中

1、判断是否有Focused行

if (gridView1.IsValidRowHandle(gridView1.FocusedRowHandle))

2、获取Focused行

1、绑定的是数据行:

DataRow Row = gridView1.GetFocusedDataRow();

2、绑定的是实体:

**Entity entity = gridView1.GetFocusedRow() as **Entity;

3、获取Focused行单元格的值

string Code = gridView1.GetFocusedRowCellValue("Code").ToString();
string Code = gridView1.GetRowCellValue(e.FocusedRowHandle, "Code")

FocusedRowChanged事件:

if (bandedGridView1.GetFocusedDataRow() == null) return;//判断当前选中行是否为null
//返回值
var columnValue= bandedGridView1.GetFocusedRowCellValue("绑定列字段名称").ToString();

动态添加列

// 动态添加列             
DevExpress.XtraGrid.Columns.GridColumn Col1 = new DevExpress.XtraGrid.Columns.GridColumn();             
Col1.FieldName = "Name";             
Col1.Caption = "名字";             
Col1.Visible = false;             
Col1.VisibleIndex = gvCountry.Columns.Count;             
gvCountry.Columns.Add(Col1);

添加非绑定列

下面的例子主要演示如何为gird网格添加一个非绑定列,从而显示根据 Quantity*UnitPrice*(1-Discount)公式计算出来的每个订单的金额。

private void Form1_Load(object sender, System.EventArgs e)
{
    // ...
    gridControl1.ForceInitialize();
    // Create an unbound column.
    GridColumn unbColumn = gridView1.Columns.AddField("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(int listSourceRowIndex)
{
    DataRow row = nwindDataSet.Tables["Order Details"].Rows[listSourceRowIndex];
    decimal unitPrice = Convert.ToDecimal(row["UnitPrice"]);
    decimal quantity = Convert.ToDecimal(row["Quantity"]);
    decimal discount = Convert.ToDecimal(row["Discount"]);
    return unitPrice * quantity * (1 - discount);
}
// Provides data for the Total column.
private void gridView1_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
{
    if (e.Column.FieldName == "Total" && e.IsGetData) e.Value =
    getTotalValue(e.ListSourceRowIndex);
}

编辑器

XtraGrid提供了多种编辑器。这些能够在Grid/CardView/BandedView中使用。在属性编辑器中的In-place Editor Repository可以对编辑器进行管理。在Columns的ColumnEdit中选择该列使用哪个编辑器。

也可以通过代码实现:

RepositoryItemComboBox repositoryItemComboBox_abc=new RepositoryItemComboBox();
// 
// 对编辑器进行设置
// 
this.gridColumn1.ColumnEdit = repositoryItemComboBox_abc;  //在需要的列里使用定义好的编辑器

添加按钮列

把列的ColumnEdit属性设置为RepositoryItemButtonEdit
把TextEditStyle属性设置为HideTextEditor;
把Buttons的Kind属性设置为Glyph;

把Button的Caption用于设置文字
把Buttons的TextOption的HAlignment属性设置为Near;
如果要用到事件的话,还要注册事件。。。
在GridControl的设计器中Repository页中的In-place Editor Repository项中
在右边的Repository栏中找到你的ButtonEdit,选它的事件属性页,注册它的ButtonClick事件即可

数据验证

有两种方法来实现基于单元格的验证:

1、使用RepositoryItem.Validating事件

事件的"sender" 必须转换为BaseEdit类型,使用EditValue来获取当前输入的值并进行校验,如果校验不通过,把e.Cancel设置True。这种方法一般用来对内置控件的单元格进行数据验证。

private void TextEdit1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
    BaseEdit textEdit = sender as BaseEdit;
    if (textEdit.Text.ToString().Trim().Length == 0)
    {
        e.Cancel = true;
        //标识 错误提示
        errorReason = 0;
        return;
    }
    else
    {
        //获取GridView中所有的选中的行号
        //此处不允许多选,故只有一行
        int[] iRowId = this.gViewActList.GetSelectedRows();
        for (int i = 0; i < gViewActList.DataRowCount; i++)
        {
            //重复检验时,不验证当前行
            if (i != iRowId[0])
            {
                if (textEdit.EditValue.ToString().Trim() == gViewActList.GetDataRow(i)["GridView上绑定的列名"].ToString().Trim())
                {
                    e.Cancel = true;
                    //标识 错误提示
                    errorReason = 1;
                    return;
                }
            }
        }
    }
}

跟据Validating事件中的标识,进行错误信息提示:

private void gViewActList_InvalidValueException(object sender, InvalidValueExceptionEventArgs e)
{
    if (errorReason == 0)
    {
        e.ErrorText = "动作名称不允许为空!";
    }
    else if (errorReason == 1)
     {
         e.ErrorText = "动作名称不允许为重复!";
     }
     else
     {
         e.ErrorText = "值无效!";
     }
}

2、使用 GridView.ValidatingEditor 事件

事件的"sender"必须转换为GridView类型,当前列可以从GridView.FocusedColumn属性获得,值可以从e.Value获取,如果校验不通过,需要把e.Valid设置为False。这种方法一般用于对整个Grid内的文本框进行数据验证

private void gvList_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e){
             if (this.gvList.FocusedColumn.FieldName == "passQty"){ 
                string passQty = e.Value.ToString().Trim();                 
                int receiveQty = orderDetailList[this.gvList.FocusedRowHandle].qty; 
                if (!JXType.IsIntBigThanZero(passQty)){ 
                    e.Valid = false;                     
                    e.ErrorText = "合格数量必须为大于等于0, 并且小于等于接货数量的整数!";
                }else{ 
                    if (int.Parse(passQty) > receiveQty){ 
                        e.Valid = false;                         
                        e.ErrorText = "合格数量必须为大于0, 并且小于等于接货数量的整数!";
                    }
                }
            }
}

在设置完事件之后需要写一个GridView.InvalidValueException 的事件委托,如

private void gridView1_InvalidValueException(object sender, DevExpress.XtraGrid.Views.Base.InvalidValueExceptionEventArgs e)
{
    e.ThrowException = false;
    e.WindowText = "验证通过";
    e.DisplayError = true;
}

3、使用 GridView.ValidateRow事件

在gridview的ValidateRow事件中加入数据校验代码:

#region 检查数据   
private void gridView1_ValidateRow(object sender, ValidateRowEventArgs e){
    GridView view = sender as GridView;   
    view.ClearColumnErrors();
    if (view.GetRowCellValue(e.RowHandle, "Birthday") == DBNull.Value){ 
        e.Valid = false;   
        view.SetColumnError(view.Columns["Birthday"], "必须指定出生日期");   
    }
}

添加CheckBox并支持多选操作.

OptionsSelection -> MultiSelect : True

MultiSelectMode : CheckBoxRowSelect

全选和反选

这是一个比较难的问题,这里我结合网上寻找的资料总结了一个实体类贴上源代码

//-------------------------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2014 , ZTO , Ltd .
 //-------------------------------------------------------------------------------------

using System.Drawing;
 using System.Windows.Forms;
 using DevExpress.XtraEditors.Repository;

namespace ZTO.WayBill.Utilities
 {
     /// <summary>
     /// Dev GridControl 创建全选复选框
    ///
     /// 修改纪录
    ///
     ///          2014-5-30   版本:1.0 YangHengLian 创建主键,注意命名空间的排序。
    /// 
     /// 版本:1.0
     ///
     /// <author>
     ///        <name>YangHengLian</name>
    ///        <date>2014-5-30</date>
     /// </author>
     /// </summary>
     public class DevControlHelper
     {
         /// <summary>
         /// 创建复选框
        /// </summary>
         /// <param name="e"></param>
         /// <param name="chk"></param>
         public static void DrawCheckBox(DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e, bool chk)
         {
             RepositoryItemCheckEdit repositoryCheck = e.Column.ColumnEdit as RepositoryItemCheckEdit;
             if (repositoryCheck != null)
             {
                 Graphics g = e.Graphics;
                 Rectangle r = e.Bounds;
                 DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info;
                 DevExpress.XtraEditors.Drawing.CheckEditPainter painter;
                 DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs args;
                 info = repositoryCheck.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
                 painter = repositoryCheck.CreatePainter() as DevExpress.XtraEditors.Drawing.CheckEditPainter;
                 info.EditValue = chk;
                 info.Bounds = r;
                 info.CalcViewInfo(g);
                 args = new DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs(info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
                 painter.Draw(args);
                 args.Cache.Dispose();
             }
         }
         /// <summary>
         /// 全选,反选
        /// </summary>
         /// <param name="gridView"></param>
         /// <param name="fieldName"></param>
         /// <param name="currentStatus"></param>
         /// <returns></returns>
         public static bool ClickGridCheckBox(DevExpress.XtraGrid.Views.Grid.GridView gridView, string fieldName, bool currentStatus)
         {
             bool result = false;
             if (gridView != null)
             {
                 gridView.ClearSorting();//禁止排序
                gridView.PostEditor();
                 DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info;
                 Point pt = gridView.GridControl.PointToClient(Control.MousePosition);
                 info = gridView.CalcHitInfo(pt);
                 if (info.InColumn && info.Column != null && info.Column.FieldName == fieldName)
                 {
                     for (int i = 0; i < gridView.RowCount; i++)
                     {
                         gridView.SetRowCellValue(i, fieldName, !currentStatus);
                     }
                     return true;
                 }
             }
             return result;
         }
     }
 }

下面是使用步骤

窗体加载事件添加一些代码

private bool _mCheckStatus; //GridControl全选,作为全局变量,默认false
        private void FrmInputBill_Load(object sender, EventArgs e)
        {
            bandedGridView1.OptionsBehavior.Editable = false;
            bandedGridView1.OptionsBehavior.ReadOnly = true;
            var col = new BandedGridColumn { FieldName = "Check", Visible = true, VisibleIndex = 0, ColumnEdit = new RepositoryItemCheckEdit() };
            col.OptionsColumn.AllowEdit = true; //CheckBox可以编辑改变
            gridBand1.Columns.Insert(0, col);
            bandedGridView1.Click += bandedGridView1_Click;
            bandedGridView1.CustomDrawColumnHeader += bandedGridView1_CustomDrawColumnHeader;
            bandedGridView1.DataSourceChanged += bandedGridView1_DataSourceChanged;
       //这里绑定数据源
        }
        #region GridControl支持全选事件
 
        private void bandedGridView1_Click(object sender, EventArgs e)
        {
            if (DevControlHelper.ClickGridCheckBox(this.bandedGridView1, "Check", _mCheckStatus))
            {
                _mCheckStatus = !_mCheckStatus;
            }
        }
 
        private void bandedGridView1_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.FieldName == "Check")
            {
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                DevControlHelper.DrawCheckBox(e, _mCheckStatus);
                e.Handled = true;
            }
        }
 
        private void bandedGridView1_DataSourceChanged(object sender, EventArgs e)
        {
            GridColumn column = this.bandedGridView1.Columns.ColumnByFieldName("Check");
            if (column != null)
            {
                column.Width = 40;
                column.OptionsColumn.ShowCaption = false;
                column.ColumnEdit = new RepositoryItemCheckEdit();
            }
        }
 
        #endregion

重绘单元格或者行的显示,使用CustomDrawCell()事件

通过在Appearence中添加FormatCondition,设置应用与整行,还是单一个单元格,使用CustomDrawCell事件。

void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
    var currentView = sender as GridView;
    if (currentView != null && e.RowHandle == currentView.FocusedRowHandle) return;
    Rectangle r = e.Bounds;
    if (e.Column.FieldName == "F_State")
    {
        if (e.CellValue.ToString().Equals("False"))
        {
            e.Appearance.ForeColor = Color.Red;
            e.Appearance.DrawString(e.Cache, e.DisplayText, r);
            e.Handled = true;
        }

    }
}

数据导入导出

原文:Export to XLS and XLSX Formats | WinForms Controls | DevExpress Documentation

XtraGrid 支持Html、Xml、Txt、Xsl导出,对应的导出器是ExportHtmlProvider、ExportXmlProvider、 ExportTxtProvider、ExportXslProvider。都在命名空间DevExpress.XtraExport里面。

这里封装了一个数据导出的方法,可以导出上述列举的类型,只需要传入相应类型的provider就可以了。

private void ExportTo(IExportProvider provider)
{
    Cursor currentCursor = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    this.FindForm().Refresh();
    BaseExportLink link = gridView1.CreateExportLink(provider);
    (link as GridViewExportLink).ExpandAll = false;
    link.ExportTo(true);
    provider.Dispose();
    Cursor.Current = currentCursor;
}

调用时只需要创建一个相应的provider。

IExportProvider provider = new ExportXlsProvider(FullFileName); //这里可以是ExportHtmlProvider、ExportXmlProvider、ExportTxtProvider
ExportTo(provider);

也可以

string path = "output.xlsx";

//Customize export options
(gridControl1.MainView as GridView).OptionsPrint.PrintHeader = false;
XlsxExportOptionsEx advOptions = new XlsxExportOptionsEx();
advOptions.AllowGrouping = DevExpress.Utils.DefaultBoolean.False;
advOptions.ShowTotalSummaries = DevExpress.Utils.DefaultBoolean.False;
advOptions.SheetName = "Exported from Data Grid";

gridControl1.ExportToXlsx(path, advOptions);
// Open the created XLSX file with the default application.
Process.Start(path);

导入数据只尝试了导入Excel的导入,利用ODBC读取Excel的数据到DataTable中,再把DataTable绑定到XtraGrid中。这里也是封装了一个读取Excel数据的方法。

private DataSet GetDataFromExcelWithAppointSheetName(string Path)
{
    String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=" + Path + ";" +"Extended Properties=Excel 8.0;";
    OleDbConnection conn = new OleDbConnection(strConn);
    conn.Open();
    //返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等 
    DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
    //包含excel中表名的字符串数组
    string[] strTableNames = new string[dtSheetName.Rows.Count];
    for (int k = 0; k < dtSheetName.Rows.Count; k++)
    {
        strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
    }
    OleDbDataAdapter da = null;
    DataSet ds = new DataSet();
    //从指定的表明查询数据,可先把所有表明列出来供用户选择
    string strExcel = "select * from[" + strTableNames[0] + "]";
    da = new OleDbDataAdapter(strExcel, conn);
    da.Fill(ds);
    return ds;
}

以这样方式调用。

DataSet ds = GetDataFromExcelWithAppointSheetName(FullFileName);

导出到PDF

一种方法:

using DevExpress.XtraPrinting;

// Create a PrintingSystem component.
DevExpress.XtraPrinting.PrintingSystem ps = new DevExpress.XtraPrinting.PrintingSystem();

// Create a link that will print a control.
DevExpress.XtraPrinting.PrintableComponentLink link = new PrintableComponentLink(ps);

// Specify the control to be printed.
link.Component = gridControl1;

// Generate a report.
link.CreateDocument();

// Export the report to a PDF file.
string filePath = @"c:\gridcontrol.pdf";
link.PrintingSystem.ExportToPdf(filePath);

System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = filePath;
process.Start();

二种:

DevExpress.XtraGrid.Views.Grid.GridView View = gridControl1.MainView    as DevExpress.XtraGrid.Views.Grid.GridView;
if (View != null) {
   View.OptionsPrint.ExpandAllDetails = true;//请注意,仅当GridOptionsPrint.PrintDetails属性设置为true时,此设置才有效。
   View.ExportToPdf("MainViewData.pdf");
}

行双击事件的处理

要响应GridView的单击或者双击事件,要设置GridView的OptionsBehavior.Editable=false。如果为true,它是不会响应这这两个事件的。 它本的的机制就是这样。

//双击行弹出rowDetail信息 
        private void gridView1_MouseDown(object sender, MouseEventArgs e) 
        {  
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hInfo = gridView1.CalcHitInfo(new Point(e.X,e.Y));  
            if (gridView1.RowCount > 0 && e.Button == MouseButtons.Left && e.Clicks == 2) 
            {  
                //判断光标是否在行范围内  
                if (hInfo.InRow)  
                {  
                    //取得选定行信息  
                    string nodeName = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "nodeName").ToString(); 
                    //string nodeName = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[0], "nodeName").ToString(); 
                    string sql = "select nodeDetail from treelist where nodeName = '" + nodeName + "'"; 
                    SqlCommand comm = new SqlCommand(sql, conn);  
                    try 
                    {  
                        conn.Open();  
                        MessageBox.Show(comm.ExecuteScalar().ToString(), "Detail"); 
                    }  
                    catch (Exception ex)  
                    {  
                        MessageBox.Show(ex.Message, "Error"); 
                    }  
                    finally 
                    {  
                        conn.Close();  
                    }  
                }  
            }  
        }

那么MouseDown方法与DoubleClick有什么区别呢?grid1_DoubleClick(object sender, EventArgs e)函数会捕获整个grid的双击事件而不仅仅是双击列表行事件,比如:你双击表头、列表展示数据的下方的空白部分都会引发grid1_DoubleClick(object sender, EventArgs e)函数,而ViewHtlb_MouseDown(object sender, MouseEventArgs e)函数此时不会被激活。

定位到某数据/记录??

this.gridView.MoveFirst();
this.gridView.MoveNext();
this.gridView.MoveLast();

禁止 各列头 移动\排序\改变列宽

gridView1.OptionsCustomization.AllowColumnMoving = false;
gridView1.OptionsCustomization.AllowSort = false;
gridView1.OptionsCustomization.AllowColumnResizing = false;

拖动滚动条时固定某一列

设置Columns,选择要固定的列,设置Fixed属性,

可以选择以下固定方式:

呈现给用户自定义的菜单:

#region Grid events
        private void gridView_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            if (e.MenuType == DevExpress.XtraGrid.Views.Grid.GridMenuType.Column)
            {
                DevExpress.XtraGrid.Menu.GridViewColumnMenu menu = e.Menu as DevExpress.XtraGrid.Menu.GridViewColumnMenu;
                menu.Items.Clear();
                if (menu.Column != null)
                {
                    menu.Items.Add(CreateCheckItem("取消固定", menu.Column, DevExpress.XtraGrid.Columns.FixedStyle.None, imageList2.Images[0]));
                    menu.Items.Add(CreateCheckItem("固定到左边", menu.Column, DevExpress.XtraGrid.Columns.FixedStyle.Left, imageList2.Images[1]));
                    menu.Items.Add(CreateCheckItem("固定到右边", menu.Column, DevExpress.XtraGrid.Columns.FixedStyle.Right, imageList2.Images[2]));
                }
            }
        }

        #endregion
        #region New column menu
        DXMenuCheckItem CreateCheckItem(string caption, GridColumn column, DevExpress.XtraGrid.Columns.FixedStyle style, Image image)
        {
            DXMenuCheckItem item = new DXMenuCheckItem(caption, column.Fixed == style, image, new EventHandler(OnFixedClick));
            item.Tag = new MenuInfo(column, style);
            return item;
        }
        void OnFixedClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            MenuInfo info = item.Tag as MenuInfo;
            if (info == null) return;
            info.Column.Fixed = info.Style;
        }
        class MenuInfo
        {
            public MenuInfo(GridColumn column, DevExpress.XtraGrid.Columns.FixedStyle style)
            {
                this.Column = column;
                this.Style = style;
            }
            public DevExpress.XtraGrid.Columns.FixedStyle Style;
            public GridColumn Column;
        }
        #endregion

设置自动增加的行号

this.gridView1.IndicatorWidth = 30;//设置显示行号的列宽

private void gridview_CustomDrawRowIndicator(object sender,DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e){

     e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
     if(e.Info.IsRowIndicator){
        if(e.RowHandle >= 0){
            e.Info.DisplayText = (e.RowHandle + 1).ToString();                 
        }else if(e.RowHandle > -1000 && e.RowHandle < 0){
            e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite;
            e.Info.DisplayText = "G" + e.RowHandle.ToString();                 
        }             
     }
}

在查询得到 0 条记录时, 显示自定义的字符提示

// When no Records Are Being Displayed
private void gridView1_CustomDrawEmptyForeground(object sender, CustomDrawEventArgs e)
{
    // 方法一(此方法为GridView设置了数据源绑定时,可用)
    ColumnView columnView = sender as ColumnView;
    BindingSource bindingSource = this.gridView1.DataSource as BindingSource;
    if(bindingSource.Count == 0){
        string str = "没有查询到你所想要的数据!";
        Font f = new Font("宋体", 10, FontStyle.Bold);        
        var tmpLeft = e.Bounds.Left + 5;
        var tmpTop = e.Bounds.Top + 5;
        var tmpWidth = e.Bounds.Width - 5;
        var tmpHeight = e.Bounds.Height - 5;
        Rectangle r = new Rectangle(tmpLeft, tmpTop, tmpWidth, tmpHeight);
        e.Graphics.DrawString(str, f, Brushes.Black, rect); 
    }
}
// 方法二(此方法 适用于: GridView 没有设置数据源时)
if (this._flag){
 if (this.gridView1.RowCount == 0){ 
    string str = "没有查询到你所想要的数据!"; 
    Font f = new Font("宋体", 10, FontStyle.Bold);
    var tmpLeft = e.Bounds.Left + 5;
    var tmpTop = e.Bounds.Top + 5;
    var tmpWidth = e.Bounds.Width - 5;
    var tmpHeight = e.Bounds.Height - 5;
    Rectangle r = new Rectangle(tmpLeft, tmpTop, tmpWidth, tmpHeight);
    e.Graphics.DrawString(str, f, Brushes.Black, r); 
 } 
}

到此这篇关于.Net使用XtraGrid控件绑定数据的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论