1, How to solve the problem of clicking the entire row of records to select
View->OptionsBehavior->EditorShowMode Set to: Click
2, How to add a record
(1),gridView.AddNewRow() (2),realization gridView_InitNewRow event
3, How to solve the problem that GridControl records can be obtained but not displayed
gridView.populateColumns();
4, How to make a row can only be selected but not edited (or edit a cell)
(1),View->OptionsBehavior->EditorShowMode Set to: Click (2),View->OptionsBehavior->Editable Set to: false
5, How to disable the pop-up right-click menu of clicking a column in GridControl
set up Run Design->OptionsMenu->EnableColumnMenu Set to: false
1. How does gridControl remove the main panel?
Right click Run Designer = "OptionsView =" ShowGroupPanel=False;
2. How does gridControl set the automatic width of columns?
Right click Run Designer = "OptionsView =" ColumnAutoWidth=True;
3. How does gridControl make cells non editable?
Right click Run Designer = "OptionsBehavior" Editable=False;
4. Modify the top GroupPanel content
gridView1.GroupPanelText = "Panpan";
How many rows are selected?
1. How to solve the problem of clicking the entire row of records to select
View - > optionsbehavior - > editorshowmode is set to: Click
2. How to add a record
(1),gridView.AddNewRow()
(2) , implement gridView_InitNewRow event
3. How to solve the problem that GridControl records can be obtained but not displayed
gridView.populateColumns();
4. How to make a row can only be selected but not edited (or edit a cell)
(1) . view - > optionsbehavior - > editorshowmode is set to: Click
(2) . view - > optionsbehavior - > editable: false
5. How to disable the pop-up right-click menu of clicking a column in GridControl
Set run design - > optionsmenu - > enablecolumnmenu to false
6. How to hide the GroupPanel header of GridControl
Set run design - > optionsview - > showgrouppanel to false
7. How to disable the filter of column header in GridControl is shown in the following figure:
Set run design - > optionscustomization - > allowfilter to false
8. How to display user-defined character prompt / display when 0 records are queried is shown in the figure:
The method is as follows:
//When no Records Are Being Displayed private void gridView1_CustomDrawEmptyForeground(object sender, CustomDrawEventArgs e) { //Method 1 (available when data source binding is set for GridView) ColumnView columnView = sender as ColumnView; BindingSource bindingSource = this.gridView1.DataSource as BindingSource; if(bindingSource.Count == 0) { string str = "The data you want is not queried!"; Font f = new Font("Song typeface", 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); } //Method 2 (this method is used when GridView does not set data source binding. This method is generally used) if (this._flag) { if (this.gridView1.RowCount == 0) { string str = "The data you want is not queried!"; Font f = new Font("Song typeface", 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); } } }
6, How to hide the GroupPanel header of GridControl
set up Run Design->OptionsView->ShowGroupPanel Set to: false
7, How to disable filters for column headers in GridControl
The filter is shown in the figure below:
Devaxpress gridcontrol Usage Summary
Set run design - > optionscustomization - > allowfilter to false
8, How to display custom character prompt / display when 0 records are queried
As shown in the figure:
Devaxpress gridcontrol Usage Summary
The method is as follows:
9, How do I display the horizontal scroll bar?//When no Records Are Being Displayed private void gridView1_CustomDrawEmptyForeground(object sender, CustomDrawEventArgs e) { //Method 1 (available when data source binding is set for GridView) ColumnView columnView = sender as ColumnView; BindingSource bindingSource = this.gridView1.DataSource as BindingSource; if(bindingSource.Count == 0) { string str = "The data you want is not queried!"; Font f = new Font("Song typeface", 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); } //Method 2 (this method is used when GridView does not set data source binding. This method is generally used) if (this._flag) { if (this.gridView1.RowCount == 0) { string str = "The data you want is not queried!"; Font f = new Font("Song typeface", 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); } } }
10, How do I navigate to the first data / record?set up this.gridView.OptionsView.ColumnAutoWidth = false;
set up this.gridView.MoveFirst()
11, How do I navigate to the next data / record?
set up this.gridView.MoveNext()
12, How do I navigate to the last data / record?
set up this.gridView.MoveLast()
13, Set to select one row at a time and cannot be edited
this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus; this.gridView1.OptionsBehavior.Editable = false; this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
14, How to display line numbers?
this.gridView1.IndicatorWidth = 40; //Displays the sequence number of the row private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e) { if (e.Info.IsRowIndicator && e.RowHandle>=0) { e.Info.DisplayText = (e.RowHandle + 1).ToString(); } }
15, How to prevent column heads from moving?
set up gridView1.OptionsCustomization.AllowColumnMoving = false;
16, How to disable sorting of column headers?
set up gridView1.OptionsCustomization.AllowSort = false;
17, How to prevent column headers from changing column width?
set up gridView1.OptionsCustomization.AllowColumnResizing = false; Normal 0 7.8 LB 0 2 false false false EN-US ZH-CN X-NONE
DEV control: gridControl common property settings
1. Hide the top GroupPanel
2. Get the value of a field of the currently selected recordgridView1.OptionsView.ShowGroupPanel=false;
3. Data is read-onlysValue=Table.Rows[gridView1.FocusedRowHandle][FieldName].ToString();
gridView1.OptionsBehavior.Editable=false;
4. Do not display MasterDetailView
gridView1.OptionsDetail.EnableMasterViewMode=false;
5. Modify the top GroupPanel content
gridView1.GroupPanelText="Electronic soul";
6. Set data source:
gridControl1.DataSource = dt; Bind each column FiledName--attribute about Oracle database,Field names in all programs written in the designer must be capitalized,Otherwise, the field may not be bound,sqlserver There is no such limit.
7. Read / write copy permission setting
Read only, non copyable:
Read only and can be copied:ColumnViewOptionsBehavior.Editable = False
ColumnViewOptionsBehavior.Editable = True OptionsColumn.AllowEdit = True OptionsColumn.ReadOnly = True
Editable:
ColumnViewOptionsBehavior.Editable = True OptionsColumn.AllowEdit = True OptionsColumn.ReadOnly = False
8. Template column setting:
Go to Columns and find ColumnEdit. In his properties
Take LookUpEdit as an example:
First, add LookUpEdit. From the left menu of Designer in place editor repository Named Re1 then. Add three Columns to his Columns property Caption s are: number, name and gender The fieldnames are FID, fname and fsex Then set NullText of Re1 to null
The AutoSearchColumnIndex property is set to 2 Set the immediatepopup property to True
Set SearchMode to OnlyInPopup
Then attach the template column to column 1 mentioned above (that is, set the ColumnEdit attribute of column 1 to Re1)
Finally, we need to bind the data source and display item to Re1 in the code
9. Set a column of text and title to be displayed in the BureauRe1.DataSource =DALUse.Query("select fid,fname,fsex from dual").Tables[0]; Re1.DisplayMember ="FSEX"; Re1.ValueMember ="FNAME";
10. Remove the automatic filter function above a columngridView1.Columns[0].AppearanceHeader.TextOptions.HAlignment =DevExpress.Utils.HorzAlignment.Center; gridView1.Columns[0].AppearanceCell.TextOptions.HAlignment =DevExpress.Utils.HorzAlignment.Center;
11. Set frozen column (left frozen)gridView1.Columns[0].OptionsFilter.AllowAutoFilter = false; gridView1.Columns[0].OptionsFilter.AllowFilter =false; gridView1.Columns[0].OptionsFilter.ImmediateUpdateAutoFilter =false;
12. Get cell data (0 rows and 0 columns)gridView1.Columns[0].Fixed= DevExpress.XtraGrid.Columns.FixedStyle.Left;
13. Set cell data (assign a value of 123 to cells in row 0 and column 0)string ss=gridView1.GetRowCellDisplayText(0,gridView1.Columns[0]); string ss = gridView1.GetRowCellValue(0, gridView1.Columns[0]);
13. Manually add dev columnsgridView1.SetRowCellValue(0, gridView1.Columns[0],"123");
14. To set the automatically added line number, you need to add the event CustomDrawRowIndicator to the gridview firstDevExpress.XtraGrid.Columns.GridColumn Col1=newDevExpress.XtraGrid.Columns.GridColumn (); Col1.FieldName="FID"; Col1.Visible=true; Col1.VisibleIndex=gridView1.Columns.Count; gridView1.Columns.Add(Col1);
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(); }
15. Delete: (the datagridviewdel method in dgvdel is modified)
public static voiddatagridviewdel_Dev(DevExpress.XtraGrid.Views.Grid.GridView Mydgv) { if (MessageBox.Show("Are you sure you want to delete the selected record?", "Delete prompt",MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, false) == DialogResult.Yes) { intiSelectRowCount = Mydgv.SelectedRowsCount; if(iSelectRowCount > 0) { Mydgv.DeleteSelectedRows(); } } }
16. Adding: (for adding, the AddNewRow method can do it)
17. Save (the RefreshData and RefreshDataSource methods provided by the third-party control are not easy to save data. Finally, the datagridviewsave method of Dgvsave is used. This method can be used)private void btn_add_Click(object sender, EventArgs e) { gridView1.AddNewRow(); } What special settings do you have for the newly added bank,Can be in it gridView1_InitNewRow Fill in the event: 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])); //Copy the data of the last row to the new row View.SetRowCellValue(e.RowHandle, View.Columns[1],gridView1.GetRowCellValue(gridView1.GetRowHandle(gridView1.RowCount - 2),gridView1.Columns[1])); //Copy the data of the last row to the new row }
18. Special effects: there are five types of views in gridcontrol, the common one is gridview, and then cardview, BandedView, advanced BandedView and LayoutView respectively; There are 5 kinds in total.
1) In the view group, set the viewmode under OptionView to "Carousel" to achieve this kind of "Carousel" gridcontrol view effect
2),layoutView1.OptionsCarouselMode.PitchAngle this attribute determines the pitch angle of the "carousel"; Helix angle; Spiral rise angle; Pitch angle; dip angle; Pitch cone half angle
3) The Roll Angle attribute determines the Roll Angle
4) Specify the data source and display the data:
//Display data 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[]")); 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; } //Returns the byte stream byte [] of the picture 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; }
19. Check the validity of the data
Add the check code to the ValidateRow event of gridview:
Call GridView The updatecurrerow() method performs a check#region check data private void gridView1_ValidateRow(object sender, ValidateRowEventArgse) { GridView view = sender as GridView; view.ClearColumnErrors(); if (view.GetRowCellValue(e.RowHandle, "ReceiveDate") ==DBNull.Value) { e.Valid = false; view.SetColumnError(view.Columns["ReceiveDate"], "You must specify a date"); } } #endregion
The four most commonly used code snippets of devaexpress WinForm:
1, Delete operation of GridControl
private void rILinkEditInfoDel_Click(object sender, EventArgs e) { if (XtraMessageBox.Show("Are you sure you want to delete the current record?", "warning",MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { DataRow row =gvInfos.GetDataRow(gvInfos.FocusedRowHandle); delByCode(row["Code"].ToString()); XtraMessageBox.Show("Operation succeeded!"); } }
2, Bind columns in non data table
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> ///Get pictures from resource files /// </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); }
3, Color selection control in GridControl/// <summary> ///Set row styles dynamically based on conditions /// </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; } } } } }
4, About GridControl validation exampleprivate 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()); } }
/**//// <summary> ///Initialize GridView and bind data /// </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 ="Division number"; this.gridView1.Columns["reg_name"].Caption ="Division name"; this.gridView1.Columns["parent_id"].Caption ="Parent zone number"; this.gridView1.Columns["reg_desc"].Caption ="Zoning description"; 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, "Division number")); lookUEParent_Id.Columns.Add(newLookUpColumnInfo("reg_name", 40, "Division name")); 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> ///Related handlers for gridView cell validation /// </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 = "Illegal division number!\n Parent zone number should be incremented by 2~3 Bit data composition!"; } 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 = "The division name shall be in Chinese characters\n Length 1 to 20"; } } } private void gridView1_InvalidValueException(objectsender, InvalidValueExceptionEventArgs e) { if (MyDialog.Alert(" The content you filled in does not comply with the rules\n Do you want to discard the changes you just made to this item?", "The content you edited does not conform to the rules", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) ==DialogResult.Yes) { e.ExceptionMode = ExceptionMode.Ignore; } }
/**//// <summary> ///Related handlers for gridView row validation /// </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"],"Please fill in the division number!",DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default); // e.ErrorText = "zone name cannot be empty!"; } if (regName.Length < 1) { e.Valid = false; this.gridView1.SetColumnError(this.gridView1.Columns["reg_name"],"Zone name cannot be empty!",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(" The content you filled in does not comply with the rules\n Do you want to discard the changes you just made to this item?","The content you edited does not conform to the rules", MessageBoxButtons.YesNo,MessageBoxIcon.Warning) == DialogResult.Yes) { e.ExceptionMode = ExceptionMode.Ignore; } else { e.ExceptionMode = ExceptionMode.NoAction; } } } else { e.ExceptionMode = ExceptionMode.Ignore; } }
view plaincopy to clipboardprint? //Gets the data of any cell in the focus row ColumnView cv = (ColumnView)gridControl_Gongzi.FocusedView;//Get this id again, otherwise you can't delete it from the header int focusedhandle = cv.FocusedRowHandle; object rowIdObj = gridView1.GetRowCellValue(focusedhandle,"id"); if (DBNull.Value != rowIdObj) { FocusedRow_id = Convert.ToInt32(rowIdObj); } //Gets the data of any cell in the focus row ColumnView cv = (ColumnView)gridControl_Gongzi.FocusedView;//Get this id again, otherwise you can't delete it from the header int focusedhandle = cv.FocusedRowHandle; object rowIdObj = gridView1.GetRowCellValue(focusedhandle, "id"); if (DBNull.Value != rowIdObj) { FocusedRow_id = Convert.ToInt32(rowIdObj); } view plaincopy to clipboardprint? //Execute when data changes 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); } } //Execute when data changes 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? //Sets the position of the focus cell of the focus row ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView; view.FocusedColumn = view.Columns["bumen"]; //Sets the position of the focus cell of the focus row ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView; view.FocusedColumn = view.Columns["bumen"]; view plaincopy toclipboardprint? //When the focus line changes, execute to obtain the selected focus line 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)//Make a judgment, otherwise an error will be reported after the id is not obtained { FocusedRow_id = Convert.ToInt32(rowIdObj); } } //When the focus line changes, execute to obtain the selected focus line 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)//Make a judgment, otherwise an error will be reported after the id is not obtained { FocusedRow_id = Convert.ToInt32(rowIdObj); } } view plaincopy to clipboardprint? //The FocusedHandle of the focus line is: FocuseRow_Handle = -999998; //Gets the handle of the focus row ColumnView newview = (ColumnView)gridControl_Gongzi.FocusedView; FocuseRow_Handle = newview.FocusedRowHandle; //Press enter to add a new line 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"];//Position the focus grid FocuseRow_Handle = newview.FocusedRowHandle;//Get the FocuseRowHandle of the new focus row and initialize the global variable FocuseRow_Handle is used to determine whether to update or insert when saving
9. How do I display the horizontal scroll bar? or
Set this gridView. OptionsView. ColumnAutoWidth = false;
..... List width adaptive content
gridview1.BestFitColumns();
10. How do I navigate to the first data / record?
Set this gridView. MoveFirst()
11. How do I navigate to the next data / record?
Set this gridView. MoveNext()
12. How do I navigate to the last data / record?
Set this gridView. MoveLast()
13. Set to select one row at a time and cannot be edited
this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus; this.gridView1.OptionsBehavior.Editable = false; this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
14. How to display line numbers?
private void gvPayList_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 < 0 && e.RowHandle > -1000) { e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite; e.Info.DisplayText = "G" + e.RowHandle.ToString(); } } }
15. How to prevent column heads from moving?
Set gridview1 OptionsCustomization. AllowColumnMoving = false;
16. How to disable sorting of column headers?
Set gridview1 OptionsCustomization. AllowSort = false;
17. How to prevent column headers from changing column width?
Set gridview1 OptionsCustomization. AllowColumnResizing = false;
18. Fix a column when dragging the scroll bar
Set Columns and select the Columns to fix. Set the Fixed attribute. You can select Fixed on the left, Fixed on the right, or unfixed.
19. Get the selected row and specify the contents of the column cell
return gridView1.GetRowCellValue(pRows[0], ColumName).ToString ();
20. Group display
OptionsView>OptionsBehavior>AutoExpandAllGroups = True
Select the columns to group and set the GroupIndex property to 0
21. Format data
22. Consolidated headerprivate 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 = "Qualified quantity must be an integer greater than or equal to 0 and less than or equal to receiving quantity!"; } else { if (int.Parse(passQty) > receiveQty) { e.Valid = false; e.ErrorText = "The qualified quantity must be an integer greater than 0 and less than or equal to the receiving quantity!"; } } } }
///Initialize table using DevExpress.XtraGrid.Columns; using DevExpress.XtraGrid.Views.Base; using DevExpress.XtraGrid.Views.BandedGrid; using DevExpress.XtraEditors.Repository; private void InitGrid() { // advBandedGridView1 is the default view on the table. Note that BandedGridView is declared here BandedGridView view = advBandedGridView1 as BandedGridView; view.BeginUpdate(); //Start editing the view to prevent other events from being triggered view.BeginDataUpdate(); //Start data editing view.Bands.Clear(); view.OptionsView.ShowColumnHeaders = false; //Because there is a Band column, hide the ColumnHeader //Add column header //Add column header GridBand bandID = view.Bands.AddBand("ID"); bandID.Visible = false; //Hide ID column GridBand bandName = view.Bands.AddBand("full name"); GridBand bandSex = view.Bands.AddBand("Gender"); GridBand bandBirth = view.Bands.AddBand("date of birth"); GridBand bandScore = view.Bands.AddBand("fraction"); GridBand bandMath = bandScore.Children.AddBand("mathematics"); GridBand bandChinese = bandScore.Children.AddBand("language"); GridBand bandEnglish = bandScore.Children.AddBand("English"); GridBand bandSubTotal = bandScore.Children.AddBand("Subtotal"); GridBand bandRemark = view.Bands.AddBand("remarks"); bandFile.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;//This is the center display of the merged header view.EndDataUpdate();//End data editing view.EndUpdate(); //End view editing }
See for details
dev gridcontrol merge header
23. / / dynamically add columns
24. Set automatically added line numberDevExpress.XtraGrid.Columns.GridColumn Col1 = new DevExpress.XtraGrid.Columns.GridColumn(); Col1.FieldName = "name"; Col1.Caption = "name"; Col1.Visible = false; Col1.VisibleIndex = gvCountry.Columns.Count; gvCountry.Columns.Add(Col1);
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 < 0 && e.RowHandle > -1000) { e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite; e.Info.DisplayText = "G" + e.RowHandle.ToString(); } } }
25. Special effects: there are five types of views in gridcontrol, the common one is gridview, and then cardview, BandedView, Advanced BandedView and LayoutView respectively; There are 5 kinds in total.
1) in the view group, set the viewmode under OptionView to "Carousel" to achieve the "merry go round" gridcontrol view effect
2),layoutView1.OptionsCarouselMode.PitchAngle this attribute determines the pitch angle of the "carousel"; Helix angle; Spiral rise angle; Pitch angle; dip angle; Pitch cone half angle
3) the Roll Angle attribute determines the Roll Angle
4) specify data source and display data:
//Display data 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[]")); 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; } //Returns the byte stream byte [] of the picture 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; }
26. Check the validity of the data
Add the check code to the ValidateRow event of gridview:
#region check data private void gridView1_ValidateRow(object sender, ValidateRowEventArgs e) { GridView view = sender as GridView; view.ClearColumnErrors(); if (view.GetRowCellValue(e.RowHandle, "ReceiveDate") == DBNull.Value) { e.Valid = false; view.SetColumnError(view.Columns["ReceiveDate"], "You must specify a date"); } }
27. Set a column of text and title to be displayed in the Bureau
gridView1.Columns[0].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; gridView1.Columns[0].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
28. Multiple selection of list filter conditions
Listing OptionsFilter.FilterPopupMode= DevExpress.XtraGrid.Columns.FilterPopupMode.CheckedList
29. Interlaced color change method
this.gridView1.Appearance.OddRow.BackColor = Color.White; // Set the color of odd rows / / it is white by default and can be omitted this.gridView1.OptionsView.EnableAppearanceOddRow = true; // Enable / / valid when used with the above binding this.gridView1.Appearance.EvenRow.BackColor = Color.WhiteSmoke; // Set even row color this.gridView1.OptionsView.EnableAppearanceEvenRow = true; // Enable / / valid when used with the above binding