广告
返回顶部
首页 > 资讯 > 后端开发 > ASP.NET >.Net使用XtraGrid控件绑定数据
  • 844
分享到

.Net使用XtraGrid控件绑定数据

2024-04-02 19:04:59 844人浏览 薄情痞子
摘要

目录设计数据源并绑定字段:表格数据与数据源的数据同步新增一条记录,添加行删除选中行获取选定行,指定列单元格的内容Get/Set 单元格的值选中行改变绑定行数据到对应控件中1、判断是否

设计数据源并绑定字段:

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

  • IList 接口,包括一维数组。List<T>等!
  • IListSource 接口,例如,DataTable 和 DataSet 类。
  • IBindingList 接口,例如,BindingList 类。
  • IBindingListView 接口,例如,BindingSource 类。

修改也是同步的

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

--结束END--

本文标题: .Net使用XtraGrid控件绑定数据

本文链接: https://www.lsjlt.com/news/150412.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • .Net使用XtraGrid控件绑定数据
    目录设计数据源并绑定字段:表格数据与数据源的数据同步新增一条记录,添加行删除选中行获取选定行,指定列单元格的内容Get/Set 单元格的值选中行改变绑定行数据到对应控件中1、判断是否...
    99+
    2022-11-13
  • 怎么使用DataGrid控件绑定数据
    要使用DataGrid控件绑定数据,您可以按照以下步骤进行操作:1. 首先,确保您已经在项目中添加了DataGrid控件。这通常涉及...
    99+
    2023-10-10
    DataGrid
  • winform数据绑定控件是什么
    WinForm数据绑定控件是一组用于将数据与Windows Forms应用程序中的控件进行绑定的工具和组件。这些控件包括数据源控件、...
    99+
    2023-10-12
    winform
  • 详解DataGridView控件的数据绑定
    目录一、非绑定模式二、绑定模式示例程序:1、界面设计如下图:2、代码实现如下:使用DataGridView控件,可以显示和编辑来自多种不同类型的数据源的表格数据。 将数据绑定到Dat...
    99+
    2022-11-13
  • ASP.NET实现Repeater控件的数据绑定
    Repeater基础 在aspx文件中加入Repeater 控件,在<ItemTemplate></ItemTemplate>包含的范围里加入自己控制的代码,...
    99+
    2022-11-13
  • 怎么实现DataGridView控件的数据绑定
    这篇文章主要介绍了怎么实现DataGridView控件的数据绑定,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。使用DataGridView控件,可以显示和编辑来自多种不同类型...
    99+
    2023-06-29
  • datagridview控件绑定数据的方式有哪些
    DataGridView控件可以通过以下方式绑定数据:1. 数据源绑定:使用DataGridView的DataSource属性将数据...
    99+
    2023-08-08
    datagridview
  • ASP.NET中怎么实现一个数据绑定控件
    本篇文章给大家分享的是有关ASP.NET中怎么实现一个数据绑定控件,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。ASP.NET数据绑定控件一.回顾如果你使用过ASP.NET内置...
    99+
    2023-06-18
  • C#开发WinForm清空DataGridView控件绑定的数据
    使用DataGridView控件绑定数据后有时需要清空绑定的数据,在清除DataGridView绑定的数据时: 1、设置DataSource为null this.dgvDemo.Da...
    99+
    2022-11-13
  • c#中datagridview控件绑定数据的方法有哪些
    在C#中,可以通过以下几种方法绑定数据到DataGridView控件:1. 使用DataTable:可以通过将DataTable对象...
    99+
    2023-08-08
    c# datagridview
  • js中如何使用事件on动态绑定数据以及绑定多个事件
    这篇文章将为大家详细讲解有关js中如何使用事件on动态绑定数据以及绑定多个事件,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。一.on('clcik')与$...
    99+
    2022-10-19
  • ASP.NET复合控件引发数据绑定事件的示例分析
    这篇文章主要为大家展示了“ASP.NET复合控件引发数据绑定事件的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“ASP.NET复合控件引发数据绑定事件的示例分析”这篇文章吧。生成数据绑定...
    99+
    2023-06-18
  • vue使用什么绑定数据
    本教程操作环境:windows7系统、vue3版,DELL G3电脑。Vue绑定数据的几种方式一、用双大括号 ‘{{}}’ 把数据给到页面<template> <div class="mainBody&qu...
    99+
    2023-05-14
    数据绑定 Vue
  • C#开发WinForm中怎么清空DataGridView控件绑定的数据
    本文小编为大家详细介绍“C#开发WinForm中怎么清空DataGridView控件绑定的数据”,内容详细,步骤清晰,细节处理妥当,希望这篇“C#开发WinForm中怎么清空DataGridView控件绑定的数据”文章能帮助大家解决疑惑,下...
    99+
    2023-06-29
  • 使用嵌套的Repeater控件和VisualC#.NET显示分层数据
    可以使用嵌套的Repeater控件和Visual C#.NET来显示分层数据。以下是一个示例:假设有以下数据结构:```csharp...
    99+
    2023-09-08
    C#
  • 如何在Flex数据绑定中使用数组
    这篇文章给大家分享的是有关如何在Flex数据绑定中使用数组的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。在Flex数据绑定中使用数组在使用数组进行工作时,比如Array或者ArrayCollection对象,可以...
    99+
    2023-06-17
  • AspNetAjaxPager,Asp.Net通用无刷新Ajax分页控件,支持多样式多数据绑定
    本控件可以对GridView,Repeater,DataGrid,DataList...几乎所有的.net数据绑定控件进行分页,全部无刷新,数据绑定部分可以使用存储过程也可以直...
    99+
    2022-06-07
    ajax分页 ASP.NET 数据绑定 数据
  • 使用Vue.js实现数据的双向绑定
    目录如何用Vue.js实现数据的双向绑定?1. 理解双向绑定2. 使用v-model指令3. 使用自定义组件实现双向绑定4. 数据劫持5. 模板引擎6.Object.definePr...
    99+
    2023-05-16
    Vue.js数据的双向绑定 Vue.js双向绑定
  • AngularJs中控制器、数据绑定、作用域的示例分析
    小编给大家分享一下AngularJs中控制器、数据绑定、作用域的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!1、控制器:概念:在angularJS中控制器是一个函数,用来向视图的...
    99+
    2022-10-19
  • React如何使用Hooks简化受控组件的状态绑定
    这篇文章主要介绍React如何使用Hooks简化受控组件的状态绑定,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!ECMAScript 6文章中大量用到了 ES6 语法,比如解构赋值和...
    99+
    2022-10-19
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作