您的位置:新葡亰496net > 奥门新萄京娱乐场 > gridview钦定单元格cell获取坐标,GridControl使用办法

gridview钦定单元格cell获取坐标,GridControl使用办法

发布时间:2019-10-30 00:30编辑:奥门新萄京娱乐场浏览(130)

    1 DevExpress.XtraGrid.Views.Grid.ViewInfo.GridViewInfo Info2 = gvQueryResult.GetViewInfo() as DevExpress.XtraGrid.Views.Grid.ViewInfo.GridViewInfo;
    2 DevExpress.XtraGrid.Views.Grid.ViewInfo.GridCellInfo cellInfo2 = Info2.GetGridCellInfo(gvQueryResult.GetRowHandle(11), gvQueryResult.Columns[3]);//(gvQueryResult.FocusedRowHandle, gvQueryResult.FocusedColumn);
    3 string m2 = cellInfo2.Bounds.X.ToString();
    4 string n2 = cellInfo2.Bounds.Y.ToString();
    5 txtGenData.Top = Convert.ToInt32(n2)   gctlQueryResult.Top;
    6 txtGenData.Left = Convert.ToInt32(m2)   gctlQueryResult.Left;
    7 btnGenData.Top = Convert.ToInt32(n2)   gctlQueryResult.Top - 1;
    8 btnGenData.Left = Convert.ToInt32(m2)   124   124   gctlQueryResult.Left;
    9 gvQueryResult.RefreshData();
    

    后生可畏、如何消除单击记录整行选中的标题

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using DevExpress.XtraEditors;
    using DevExpress.XtraEditors.Repository;
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

     

    View->OptionsBehavior->EditorShowMode 设置为:Click

            private void Form1_Load(object sender, EventArgs e)
            {
                var ds = new DataSet();
                ds.ReadXml(@"D:StoreInfo.xml");
                gridLookUpDevice.Properties.DataSource = ds.Tables[0];
                this.gridLookUpDevice.Properties.View.OptionsSelection.MultiSelect = true;
                this.gridLookUpDevice.CustomDisplayText = new DevExpress.XtraEditors.Controls.CustomDisplayTextEventHandler(gridLookUpDevice_CustomDisplayText);

     

    二、怎么样新添一条记下

                GridCheckMarksSelection gridCheckMarksDevice;

    //=============================================================================================================================

    (1)、gridView.AddNewRow()

                gridCheckMarksDevice = new GridCheckMarksSelection(gridLookUpDevice.Properties);

    dev gridview钦命单元格cell获取坐标   以上

    (2)、实现gridView_InitNewRow事件

                gridCheckMarksDevice.SelectionChanged = new GridCheckMarksSelection.SelectionChangedEventHandler(gridCheckMarksDevice_SelectionChanged);

    //=============================================================================================================================

    三、怎么样清除GridControl记录能获得而尚未体现出来的标题

                gridCheckMarksDevice.SelectAll(ds.Tables[0].DefaultView);

     

    gridView.populateColumns();

                gridLookUpDevice.Properties.Tag = gridCheckMarksDevice;
            }

     

    四、如何让行只好选拔而无法编辑(或编辑某风流洒脱单元格)

            private void gridCheckMarksDevice_SelectionChanged(object sender, EventArgs e)
            {
                if (ActiveControl is GridLookUpEdit)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (DataRowView rv in (sender as GridCheckMarksSelection).Selection)
                    {
                        if (sb.ToString().Length > 0) { sb.Append(", "); }
                        sb.Append(rv["StoreName"].ToString());
                    }
                    (ActiveControl as GridLookUpEdit).Text = sb.ToString();
                }
            }

     

    (1)、View->OptionsBehavior->EditorShowMode 设置为:Click

            public List<string> deviceList;
            public object m_sender;
            private void gridLookUpDevice_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
            {
                StringBuilder sb = new StringBuilder();
                GridCheckMarksSelection gridCheckMark = sender is GridLookUpEdit ? (sender as GridLookUpEdit).Properties.Tag as GridCheckMarksSelection : (sender as RepositoryItemGridLookUpEdit).Tag as GridCheckMarksSelection;
                if (gridCheckMark == null) return;
                foreach (DataRowView rv in gridCheckMark.Selection)
                {
                    if (sb.ToString().Length > 0) { sb.Append(", "); }
                    sb.Append(rv["StoreName"].ToString());
                }
                e.DisplayText = sb.ToString();

     

    (2)、View->OptionsBehavior->Editable 设置为:false

                deviceList = SelectAllDeviceCode(sender, e);
                m_sender = sender;
            }

    1.藏身最下边包车型地铁GroupPanel
    gridView1.OptionsView.ShowGroupPanel=false;

    五、怎样禁止使用GridControl中单击列弹出右键菜单

            private List<String> SelectAllDeviceCode(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
            {
                List<String> strDeviceCodeList = new List<String>();

    2.到手当前选定记录某字段的值
    sValue=Table.Rows[gridView1.FocusedRowHandle][FieldName].ToString();

    设置Run Design->OptionsMenu->EnableColumnMenu 设置为:false

                GridCheckMarksSelection gridCheckMark = sender is GridLookUpEdit ? (sender as GridLookUpEdit).Properties.Tag as GridCheckMarksSelection : (sender as RepositoryItemGridLookUpEdit).Tag as GridCheckMarksSelection;
                if (gridCheckMark == null) return null;
                foreach (DataRowView rv in gridCheckMark.Selection)
                {
                    String deviceCode = rv["StoreNo"].ToString();
                    strDeviceCodeList.Add(deviceCode);
                }
                return strDeviceCodeList;
            }
            //获取接纳的值
            private void ShowBarChart()
            {

    3.数额只读
    gridView1.OptionsBehavior.Editable=false;

    六、如何掩盖GridControl的GroupPanel表头

                if (m_sender != null)
                {
                    var sb = new StringBuilder();
                    GridCheckMarksSelection gridCheckMark = m_sender is GridLookUpEdit ? (m_sender as GridLookUpEdit).Properties.Tag as GridCheckMarksSelection : (m_sender as RepositoryItemGridLookUpEdit).Tag as GridCheckMarksSelection;
                    if (gridCheckMark != null)
                    {
                        int i = 0;
                        foreach (DataRowView rowView in gridCheckMark.Selection)
                        {
                            String deviceCode = rowView.Row["StoreNo"].ToString();
                            String deviceName = rowView.Row["StoreName"].ToString();
                            //MessageBox.Show(deviceCode);
                            if (!String.IsNullOrWhiteSpace(deviceCode))
                            {
                                if (i > 0)
                                {
                                    sb.Append(",");}
                                sb.Append(deviceCode);
                                i ;
                            }
                        }
                    }
                    MessageBox.Show(sb.ToString());
                }
            }
        }
    }

    4.不显示MasterDetailView
    gridView1.OptionsDetail.EnableMasterViewMode=false;

    设置Run Design->OptionsView->ShowGroupPanel 设置为:false

    创建类:GridCheckMarksSelection.cs
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using DevExpress.Utils.Drawing;
    using DevExpress.XtraEditors.Repository;
    using DevExpress.XtraGrid.Columns;
    using DevExpress.XtraGrid.Views.Base;
    using DevExpress.XtraGrid.Views.Grid;
    using DevExpress.XtraGrid.Views.Grid.ViewInfo;

    5.改换最下面的GroupPanel内容
    gridView1.GroupPanelText="柳生飘絮";

    七、怎样禁用GridControl中列头的过滤器

    namespace WindowsFormsApplication1
    {
        public class GridCheckMarksSelection
        {
            #region Fileds
            RepositoryItemGridLookUpEdit _currentRepository;

    6.安装数据源:
    gridControl1.DataSource = dt;
    绑定每一列的FiledName--属性
    对于Oracle数据库,全体的在设计器里写的顺序中的字段名必需大写,不然可能绑定不上字段,sqlserver未有那几个节制.

    过滤器如下图所示:

            protected ArrayList selection;
            protected String checkColumnFieldName = "CheckMarkSelection";
            RepositoryItemCheckEdit edit;
            const Int32 CheckboxIndent = 4;
            #endregion

    7.读写拷贝权限设置
    只读不可拷贝:
    ColumnViewOptionsBehavior.Editable = False

    图片 1

            #region Construct
            public GridCheckMarksSelection(RepositoryItemGridLookUpEdit repository)
                : this()
            {
                CurrentRepository = repository;
            }

    只读可拷贝:
    ColumnViewOptionsBehavior.Editable = True
    OptionsColumn.AllowEdit = True
    OptionsColumn.ReadOnly = True

    设置 Run Design->OptionsCustomization->AllowFilter 设置为:false

            public RepositoryItemGridLookUpEdit CurrentRepository
            {
                get { return _currentRepository; }
                set
                {
                    if (_currentRepository != value)
                    {
                        Detach();
                        Attach(value);
                    }
                }
            }

    可编辑:
    ColumnViewOptionsBehavior.Editable = True
    OptionsColumn.AllowEdit = True
    OptionsColumn.ReadOnly = False

    八、怎么着在询问得到0条记下时显得自定义的字符提醒/显示

            public GridCheckMarksSelection()
            {
                selection = new ArrayList();
                this.OnSelectionChanged();
            }
            #endregion

    8.模板列的装置:
    到Columns中,在他的天性中找到ColumnEdit.
    以LookUpEdit为例:
    首先从Designer左侧菜单In-Place Editor Repository中增添LookUpEdit.取名叫Re1.然后.在他的Columns属性中丰硕3列.Caption逐项为:编号,姓名,性别.FieldName依次为:FID,FNAME,FSEX.然后将Re1的NullText设置成空.
      AutoSearchColumnIndex属性设置为2.ImmediatePopup属性设置为True.
      SearchMode设置为OnlyInPopup.
      然后将以此模板列附加到大家地点提到的列1(也正是将列1的ColumnEdit属性设成Re1)
      最终大家还要在代码里面给Re1绑定数据源和展现项.
    Re1.DataSource = DALUse.Query("select fid,fname,fsex from dual").Tables[0];
    Re1.DisplayMember = "FSEX";
    Re1.ValueMember = "FNAME";

    如图所示:

            #region Attribute
            public ArrayList Selection
            {
                get { return selection; }
                set { selection = value; }
            }

    9.设某一列文字和标题局中显得
    gridView1.Columns[0].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
    gridView1.Columns[0].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;

    图片 2

            public Int32 SelectedCount { get { return selection.Count; } }
            #endregion

    10.去掉某一列上边包车型客车机关筛选成效(Filter)
    gridView1.Columns[0].OptionsFilter.AllowAutoFilter = false;
    gridView1.Columns[0].OptionsFilter.AllowFilter = false;
    gridView1.Columns[0].OptionsFilter.ImmediateUpdateAutoFilter = false;

    措施如下:

            #region GridSelect
            public object GetSelectedRow(Int32 index)
            { return selection[index]; }

    11.安装冻结列(左冻结)
    gridView1.Columns[0].Fixed= DevExpress.XtraGrid.Columns.FixedStyle.Left;

    //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);
              Rectangle r = new Rectangle(e.Bounds.Top 5, e.Bounds.Left 5, e.Bounds.Right - 5, e.Bounds.Height - 5);
              e.Graphics.DrawString(str, f, Brushes.Black, r);
         }
         //方法二(此措施为GridView未有安装数据源绑依期,使用,日常选拔此种方法)  
         if (this._flag)
         {
              if (this.gridView1.RowCount == 0)
              {
                   string str = "没有查询到您所想要的数额!";
                   Font f = new Font("宋体", 10, FontStyle.Bold);
                   Rectangle r = new Rectangle(e.Bounds.Left 5, e.Bounds.Top 5, e.Bounds.Width - 5, e.Bounds.Height - 5);
                   e.Graphics.DrawString(str, f, Brushes.Black, r);
              }
         }
    }

            public Int32 GetSelectedIndex(object row)
            { return selection.IndexOf(row); }

    12.获得单元格数据(0行0列)
    string ss=gridView1.GetRowCellDisplayText(0, gridView1.Columns[0]);
    string ss = gridView1.GetRowCellValue(0, gridView1.Columns[0]);

    九、怎么着显示等级次序滚动条?

            public void ClearSelection(GridView currentView)
            {
                selection.Clear();
                Invalidate(currentView);
                OnSelectionChanged();
            }

    13.装置单元格数据(将0行0列的单元格赋值123)
    gridView1.SetRowCellValue(0, gridView1.Columns[0], "123");

    设置this.gridView.OptionsView.ColumnAutoWidth = false;

            public void SelectAll(object sourceObject)
            {
                selection.Clear();
                if (sourceObject != null)
                {
                    if (sourceObject is ICollection)
                        selection.AddRange(((ICollection)sourceObject));
                    else
                    {
                        GridView currentView = sourceObject as GridView;
                        for (Int32 i = 0; i < currentView.DataRowCount; i )
                            selection.Add(currentView.GetRow(i));
                        Invalidate(currentView);
                    }
                }
                this.OnSelectionChanged();
            }

    13.手动加多dev的列
    DevExpress.XtraGrid.Columns.GridColumn Col1=new DevExpress.XtraGrid.Columns.GridColumn ();
    Col1.FieldName="FID";
    Col1.Visible=true;
    Col1.VisibleIndex=gridView1.Columns.Count;
    gridView1.Columns.Add(Col1);

    十、如何稳固到第一条数据/记录?

            public delegate void SelectionChangedEventHandler(object sender, EventArgs e);
            public event SelectionChangedEventHandler SelectionChanged;
            public void OnSelectionChanged()
            {
                if (SelectionChanged != null)
                {
                    EventArgs e = new EventArgs();
                    SelectionChanged(this, e);
                }
            }
            public void SelectGroup(GridView currentView, Int32 rowHandle, bool select)
            {
                if (IsGroupRowSelected(currentView, rowHandle) && select) return;
                for (Int32 i = 0; i < currentView.GetChildRowCount(rowHandle); i )
                {
                    Int32 childRowHandle = currentView.GetChildRowHandle(rowHandle, i);
                    if (currentView.IsGroupRow(childRowHandle))
                        SelectGroup(currentView, childRowHandle, select);
                    else
                        SelectRow(currentView, childRowHandle, select, false);
                }
                Invalidate(currentView);
            }

    14.装置自动增添的行号,要求先加多给gridview增加事件CustomDrawRowIndicator

    设置 this.gridView.MoveFirst()

            public void SelectRow(GridView currentView, Int32 rowHandle, bool select)
            {
                SelectRow(currentView, rowHandle, select, true);
            }

    private void gridview_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
    {
    if (e.Info.IsRowIndicator && e.RowHandle >= 0)
    e.Info.DisplayText = (e.RowHandle 1).ToString();
    }

    十后生可畏、如何牢固到下一条数据/记录?

            public void InvertRowSelection(GridView currentView, Int32 rowHandle)
            {
                if (currentView.IsDataRow(rowHandle))
                    SelectRow(currentView, rowHandle, !IsRowSelected(currentView, rowHandle));
                if (currentView.IsGroupRow(rowHandle))
                    SelectGroup(currentView, rowHandle, !IsGroupRowSelected(currentView, rowHandle));
            }

    15.删除: (修改了dgvdel里的datagridviewdel方法)
    public static void datagridviewdel_Dev(DevExpress.XtraGrid.Views.Grid.GridView Mydgv)
    {
    if (Message博克斯.Show("你显著要去除选中的记录吗?", "删除提醒", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, false) == DialogResult.Yes)
    {
    int iSelectRowCount = Mydgv.SelectedRowsCount;
    if (iSelectRowCount > 0)
    {
    Mydgv.DeleteSelectedRows();
    }
    }
    }

    设置 this.gridView.MoveNext()

            public bool IsGroupRowSelected(GridView currentView, Int32 rowHandle)
            {
                for (Int32 i = 0; i < currentView.GetChildRowCount(rowHandle); i )
                {
                    Int32 row = currentView.GetChildRowHandle(rowHandle, i);
                    if (currentView.IsGroupRow(row))
                    {
                        if (!IsGroupRowSelected(currentView, row)) return false;
                    }
                    else
                        if (!IsRowSelected(currentView, row)) return false;
                }
                return true;
            }

    1. 新扩张: (对于新添,其自己的AddNewRow方法就足以成功)
      private void btn_add_Click(object sender, EventArgs e)
      {
      gridView1.AddNewRow();
      }
      现实要是对于新加行还犹如何非常的设置,能够在它gridView1_InitNewRow事件中填入:
      private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
      {
      ColumnView View = sender as ColumnView;
      View.SetRowCellValue(e.RowHandle, View.Columns[0], gridView1.GetRowCellValue(gridView1.GetRowHandle(gridView1.RowCount - 2), gridView1.Columns[0])); //复制最终后生可畏行的多少到新行

    十九、如何稳固到最后一条数据/记录?

            public bool IsRowSelected(GridView currentView, Int32 rowHandle)
            {
                if (currentView.IsGroupRow(rowHandle))
                    return IsGroupRowSelected(currentView, rowHandle);

    View.SetRowCellValue(e.RowHandle, View.Columns[1], gridView1.GetRowCellValue(gridView1.GetRowHandle(gridView1.RowCount - 2), gridView1.Columns[1])); //复制最终后生可畏行的多少到新行

    设置 this.gridView.MoveLast()

                object row = currentView.GetRow(rowHandle);
                return GetSelectedIndex(row) != -1;
            }
            #endregion

    }

    十四、设置成二回选拔大器晚成行,並且无法被编辑

            #region Attach|Detach
            protected virtual void Attach(RepositoryItemGridLookUpEdit rep)
            {
                if (rep == null) return;
                selection.Clear();
                _currentRepository = rep;

    1. 保存 (第三方控件提供的RefreshData和RefreshDataSource方法对于保留数据都不佳使,最后照旧选用了Dgvsave的datagridviewsave方法,用这些点子就足以)

    this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
    this.gridView1.OptionsBehavior.Editable = false;
    this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;

                edit = _currentRepository.View.GridControl.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;

    18.特效:gridcontrol中有5种view 型式,普通的是gridview,然后分别为cardview、BandedView、Advanced BandedView、LayoutView;共5种。
    1)、view组中把OptionView下的viewmode 设置成“Carousel”就完毕这种“旋转木马”式的gridcontrol view 特效了
    2)、layoutView1.OptionsCarouselMode.PitchAngle 那天特性决定“旋转木马”的pitch angle 螺距角; 螺旋角; 螺旋升角; 俯仰角; 倾角; 节锥半角
    3)、Roll Angle 属性决定着倾侧角度
    4)、钦点数据源,展现数据:
    //展现数据
    private void showData(List<Employee > list)
    {
    DataTable dt = new DataTable("OneEmployee");
    dt.Columns.Add("Caption", System.Type.GetType("System.String"));
    dt.Columns.Add("Department", System.Type.GetType("System.String"));
    dt.Columns.Add("PhotoName", System.Type.GetType("System.Byte[]"));

    十五、怎么样体现行号?

                GridColumn column = _currentRepository.View.Columns.Add();
                column.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
                column.Visible = true;
                column.VisibleIndex = 0;
                column.FieldName = checkColumnFieldName;
                column.Caption = "Mark";
                column.OptionsColumn.ShowCaption = false;
                column.OptionsColumn.AllowEdit = false;
                column.OptionsColumn.AllowSize = false;
                column.UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
                column.Width = GetCheckBoxWidth();
                column.ColumnEdit = edit;

    for (int i = 0; i < list.Count; i )
    {
    DataRow dr = dt.NewRow();
    dr["Caption"] = list[i].Name;
    dr["Department"] = list[i].Department;
    string imagePath = @"D:C#photos" list[i].PhotoPath;
    dr["PhotoName"] = getImageByte(imagePath);
    dt.Rows.Add(dr);
    }
    gridControl1.DataSource = dt;
    }

    this.gridView1.IndicatorWidth = 40; 
    //显示行的序号 
    private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
    {
         if (e.Info.IsRowIndicator && e.RowHandle>=0)
         {
              e.Info.DisplayText = (e.RowHandle 1).ToString();
         }
    }

                _currentRepository.View.Click = new EventHandler(View_Click);
                _currentRepository.View.CustomDrawColumnHeader = new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
                _currentRepository.View.CustomDrawGroupRow = new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
                _currentRepository.View.CustomUnboundColumnData = new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
                _currentRepository.View.KeyDown = new KeyEventHandler(view_KeyDown);
            }

    //再次回到图片的字节流byte[]
    private byte[] getImageByte(string imagePath)
    {
    FileStream files = new FileStream(imagePath, FileMode.Open);
    byte[] imgByte = new byte [files.Length ];
    files.Read(imgByte, 0, imgByte.Length);
    files.Close();
    return imgByte;
    }

    十二、咋样让各列头防止移动?

            protected virtual void Detach()
            {
                if (_currentRepository == null) return;
                if (edit != null)
                {
                    _currentRepository.View.GridControl.RepositoryItems.Remove(edit);
                    edit.Dispose();
                }
                _currentRepository.View.Click -= new EventHandler(View_Click);
                _currentRepository.View.CustomDrawColumnHeader -= new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
                _currentRepository.View.CustomDrawGroupRow -= new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
                _currentRepository.View.CustomUnboundColumnData -= new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
                _currentRepository.View.KeyDown -= new KeyEventHandler(view_KeyDown);
                _currentRepository = null;
            }

    19.检查数据的管事
    在gridview的ValidateRow事件中加入检查代码:
    #region 检查数据
    private void gridView1_ValidateRow(object sender, ValidateRowEventArgs e)
    {
    GridView view = sender as GridView;
    view.ClearColumnErrors();

    设置gridView1.OptionsCustomization.AllowColumnMoving = false;

            void Invalidate(GridView currentView)
            {
                currentView.BeginUpdate();
                currentView.EndUpdate();
            }
            void SelectRow(GridView currentView, Int32 rowHandle, bool select, bool invalidate)
            {
                if (IsRowSelected(currentView, rowHandle) == select) return;
                object row = currentView.GetRow(rowHandle);
                if (select)
                    selection.Add(row);
                else
                    selection.Remove(row);
                if (invalidate)
                    Invalidate(currentView);
                OnSelectionChanged();
            }
            void view_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
            {
                GridView currentView = sender as GridView;
                if (e.Column != null && e.Column.FieldName == checkColumnFieldName)
                {
                    if (e.IsGetData)
                        e.Value = IsRowSelected(currentView, currentView.GetRowHandle(e.ListSourceRowIndex));
                    else
                        SelectRow(currentView, currentView.GetRowHandle(e.ListSourceRowIndex), (bool)e.Value);
                }
            }
            void view_KeyDown(object sender, KeyEventArgs e)
            {
                GridView currentView = sender as GridView;
                if (currentView.FocusedColumn.FieldName != checkColumnFieldName || e.KeyCode != Keys.Space) return;
                InvertRowSelection(currentView, currentView.FocusedRowHandle);
            }
            void View_Click(object sender, EventArgs e)
            {
                GridHitInfo info;
                GridView currentView = (sender as GridView);
                Point pt = currentView.GridControl.PointToClient(Control.MousePosition);
                info = currentView.CalcHitInfo(pt);
                if (info.Column != null && info.Column.FieldName == checkColumnFieldName)
                {
                    if (info.InColumn)
                    {
                        if (SelectedCount == currentView.DataRowCount)
                            ClearSelection(currentView);
                        else
                            SelectAll(currentView);
                    }
                    if (info.InRowCell)
                        InvertRowSelection(currentView, info.RowHandle);
                }
                if (info.InRow && currentView.IsGroupRow(info.RowHandle) && info.HitTest != GridHitTest.RowGroupButton)
                    InvertRowSelection(currentView, info.RowHandle);
            }
            void View_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
            {
                if (e.Column != null && e.Column.FieldName == checkColumnFieldName)
                {
                    e.Info.InnerElements.Clear();
                    e.Painter.DrawObject(e.Info);
                    DrawCheckBox(e.Graphics, e.Bounds, SelectedCount == (sender as GridView).DataRowCount);
                    e.Handled = true;
                }
            }
            void View_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e)
            {
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo info;
                info = e.Info as DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo;

    if (view.GetRowCellValue(e.RowHandle, "ReceiveDate") == DBNull.Value)
    {
    e.Valid = false;
    view.SetColumnError(view.Columns["ReceiveDate"], "必得钦定日期");
    }

    十二、怎样让各列头制止排序?

                info.GroupText = "         " info.GroupText.TrimStart();
                e.Info.Paint.FillRectangle(e.Graphics, e.Appearance.GetBackBrush(e.Cache), e.Bounds);
                e.Painter.DrawObject(e.Info);

    }
    #endregion
    调用gridview.UpdateCurrentRow()方法试行检查

    设置gridView1.OptionsCustomization.AllowSort = false;

                Rectangle r = info.ButtonBounds;
                r.Offset(r.Width CheckboxIndent * 2 - 1, 0);
                DrawCheckBox(e.Graphics, r, IsGroupRowSelected((sender as GridView), e.RowHandle));
                e.Handled = true;
            }
            #endregion

    最常用的DevExpress Winform 4个代码片段:

    十五、怎么着禁绝各列头退换列宽?

            #region CheckBox
            protected Int32 GetCheckBoxWidth()
            {
                DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info = edit.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
                Int32 width = 0;
                GraphicsInfo.Default.AddGraphics(null);
                try
                {
                    width = info.CalcBestFit(GraphicsInfo.Default.Graphics).Width;
                }
                finally
                {
                    GraphicsInfo.Default.ReleaseGraphics();
                }
                return width CheckboxIndent * 2;
            }

    意气风发 、GridControl的删减操作

    设置gridView1.OptionsCustomization.AllowColumnResizing = false;
    Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE

            protected void DrawCheckBox(Graphics g, Rectangle r, bool Checked)
            {
                DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info;
                DevExpress.XtraEditors.Drawing.CheckEditPainter painter;
                DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs args;
                info = edit.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
                painter = edit.CreatePainter() as DevExpress.XtraEditors.Drawing.CheckEditPainter;
                info.EditValue = Checked;
                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();
            }
            #endregion
        }
    }

    private void rILinkEditInfoDel_Click(object sender, EventArgs e)
    {
    if (XtraMessageBox.Show("请鲜明是或不是删除当前记下?", "警示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
    {
    DataRow row = gvInfos.GetDataRow(gvInfos.FocusedRowHandle);
    delByCode(row["Code"].ToString());
    XtraMessageBox.Show("操作成功!");
    }
    }

    DEV控件:gridControl常用属性设置

    二、绑定非数据表中列

    2011-01-19 09:50

    Hashtable ht = new Hashtable();

    1.潜藏最上面的GroupPanel
      gridView1.OptionsView.ShowGroupPanel=false;

    gridview钦定单元格cell获取坐标,GridControl使用办法总计2。private void gridView6_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
    {
    GridView View = sender as GridView;
    if (e.RowHandle >= 0)
    {
    object needAlert = View.GetRowCellValue(e.RowHandle, View.Columns["needAlert"]);
    if (needAlert != null & needAlert != DBNull.Value && needAlert.ToString().Trim() != "0" & View.GetRowCellValue(e.RowHandle, View.Columns["Value"]) != DBNull.Value)
    {
    decimal AverValue = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle, View.Columns["Value"]));
    object MinValue = View.GetRowCellValue(e.RowHandle, View.Columns["MinValue"]);
    object MaxVlaue = View.GetRowCellValue(e.RowHandle, View.Columns["MaxValue"]);
    if (MinValue != DBNull.Value & MinValue != null & MaxVlaue.ToString() != "" & MaxVlaue != DBNull.Value && MaxVlaue != null & MaxVlaue.ToString() != "")
    {
    decimal gridColumn2 = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle, View.Columns["MinValue"]));
    decimal gridColumn1 = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle, View.Columns["MaxValue"]));
    if (gridColumn2 > AverValue || AverValue > gridColumn1)
    {
    if (!ht.ContainsKey("pic"))
    ht.Add("pic", GetImage(1));
    e.Value = ht["pic"];
    }
    }
    }
    }
    }

    2.收获当前选定记录某字段的值
      sValue=Table.Rows[gridView1.FocusedRowHandle][FieldName].ToString();

    /// <summary>
    /// 由能源文件获取图片
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    byte[] GetImage(int key)
    {
    Image img = DevExpress.Utils.Controls.ImageHelper.CreateImageFromResources(string.Format("RiverSys.Resources.{0}.gif", key.ToString()), typeof(RiverInfos).Assembly);
    return DevExpress.XtraEditors.Controls.ByteImageConverter.ToByteArray(img, ImageFormat.Gif);
    }

    3.数额只读
      gridView1.OptionsBehavior.Editable=false;

    /// <summary>
    /// 动态依照条件设置行样式
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void gridView6_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
    {
    GridView View = sender as GridView;
    if (e.RowHandle >= 0)
    {
    object needAlert = View.GetRowCellValue(e.RowHandle, View.Columns["needAlert"]);
    if (needAlert != null & needAlert != DBNull.Value && needAlert.ToString().Trim() != "0" & View.GetRowCellValue(e.RowHandle, View.Columns["Value"]) != DBNull.Value)
    {
    decimal AverValue = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle, View.Columns["Value"]));
    object MinValue = View.GetRowCellValue(e.RowHandle, View.Columns["MinValue"]);
    object MaxVlaue = View.GetRowCellValue(e.RowHandle, View.Columns["MaxValue"]);
    gridview钦定单元格cell获取坐标,GridControl使用办法总计2。if (MinValue != DBNull.Value & MinValue != null & MaxVlaue.ToString() != "" & MaxVlaue != DBNull.Value && MaxVlaue != null & MaxVlaue.ToString() != "")
    {
    decimal gridColumn2 = Convert.ToDecimal(MinValue);
    decimal gridColumn1 = Convert.ToDecimal(MaxVlaue);
    if (gridColumn2 > AverValue || AverValue > gridColumn1)
    {
    e.Appearance.ForeColor = Color.Red;
    e.Appearance.BackColor = Color.LightGray;
    }
    }
    }
    }
    }

    4.不显示MasterDetailView
      gridView1.OptionsDetail.EnableMasterViewMode=false;

    三、GridControl 中颜色筛选控件

    5.校订最下边包车型大巴GroupPanel内容
       gridView1.GroupPanelText="柳生飘絮";

    private void gvMapColor_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
    {
    GridView view = sender as GridView;
    DataView dv = view.DataSource as DataView;
    if (e.IsGetData)
    {
    string strVal = dv[e.ListSourceRowIndex]["Color"].ToString();
    if (strVal != "")
    {
    //e.Value = DevExpress.Utils.StyleLayout.ColorFromString(strVal);
    e.Value = Common.HexToColor(strVal);
    }
    }
    else
    {
    //Color colorVal = DevExpress.Utils.StyleLayout.ColorFromString(e.Value.ToString());
    Color colorVal = (Color)e.Value;
    dv[e.ListSourceRowIndex]["Color"] = Common.RGB_HEX(colorVal.ToArgb());
    }
    }

    6.安装数据源:
       gridControl1.DataSource = dt;
       绑定每一列的FiledName--属性
       对于Oracle数据库,全体的在设计器里写的顺序中的字段名必得大写,否则只怕绑定不上字段,sqlserver未有这么些节制.

    四、关于 GridControl 验证示例

    7.读写拷贝权限设置
      只读不可拷贝:
        ColumnViewOptionsBehavior.Editable = False

    /// <summary>
    /// 最早化GridView,绑定数据
    /// </summary>
    /// <param name="parentId"></param>
    private void GridViewBindData(string parentId)
    {
    this.gridView1.Columns.Clear();
    this.FDs= areaSetupActionHelper.getDsRegionByParentId(parentId);
    this.gridCArea.DataSource =this.FDs.Tables[0].DefaultView;

      只读可拷贝:
        ColumnViewOptionsBehavior.Editable = True
        OptionsColumn.AllowEdit = True
        OptionsColumn.ReadOnly = True

    this.gridView1.Columns["id"].VisibleIndex = -1;
    this.gridView1.Columns["childCounts"].VisibleIndex = -1;

      可编辑:
        ColumnViewOptionsBehavior.Editable = True
        OptionsColumn.AllowEdit = True
        OptionsColumn.ReadOnly = False

    this.gridView1.Columns["reg_id"].Caption = "区划编号";
    this.gridView1.Columns["reg_name"].Caption = "区划名称";
    this.gridView1.Columns["parent_id"].Caption = "父区划编号";
    this.gridView1.Columns["reg_desc"].Caption = "区划描述";
    this.gridView1.Columns["parent_id"].ImageIndex =1;
    this.gridView1.Columns["reg_desc"].ImageIndex = 0;

    8.模板列的设置:
      到Columns中,在他的习性中找到ColumnEdit.
      以LookUpEdit为例:
      首先从Designer左侧菜单In-PlaceEditor Repository中加多LookUpEdit.取名字为Re1.然后.在他的Columns属性中加上3列.Caption顺序为:编号,姓名,性别.FieldName依次为:FID,FNAME,FSEX.然后将Re1的NullText设置成空.
      AutoSearchColumnIndex属性设置为2.ImmediatePopup属性设置为True.
      SearchMode设置为OnlyInPopup.
      然后将这几个模板列附加到大家地点提到的列1(相当于将列1的ColumnEdit属性设成Re1)
      最终大家还要在代码里面给Re1绑定数据源和显示项.
             Re1.DataSource =DALUse.Query("select fid,fname,fsex from dual").Tables[0];
             Re1.DisplayMember ="FSEX";
             Re1.ValueMember ="FNAME";

    RepositoryItemTextEdit textEditReg_Id = new RepositoryItemTextEdit();
    textEditReg_Id.Mask.EditMask =parentId "file://d{2,3/}";
    textEditReg_Id.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Regular;

     

    this.gridView1.Columns["reg_id"].ColumnEdit = textEditReg_Id;

    9.设某一列文字和标题局中展现                 
       gridView1.Columns[0].AppearanceHeader.TextOptions.HAlignment =DevExpress.Utils.HorzAlignment.Center;
       gridView1.Columns[0].AppearanceCell.TextOptions.HAlignment =DevExpress.Utils.HorzAlignment.Center;

    this.gridView1.Columns["reg_desc"].ColumnEdit = new RepositoryItemMemoExEdit();

     
    10.去掉某一列下边的机动筛选功效(Filter)                 
       gridView1.Columns[0].OptionsFilter.AllowAutoFilter = false;
       gridView1.Columns[0].OptionsFilter.AllowFilter =false;               
       gridView1.Columns[0].OptionsFilter.ImmediateUpdateAutoFilter =false;

    TreeListNode node = this.treelArea.FocusedNode.ParentNode;
    string fid = node==null?"0":node.GetValue("RegID").ToString().Trim();
    DataSet ds = areaSetupActionHelper.getDsRegionByParentId(fid);
    RepositoryItemLookUpEdit lookUEParent_Id = new RepositoryItemLookUpEdit();
    lookUEParent_Id.Columns.Add(new LookUpColumnInfo("reg_id", 40, "区划编号"));
    lookUEParent_Id.Columns.Add(new LookUpColumnInfo("reg_name", 40, "区划名称"));
    lookUEParent_Id.DataSource = ds.Tables[0].DefaultView;
    lookUEParent_Id.ValueMember = "reg_id";
    lookUEParent_Id.DisplayMember = "reg_id";
    this.gridView1.Columns["parent_id"].ColumnEdit = lookUEParent_Id;
    }
    /// <summary>
    /// gridView单元格验证的相关管理程序
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void gridView1_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
    {
    if (e.Valid == false&this.gridView1.FocusedColumn.FieldName == "reg_id")
    {
    e.ErrorText = "区划编号违法!n应该为父区划编号加2~3位数据整合!";
    }
    if (this.gridView1.FocusedColumn.FieldName == "reg_name")
    {
    Regex reg=new Regex(@"[u4e00-u9fa5]{1,20}");
    Match m=reg.Match(e.Value.ToString().Trim());
    if (m.Length != e.Value.ToString().Trim().Length)
    {
    e.Valid = false;
    e.ErrorText = "区划名称应该为汉字n长度为1至20";
    }
    }
    }

     
    11.安装冻结列(左冻结)
      gridView1.Columns[0].Fixed= DevExpress.XtraGrid.Columns.FixedStyle.Left;

    private void gridView1_InvalidValueException(object sender, InvalidValueExceptionEventArgs e)
    {
    if (MyDialog.Alert(" 您所填写的内容不符合法则n 要扬弃您刚刚对此项所做的退换吗?", "您所编写的内容不合乎准则", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
    {
    e.ExceptionMode = ExceptionMode.Ignore;
    }
    }

     
    12.拿走单元格数据(0行0列)
       string ss=gridView1.GetRowCellDisplayText(0,gridView1.Columns[0]);
       string ss = gridView1.GetRowCellValue(0, gridView1.Columns[0]);

    /// <summary>
    /// gridView行验证的连带管理程序
    /// </summary>
    private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
    {
    string regid = this.gridView1.GetRowCellValue(e.RowHandle, "reg_id").ToString().Trim();
    string regName = this.gridView1.GetRowCellValue(e.RowHandle, "reg_name").ToString().Trim();
    if ( regid.Length < 1)
    {
    e.Valid = false;
    this.gridView1.SetColumnError(this.gridView1.Columns["reg_id"], "请填入区划编号!", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
    // e.ErrorText = "区划名称无法为空!";
    }
    if (regName.Length < 1)
    {
    e.Valid = false;
    this.gridView1.SetColumnError(this.gridView1.Columns["reg_name"], "区划名称无法为空!", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
    }
    }

     
    13.安装单元格数据(将0行0列的单元格赋值123)
       gridView1.SetRowCellValue(0, gridView1.Columns[0],"123");

    private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
    {

     
    13.手动增加dev的列
      DevExpress.XtraGrid.Columns.GridColumn Col1=newDevExpress.XtraGrid.Columns.GridColumn ();
      Col1.FieldName="FID";
      Col1.Visible=true;
      Col1.VisibleIndex=gridView1.Columns.Count;
      gridView1.Columns.Add(Col1);

    if (e.RowHandle >= 0)
    {
    if (this.gridView1.GetRowCellValue(e.RowHandle, this.gridView1.Columns["reg_id"]).ToString().Trim() == "" || this.gridView1.GetRowCellValue(e.RowHandle, this.gridView1.Columns["reg_name"]).ToString().Trim() == "")
    {
    if (MyDialog.Alert("  您所填写的剧情不切合准绳n 要吐弃您刚刚对此项所做的改观吗?", "您所编写的开始和结果不适合法规", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
    {
    e.ExceptionMode = ExceptionMode.Ignore;
    }
    else
    {
    e.ExceptionMode = ExceptionMode.NoAction;
    }
    }
    }
    else
    {
    e.ExceptionMode = ExceptionMode.Ignore;
    }
    }

    14.设置自动扩展的行号,须要先增加给gridview增添事件CustomDrawRowIndicator

    关于XtraGrid的运用(GridControl小结)来源:51编制程序网宣布时间:贰零零玖-04-19Hits:146
    DevExpress XtraGrid的使用(AspxGridControl小结)收藏

     

    自定义核心行的艺术: gridView_bcode.FocusedRowHandle = focuseRowInt; //通过设置GridView 的FocusedRowHandle属性

        private void gridview_CustomDrawRowIndicator(objectsender,                           DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator &&e.RowHandle >= 0)
                   e.Info.DisplayText = (e.RowHandle 1).ToString();
        }

    view plaincopy to clipboardprint?
    //获取关节行放肆单元格的数码
    ColumnView cv = (ColumnView)gridControl_Gongzi.FocusedView;//重新获取此ID 不然不或许从表头连删获取不到id
    int focusedhandle = cv.FocusedRowHandle;
    object rowIdObj = gridView1.GetRowCellValue(focusedhandle, "id");
    if (DBNull.Value != rowIdObj)
    {
    FocusedRow_id = Convert.ToInt32(rowIdObj);
    }
    //获取关节行恣意单元格的多寡
    ColumnView cv = (ColumnView)gridControl_Gongzi.FocusedView;//重新获取此ID 不然无从从表头连删获取不到id
    int focusedhandle = cv.FocusedRowHandle;
    object rowIdObj = gridView1.GetRowCellValue(focusedhandle, "id");
    if (DBNull.Value != rowIdObj)
    {
    FocusedRow_id = Convert.ToInt32(rowIdObj);
    }
    view plaincopy to clipboardprint?
    //当数码产生变化时施行
    private void gridView1_CellValueChanged(object sender, CellValueChangedEventArgs e)
    {
    int intRowHandle = e.RowHandle;
    FocusedRow_bumen = Convert.ToString(gridView1.GetRowCellValue(intRowHandle, "bumen"));
    FocusedRow_xingming = Convert.ToString(gridView1.GetRowCellValue(intRowHandle, "xingming"));
    //FocusedRow_jibengongzi = Convert.ToDecimal(gridView1.GetRowCellValue(intRowHandle, "jibengongzi"));
    object rowJibengongziObj = gridView1.GetRowCellValue(intRowHandle, "jibengongzi");
    if (DBNull.Value != rowJibengongziObj)
    {
    FocusedRow_jibengongzi = Convert.ToDecimal(rowJibengongziObj);
    }
    }
    //当数码爆发变化时实践
    private void gridView1_CellValueChanged(object sender, CellValueChangedEventArgs e)
    {
    int intRowHandle = e.RowHandle;
    FocusedRow_bumen = Convert.ToString(gridView1.GetRowCellValue(intRowHandle, "bumen"));
    FocusedRow_xingming = Convert.ToString(gridView1.GetRowCellValue(intRowHandle, "xingming"));
    //FocusedRow_jibengongzi = Convert.ToDecimal(gridView1.GetRowCellValue(intRowHandle, "jibengongzi"));
    object rowJibengongziObj = gridView1.GetRowCellValue(intRowHandle, "jibengongzi");
    if (DBNull.Value != rowJibengongziObj)
    {
    FocusedRow_jibengongzi = Convert.ToDecimal(rowJibengongziObj);
    }
    } view plaincopy to clipboardprint?
    //设置大旨行的节骨眼单元格的职位
    ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView;
    view.FocusedColumn = view.Columns["bumen"];
    //设置大旨行的枢纽单元格的职位
    ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView;
    view.FocusedColumn = view.Columns["bumen"]; view plaincopy to clipboardprint?
    //当难点行发生改变时实践获取选中核心行id
    private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
    {
    int intRowHandle = e.FocusedRowHandle;

    15.删除: (修改了dgvdel里的datagridviewdel方法)
        public static voiddatagridviewdel_Dev(DevExpress.XtraGrid.Views.Grid.GridView Mydgv)
        {
           if (MessageBox.Show("你鲜明要刨除选中的记录吗?", "删除提醒",MessageBoxButtons.YesNo,              MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, false) == DialogResult.Yes)
           {
               intiSelectRowCount = Mydgv.SelectedRowsCount;
               if(iSelectRowCount > 0)
               {
                Mydgv.DeleteSelectedRows();
               }
           }
        }
     
    16. 骤增: (对于新扩大,其本身的AddNewRow方法就足以成功)
        private void btn_add_Click(object sender, EventArgs e)
        {  
           gridView1.AddNewRow();   
         }
        具体假如对于新加行还应该有何样特别的装置,能够在它gridView1_InitNewRow事件中填入:
        private void gridView1_InitNewRow(object sender,DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
           ColumnView View = sender as ColumnView;
           View.SetRowCellValue(e.RowHandle,View.Columns[0],gridView1.GetRowCellValue(gridView1.GetRowHandle(gridView1.RowCount

    object rowIdObj = gridView1.GetRowCellValue(intRowHandle, "id");

    • 2),gridView1.Columns[0])); //复制最终风华正茂行的数量到新行

    if (DBNull.Value != rowIdObj)//做个判定不然获取不到id后报错
    {
    FocusedRow_id = Convert.ToInt32(rowIdObj);
    }
    }
    //当难点行发生变动时实行 获取选中要害行id
    private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
    {
    int intRowHandle = e.FocusedRowHandle;

               View.SetRowCellValue(e.RowHandle, View.Columns[1],gridView1.GetRowCellValue(gridView1.GetRowHandle(gridView1.RowCount

    object rowIdObj = gridView1.GetRowCellValue(intRowHandle, "id");

    • 2),gridView1.Columns[1])); //复制最生平机勃勃行的数目到新行

    if (DBNull.Value != rowIdObj)//做个判定不然获取不到id后报错
    {
    FocusedRow_id = Convert.ToInt32(rowIdObj);
    }
    }

        }

    view plaincopy to clipboardprint?
    //焦点行的FocusedHandle为:
    FocuseRow_Handle = -999998;
    //获取核心行的handle
    ColumnView newview = (ColumnView)gridControl_Gongzi.FocusedView;

     
    17. 保存 (第三方控件提供的RefreshData和RefreshDataSource方法对于保存数据都不好使,最后照旧利用了Dgvsave的datagridviewsave方法,用这一个情势就足以)

    FocuseRow_Handle = newview.FocusedRowHandle;
    //回车增加新行
    private void gridView1_KeyPress(object sender, KeyPressEventArgs e)

    18.特效:gridcontrol中有5种view 型式,普通的是gridview,然后分别为cardview、BandedView、AdvancedBandedView、LayoutView;共5种。
      1)、view组中把OptionView下的viewmode 设置成“Carousel”就直达这种“旋转木马”式的gridcontrolview 特效了
      2)、layoutView1.OptionsCarouselMode.PitchAngle 这么些性格决定“旋转木马”的pitch angle 螺距角; 螺旋角; 螺旋升角; 俯仰角; 倾角; 节锥半角 
      3)、Roll Angle 属性决定着 倾侧角度
      4)、钦赐数据源,展现数据:
      //展现数据
            private voidshowData(List<Employee > list)
            {
                DataTable dt= new DataTable("OneEmployee");
               dt.Columns.Add("Caption", System.Type.GetType("System.String"));
               dt.Columns.Add("Department",System.Type.GetType("System.String"));
               dt.Columns.Add("PhotoName",System.Type.GetType("System.Byte[]"));

    {
    if (e.KeyChar == 13)
    {
    ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView;
    if(view.IsLastRow)
    {
    if (FocuseRow_Handle == 0)
    {
    gridView1.AddNewRow();

                for(int i = 0; i < list.Count; i )
                {
                   DataRow dr = dt.NewRow();
                   dr["Caption"] = list[i].Name;
                   dr["Department"] = list[i].Department;
                   string imagePath = @"D:C#photos" list[i].PhotoPath;
                   dr["PhotoName"] = getImageByte(imagePath);
                   dt.Rows.Add(dr);
                }
               gridControl1.DataSource = dt;
            }

    ColumnView newview = (ColumnView)gridControl_Gongzi.FocusedView;

            //再次回到图片的字节流byte[]
            private byte[] getImageByte(stringimagePath)
            {
                FileStreamfiles = new FileStream(imagePath, FileMode.Open);
                byte[]imgByte = new byte [files.Length ];
               files.Read(imgByte, 0, imgByte.Length);
               files.Close();
                returnimgByte;
            }

    newview.FocusedColumn = newview.Columns["bumen"];//定位难点网格的职务

    19.检查数据的得力
      在gridview的ValidateRow事件中步向检查代码:
      #region 检查数据
      private void gridView1_ValidateRow(object sender, ValidateRowEventArgse)
      {
      GridView view = sender as GridView;
      view.ClearColumnErrors();

    FocuseRow_Handle = newview.FocusedRowHandle;//获取新主题行的FocuseRowHandle 并发轫化全局变量FocuseRow_Handle供保存操作时剖断是update如故insert

      if (view.GetRowCellValue(e.RowHandle, "ReceiveDate") ==DBNull.Value)
      {
      e.Valid = false;
      view.SetColumnError(view.Columns["ReceiveDate"], "必需钦定日期");
      }

      }
      #endregion
      调用gridview.UpdateCurrentRow()方法施行检查

    最常用的DevExpress Winform 4个代码片段:

    风流倜傥 、GridControl的删减操作

    private void rILinkEditInfoDel_Click(object sender, EventArgs e)
    {
         if (XtraMessageBox.Show("请分明是或不是删除当前记录?", "警示",MessageBoxButtons.YesNo, Message博克斯Icon.Warning) == DialogResult.Yes)
         {
             DataRow row =gvInfos.GetDataRow(gvInfos.FocusedRowHandle);
             delByCode(row["Code"].ToString());
             XtraMessageBox.Show("操作成功!");
         }
    }

    二、绑定非数据表中列

    Hashtable ht = new Hashtable();

    private void gridView6_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgse)
    {
         GridView View = sender as GridView;
         if (e.RowHandle >= 0)
         {
             object needAlert =View.GetRowCellValue(e.RowHandle, View.Columns["needAlert"]);
             if (needAlert != null &needAlert != DBNull.Value && needAlert.ToString().Trim() !="0" & View.GetRowCellValue(e.RowHandle,View.Columns["Value"]) != DBNull.Value)
             {
                decimal AverValue = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle,View.Columns["Value"]));
                 objectMinValue = View.GetRowCellValue(e.RowHandle,View.Columns["MinValue"]);
                 objectMaxVlaue = View.GetRowCellValue(e.RowHandle,View.Columns["MaxValue"]);
                 if(MinValue != DBNull.Value & MinValue != null & MaxVlaue.ToString() !="" & MaxVlaue != DBNull.Value && MaxVlaue != null &MaxVlaue.ToString() != "")
                 {
                    decimal gridColumn2 = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle,View.Columns["MinValue"]));
                    decimal gridColumn1 = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle,View.Columns["MaxValue"]));
                    if (gridColumn2 > AverValue || AverValue > gridColumn1)
                    {
                        if (!ht.ContainsKey("pic"))
                            ht.Add("pic", GetImage(1));
                        e.Value = ht["pic"];
                    }
                 }
             }
         }
    }

    /// <summary>
    /// 由能源文件获取图片
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    byte[] GetImage(int key)
    {
         Image img =DevExpress.Utils.Controls.ImageHelper.CreateImageFromResources(string.Format("RiverSys.Resources.{0}.gif",key.ToString()), typeof(RiverInfos).Assembly);
         returnDevExpress.XtraEditors.Controls.ByteImageConverter.ToByteArray(img,ImageFormat.Gif);
    }

    /// <summary>
    /// 动态遵照准则设置行样式
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void gridView6_RowStyle(object sender,DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
    {
         GridView View = sender as GridView;
         if (e.RowHandle >= 0)
         {
             object needAlert =View.GetRowCellValue(e.RowHandle, View.Columns["needAlert"]);
             if (needAlert != null &needAlert != DBNull.Value && needAlert.ToString().Trim() !="0" & View.GetRowCellValue(e.RowHandle,View.Columns["Value"]) != DBNull.Value)
             {
                decimal AverValue = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle, View.Columns["Value"]));
                 objectMinValue = View.GetRowCellValue(e.RowHandle,View.Columns["MinValue"]);
                 objectMaxVlaue = View.GetRowCellValue(e.RowHandle,View.Columns["MaxValue"]);
                 if(MinValue != DBNull.Value & MinValue != null & MaxVlaue.ToString() !="" & MaxVlaue != DBNull.Value && MaxVlaue != null &MaxVlaue.ToString() != "")
                 {
                    decimal gridColumn2 = Convert.ToDecimal(MinValue);
                    decimal gridColumn1 = Convert.ToDecimal(MaxVlaue);
                    if (gridColumn2 > AverValue || AverValue > gridColumn1)
                    {
                        e.Appearance.ForeColor = Color.Red;
                        e.Appearance.BackColor = Color.LightGray;
                    }
                 }
             }
         }
    }

    三、GridControl 中颜色筛选控件

    private void gvMapColor_CustomUnboundColumnData(object sender,DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
    {
         GridView view = sender as GridView;
         DataView dv = view.DataSource as DataView;
         if (e.IsGetData)
         {
             string strVal =dv[e.ListSourceRowIndex]["Color"].ToString();
             if (strVal != "")
             {
                //e.Value = DevExpress.Utils.StyleLayout.ColorFromString(strVal);
                e.Value = Common.HexToColor(strVal);
             }
         }
         else
         {
             //Color colorVal =DevExpress.Utils.StyleLayout.ColorFromString(e.Value.ToString());
             Color colorVal =(Color)e.Value;
            dv[e.ListSourceRowIndex]["Color"] =Common.RGB_HEX(colorVal.ToArgb());
         }
    }

    四、关于 GridControl 验证示例

    /**//// <summary>
    /// 伊始化GridView,绑定数据
    /// </summary>
    /// <param name="parentId"></param>
    private void GridViewBindData(string parentId)
    {
    this.gridView1.Columns.Clear();
    this.FDs= areaSetupActionHelper.getDsRegionByParentId(parentId);
    this.gridCArea.DataSource =this.FDs.Tables[0].DefaultView;

        this.gridView1.Columns["id"].VisibleIndex =-1;
        this.gridView1.Columns["childCounts"].VisibleIndex= -1;

        this.gridView1.Columns["reg_id"].Caption ="区划编号";
        this.gridView1.Columns["reg_name"].Caption ="区划名称";
        this.gridView1.Columns["parent_id"].Caption ="父区划编号";
        this.gridView1.Columns["reg_desc"].Caption ="区划描述";
        this.gridView1.Columns["parent_id"].ImageIndex =1;
        this.gridView1.Columns["reg_desc"].ImageIndex = 0;

        RepositoryItemTextEdit textEditReg_Id = newRepositoryItemTextEdit();
        textEditReg_Id.Mask.EditMask =parentId "\d{2,3}";
        textEditReg_Id.Mask.MaskType =DevExpress.XtraEditors.Mask.MaskType.Regular;

        this.gridView1.Columns["reg_id"].ColumnEdit =textEditReg_Id;

        this.gridView1.Columns["reg_desc"].ColumnEdit= new RepositoryItemMemoExEdit();

        TreeListNode node =this.treelArea.FocusedNode.ParentNode;
        string fid =node==null?"0":node.GetValue("RegID").ToString().Trim();
        DataSet ds =areaSetupActionHelper.getDsRegionByParentId(fid);
        RepositoryItemLookUpEdit lookUEParent_Id = newRepositoryItemLookUpEdit();
        lookUEParent_Id.Columns.Add(newLookUpColumnInfo("reg_id", 40, "区划编号"));
        lookUEParent_Id.Columns.Add(newLookUpColumnInfo("reg_name", 40, "区划名称"));
        lookUEParent_Id.DataSource = ds.Tables[0].DefaultView;
        lookUEParent_Id.ValueMember = "reg_id";
        lookUEParent_Id.DisplayMember = "reg_id";
        this.gridView1.Columns["parent_id"].ColumnEdit =lookUEParent_Id;
    }
    /**//// <summary>
    /// gridView单元格验证的连带管理程序
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void gridView1_ValidatingEditor(objectsender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
    {
    if (e.Valid == false&this.gridView1.FocusedColumn.FieldName =="reg_id")
    {
          e.ErrorText = "区划编号非法!n应该为父区划编号加2~3位数据整合!";   
        }
        if (this.gridView1.FocusedColumn.FieldName =="reg_name")
        {     
         Regex reg=new Regex(@"[u4e00-u9fa5]{1,20}");
         Match m=reg.Match(e.Value.ToString().Trim());
         if (m.Length != e.Value.ToString().Trim().Length)
         {
          e.Valid = false;
          e.ErrorText = "区划名称应该为汉字n长度为1至20";
         }
        }
    }

    private void gridView1_InvalidValueException(objectsender, InvalidValueExceptionEventArgs e)
    {
        if (MyDialog.Alert(" 您所填写的从头到尾的经过不相符准绳n 要抛弃您刚刚对此项所做的改造吗?", "您所编写的开始和结果不相符准绳", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) ==DialogResult.Yes)
        {
         e.ExceptionMode = ExceptionMode.Ignore;
        }
    }

    /**//// <summary>
    /// gridView行验证的相关管理程序
    /// </summary>
    private void gridView1_ValidateRow(objectsender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
    {
    string regid = this.gridView1.GetRowCellValue(e.RowHandle,"reg_id").ToString().Trim();
    string regName = this.gridView1.GetRowCellValue(e.RowHandle,"reg_name").ToString().Trim();
    if ( regid.Length < 1)
    {
         e.Valid = false;
        this.gridView1.SetColumnError(this.gridView1.Columns["reg_id"],"请填入区划编号!",DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
          // e.ErrorText = "区划名称不能为空!";
        }
        if (regName.Length < 1)
        {
         e.Valid = false;
        this.gridView1.SetColumnError(this.gridView1.Columns["reg_name"],"区划名称无法为空!",DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default);
        }
    }

    private void gridView1_InvalidRowException(object sender,DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
    {

        if (e.RowHandle >= 0)
        {
         if (this.gridView1.GetRowCellValue(e.RowHandle,this.gridView1.Columns["reg_id"]).ToString().Trim() == ""|| this.gridView1.GetRowCellValue(e.RowHandle,this.gridView1.Columns["reg_name"]).ToString().Trim() =="")
         {
          if (MyDialog.Alert("  您所填写的原委不相符准则n 要废弃您刚才对此项所做的改换吗?","您所编写的剧情不切合准绳", MessageBoxButtons.YesNo,Message博克斯Icon.Warning) == DialogResult.Yes)
          {
           e.ExceptionMode = ExceptionMode.Ignore;
          }
          else
          {
           e.ExceptionMode = ExceptionMode.NoAction;
          }
         }
        }
        else
        {
         e.ExceptionMode = ExceptionMode.Ignore;
        }
    }

     

    有关XtraGrid的运用(GridControl小结)来源:51编制程序网公布时间:2008-04-19Hits:146
    DevExpress XtraGrid的使用(AspxGridControl小结) 收藏

    自定义宗旨行的方法: gridView_bcode.FocusedRowHandle = focuseRowInt; //通过设置GridView 的FocusedRowHandle属性
     
    view plaincopy to clipboardprint?
    //获取关节行放肆单元格的多寡    
    ColumnView cv = (ColumnView)gridControl_Gongzi.FocusedView;//重新获取此ID 不然不可能从表头连删获取不到id   
                           int focusedhandle = cv.FocusedRowHandle;   
                           object rowIdObj = gridView1.GetRowCellValue(focusedhandle,"id");   
                           if (DBNull.Value != rowIdObj)   
                           {   
                               FocusedRow_id = Convert.ToInt32(rowIdObj);   
                           }  
    //获取关节行任性单元格的数据 
    ColumnView cv = (ColumnView)gridControl_Gongzi.FocusedView;//重新获取此ID 不然无从从表头连删获取不到id
                           int focusedhandle = cv.FocusedRowHandle;
                           object rowIdObj = gridView1.GetRowCellValue(focusedhandle, "id");
                           if (DBNull.Value != rowIdObj)
                           {
                               FocusedRow_id = Convert.ToInt32(rowIdObj);
                           }
     view plaincopy to clipboardprint?
    //当数码爆发变化时实行    
         private void gridView1_CellValueChanged(object sender,CellValueChangedEventArgs e)   
         {   
             int intRowHandle =e.RowHandle;   
             FocusedRow_bumen =Convert.ToString(gridView1.GetRowCellValue(intRowHandle,"bumen"));   
             FocusedRow_xingming =Convert.ToString(gridView1.GetRowCellValue(intRowHandle,"xingming"));   
             //FocusedRow_jibengongzi =Convert.ToDecimal(gridView1.GetRowCellValue(intRowHandle,"jibengongzi"));   
             object rowJibengongziObj =gridView1.GetRowCellValue(intRowHandle, "jibengongzi");   
             if (DBNull.Value !=rowJibengongziObj)   
             {   
                FocusedRow_jibengongzi = Convert.ToDecimal(rowJibengongziObj);   
             }   
          }  
       //当数据产生变化时实行 
            private voidgridView1_CellValueChanged(object sender, CellValueChangedEventArgs e)
            {
                int intRowHandle= e.RowHandle;
               FocusedRow_bumen = Convert.ToString(gridView1.GetRowCellValue(intRowHandle,"bumen"));
               FocusedRow_xingming = Convert.ToString(gridView1.GetRowCellValue(intRowHandle,"xingming"));
               //FocusedRow_jibengongzi =Convert.ToDecimal(gridView1.GetRowCellValue(intRowHandle,"jibengongzi"));
                objectrowJibengongziObj = gridView1.GetRowCellValue(intRowHandle,"jibengongzi");
                if(DBNull.Value != rowJibengongziObj)
                {
                   FocusedRow_jibengongzi = Convert.ToDecimal(rowJibengongziObj);
                }
             } view plaincopy toclipboardprint?
    //设置主旨行的症结单元格的位置   
    ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView;   
    view.FocusedColumn = view.Columns["bumen"];  
    //设置核心行的节骨眼单元格的职位
    ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView;
    view.FocusedColumn = view.Columns["bumen"]; view plaincopy toclipboardprint?
    //当难点行发生变动时实施 获取选中标准行id   
           private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgse)   
           {   
               int intRowHandle =e.FocusedRowHandle;   
      
               object rowIdObj =gridView1.GetRowCellValue(intRowHandle, "id");   
      
               if (DBNull.Value!= rowIdObj)//做个决断不然获取不到id后报错  
               {   
                  FocusedRow_id = Convert.ToInt32(rowIdObj);   
               }   
           }  
     //当大旨行产生更改时实践 获取选中标准行id
            private void gridView1_FocusedRowChanged(object sender,DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
            {
                intintRowHandle = e.FocusedRowHandle;
     
                objectrowIdObj = gridView1.GetRowCellValue(intRowHandle, "id");
     
                if(DBNull.Value != rowIdObj)//做个推断不然获取不到id后报错
                {
                   FocusedRow_id = Convert.ToInt32(rowIdObj);
                }
            }   
     
     view plaincopy to clipboardprint?
    //焦点行的FocusedHandle为:  
     FocuseRow_Handle = -999998;   
    //获取宗旨行的handle   
    ColumnView newview = (ColumnView)gridControl_Gongzi.FocusedView;   
      
                           FocuseRow_Handle = newview.FocusedRowHandle;   
    //回车增多新行   
      private void gridView1_KeyPress(object sender, KeyPressEventArgse)   
               
            {   
                if(e.KeyChar == 13)   
               {   
                   ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView;   
                   if(view.IsLastRow)   
                   {   
                       if (FocuseRow_Handle == 0)   
                       {   
                           gridView1.AddNewRow();   
                              
                           ColumnView newview = (ColumnView)gridControl_Gongzi.FocusedView;   
                              
                           newview.FocusedColumn = newview.Columns["bumen"];//定位难点网格的地点   
                              
                           FocuseRow_Handle = newview.FocusedRowHandle;//获取新宗旨行的FocuseRowHandle并初阶化全局变量FocuseRow_Handle供保存操作时决断是update依然insert

    本文由新葡亰496net发布于奥门新萄京娱乐场,转载请注明出处:gridview钦定单元格cell获取坐标,GridControl使用办法

    关键词: