.Net使用XtraGrid控件绑定数据

目录
  • 设计数据源并绑定字段:
  • 表格数据与数据源的数据同步
  • 新增一条记录,添加行
  • 删除选中行
  • 获取选定行,指定列单元格的内容
  • Get/Set 单元格的值
  • 选中行改变绑定行数据到对应控件中
    • 1、判断是否有Focused行
    • 2、获取Focused行
    • 3、获取Focused行单元格的值
  • 动态添加列
  • 添加非绑定列
  • 编辑器
  • 添加按钮列
  • 数据验证
    • 1、使用RepositoryItem.Validating事件
    • 2、使用 GridView.ValidatingEditor 事件
    • 3、使用 GridView.ValidateRow事件
  • 添加CheckBox并支持多选操作.
  • 全选和反选
  • 重绘单元格或者行的显示,使用CustomDrawCell()事件
  • 数据导入导出
  • 导出到PDF
  • 行双击事件的处理
  • 定位到某数据/记录??
  • 禁止 各列头 移动\排序\改变列宽
  • 拖动滚动条时固定某一列
  • 设置自动增加的行号
  • 在查询得到 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属性,

可以选择以下固定方式:

  • a. 固定在左边、
  • b. 固定在右边、
  • c. 不固定。

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

#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控件绑定数据的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • ASP.NET数据绑定控件详解

    ListBox.GridView.Repeater这三个数据绑定控件的"高效分页",ListBox和GridView内置的有分页,但是其效率太低了,少量的数据还可以,大量的数据根本就没法用,Repeater控件本身不提供分页,但是在实际的开发中可能也会有用到分页,所以也会给大家讲一下,Repeater的分页. 好了,现在开始进入正题,先从比较常用的控件说起. 一.GridView控件 主要特点:支持删.改,排序.分页.外观设置.自定义显示数据 缺 点:影响程序性能.不支持插入操作 这个

  • ASP.NET数据绑定之GridView控件

    GridView 是 DataGrid的后继控件,在.net framework 2 中,虽然还存在DataGrid,但是GridView已经走上了历史的前台,取代DataGrid的趋势已是势不挡.  作用:其功能是在web页面中显示数据源中的数据.GridView和DataGrid功能相似,都是在web页面中显示数据源中的数据,将数据源中的一行数据,也就是一条记录,显示为在web页面上输出表格中的一行.     在此GirdView的详细属性和事件我不再阐述.下面我只是简单介绍一下GirdVi

  • 浅谈ASP.NET常用数据绑定控件优劣总结

    本文的初衷在于对Asp.net常用数据绑定控件进行一个概览性的总结,主要分析各种数据绑定控件各自的优缺点,以便在实际的开发中选用合适的控件进行数据绑定,以提高开发效率. 因为这些数据绑定控件大部分都已经封装的很好了,稍微有一些基础的朋友都可以很容易的上手使用,所以本文不涉及具体控件的使用,只在于分析各自的优劣点,但是在下一篇文章里,我会主要讲一下ListBox.GridView.Repeater这三个数据绑定控件的"高效分页",ListBox和GridView内置的有分页,但是其效率太

  • asp.net实现Gradview绑定数据库数据并导出Excel的方法

    本文实例讲述了asp.net实现Gradview绑定数据库数据并导出Excel的方法.分享给大家供大家参考,具体如下: protected void showData_Click(object sender, EventArgs e) { SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=test;User ID=sa;password=sa"); SqlDataA

  • ASP.NET数据绑定之DataList控件

    DataList控件是.NET中的一个控件.DataList控件以表的形式呈现数据(在属性生成器中可以编辑),通过该控件,您可以使用不同的布局来显示数据记录(使用模板编辑),例如,将数据记录排成列或行的形式.您可以对 DataList控件进行配置,使用户能够编辑或删除表中的记录(使用EditItemTemplate模板和SelectedItemTemplate模板).DataList控件不使用数据源控件的数据修改功能,您必须自己提供此代码. 一.DataList 与 Repeater比较    

  • ASP.NET数据绑定之Repeater控件

    在ASP.NET的学习过程中,其控件的学习和使用占了很大的一部分,本文为大家介绍一下控件Repeater控件的使用,用它来绑定后台数据,然后在客户端(浏览器)上显示出来! 一. Repeater控件 1.用途:使用模板循环显示数据. 2.包含的模板: <ItemTemplate></ItemTemplate> 项目模板(里面的数据正常显示) <AlternatingItemTemplate></AlternatingItemTemplate> 交错显示模板(

  • ASP.NET数据绑定之DataList控件实战篇

    上篇文章大概讲了DataList的一些基础知识,掌握这些知识在将来的应用中起到很大的作用,现在我们就开始讲上篇文章中说的基础知识做一个小例子.     首先,我机子的数据库中有一张person表,如下图所示. 现在,我们用DataList控件将表中的信息显示出来,并可以在DataList控件上对数据库中的表进行编辑操作.     1.首先用vs创建web应用程序,添加web窗体,在web窗体内拉入DataList控件,右击控件,选择编辑项模板,在这里我们能看到四个模板,其中两个是Selected

  • .Net使用XtraGrid控件绑定数据

    目录 设计数据源并绑定字段: 表格数据与数据源的数据同步 新增一条记录,添加行 删除选中行 获取选定行,指定列单元格的内容 Get/Set 单元格的值 选中行改变绑定行数据到对应控件中 1.判断是否有Focused行 2.获取Focused行 3.获取Focused行单元格的值 动态添加列 添加非绑定列 编辑器 添加按钮列 数据验证 1.使用RepositoryItem.Validating事件 2.使用 GridView.ValidatingEditor 事件 3.使用 GridView.Va

  • 浅析Bootstrip的select控件绑定数据的问题

    此问题让我倒弄了一下午时间,最后终于被我拿下.下面小编把我的功劳分享出来,以此来做个备份,同时也希望能帮助到大家. 具体详情如下所示: $(function(){ var stu_no = freeUrl(); var data, subname="",data2; var sbList = new Array(); $.ajax({ async: false , dataType: "json", contentType: "application/js

  • ASP.NET中DropDownList下拉框列表控件绑定数据的4种方法

    DropDownList Web 服务器控件使用户能够从预定义的列表中选择一项.它与 ListBox Web 服务器控件的不同之处在于,其项列表在用户单击下拉按钮之前一直处于隐藏状态.另外,DropDownList 控件与 ListBox 控件的不同之处还在于它不支持多重选择模式. DropDownList在html中的呈现对应的是select,下面让我们来看一下DropDownList绑定数据的几种方法. 一.把Array数组绑到DropDownList 复制代码 代码如下: string[]

  • C#开发WinForm清空DataGridView控件绑定的数据

    使用DataGridView控件绑定数据后有时需要清空绑定的数据,在清除DataGridView绑定的数据时: 1.设置DataSource为null this.dgvDemo.DataSource = null 这样虽然可以清空DataGridView绑定的数据,但是DataGridView的列也会被删掉. 2.用DataGridView.Row.Clear() this.dgvDemo.Rows.Clear() 使用这种方法会报错,提示“不能清除此列表”,报错信息如下: 以上两种方法都不是想

  • C#对XtraGrid控件实现主从表关系绑定

    1.准备源数据. /// <summary> /// 记录基础信息 /// </summary> public class DetailInfo { public DetailInfo() { this.ID = Guid.NewGuid().ToString(); } /// <summary> /// ID标识 /// </summary> public string ID { get; set; } /// <summary> /// 名称

  • 学习vue.js表单控件绑定操作

    本文实例为大家分享了vue.js表单控件绑定的具体代码,供大家参考,具体内容如下 html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表单控件绑定</title> </head> <body> <!-- v-model在表单控件元素上实现数据的双向绑定 -->

  • Vue 表单控件绑定的实现示例

    本文介绍了Vue 表单控件绑定的实现示例,感觉这个地方知识点挺多的,而且很重要,所以,今天添加一点小笔记. 基础用法 可以用 v-model 指令在表单控件元素上创建双向数据绑定.根据控件类型它自动选取正确的方法更新元素.尽管有点神奇,v-model 不过是语法糖,在用户输入事件中更新数据,以及特别处理一些极端例子. Text <span>Message is: {{ message }}</span> <br> <input type="text&qu

  • Vue.js事件处理器与表单控件绑定详解

    事件处理主要通过v-on这个指令来执行. 事件监听及方法处理 1.简单的可以直接内嵌在页面. 2.可以通过将方法定义在methods中,然后再v-on中执行 3.可以通过绑定给函数传递参数,还可以传递通过变量$event给函数传递原生DOM事件. <div id="app-1"> <button v-on:click="counter += 1">增加1</button> <p>这个按钮被点击了{{counter}}&

  • DropDownList控件绑定数据源的三种方法

    本文给大家分享web  中 DropDownList绑定数据源的几种方式,先给大家分享三种常见的方式,具体详情如下所示:  第一种 this.ddltype.DataTextField = "btName";//显示的值 this.ddltype.DataValueField = "btId";//获取dropdownlist中的值 ddltype.DataSource = service.GetBusinessTypeAll(""); this

  • 在ASP.NET 2.0中操作数据之四十六:使用SqlDataSource控件检索数据

    导言 到目前为止,我们探讨的教程是由表现层,业务逻辑层和数据访问层构成的层次体系结构.数据访问层和业务逻辑层分别在教程第一和第二章提到.在Displaying Data With the ObjectDataSource 这篇教程里,我们探讨了怎样用ASP.NET 2.0的新控件--ObjectDataSource控件在表现层展示数据. 本教程到目前为止用这种层次结构来处理数据.然而绕过这种体系结构,通过直接把数据查询和业务逻辑放在Web页面上,也可以达到直接在ASP.NET页面上访问,插入,更

随机推荐