欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[转载]DevExpress GridControl 使用方法技巧 总结 收录整理

程序员文章站 2024-01-07 14:11:58
最近开始用DevExpress组件,发现很好的经验总结博客,在这里转载分享 原作者:https://www.cnblogs.com/wordgao/p/4517011.html 一、如何解决单击记录整行选中的问题 View->OptionsBehavior->EditorShowMode 设置为:C ......

最近开始用devexpress组件,发现很好的经验总结博客,在这里转载分享

原作者:https://www.cnblogs.com/wordgao/p/4517011.html

 

 

一、如何解决单击记录整行选中的问题

view->optionsbehavior->editorshowmode 设置为:click

二、如何新增一条记录

(1)、gridview.addnewrow()

 

(2)、实现gridview_initnewrow事件

三、如何解决gridcontrol记录能获取而没有显示出来的问题

gridview.populatecolumns();

四、如何让行只能选择而不能编辑(或编辑某一单元格)

(1)、view->optionsbehavior->editorshowmode 设置为:click

 

(2)、view->optionsbehavior->editable 设置为:false

五、如何禁用gridcontrol中单击列弹出右键菜单

设置run design->optionsmenu->enablecolumnmenu 设置为:false

1、gridcontrol如何去掉主面板?

鼠标右键run designer=》optionsview =》 showgrouppanel=false;

2、gridcontrol如何设置列自动宽度?

鼠标右键run designer=》optionsview=》columnautowidth=true;

3、gridcontrol如何设置单元格不可编辑?

鼠标右键run designer=》optionsbehavior 》editable=false;

4.修改最上面的grouppanel内容

gridview1.grouppaneltext=”盼盼”;
获得选中了多少行?

1、 如何解决单击记录整行选中的问题

view->optionsbehavior->editorshowmode 设置为:click

2、 如何新增一条记录

(1)、gridview.addnewrow()

(2)、实现 gridview_initnewrow 事件

3、如何解决 gridcontrol 记录能获取而没有显示出来的问题

gridview.populatecolumns();

4、如何让行只能选择而不能编辑(或编辑某一单元格)

(1)、view->optionsbehavior->editorshowmode 设置为:click

(2)、view->optionsbehavior->editable 设置为:false

5、如何禁用 gridcontrol 中单击列弹出右键菜单

设置 run design->optionsmenu->enablecolumnmenu 设置为:false

6、如何隐藏 gridcontrol 的 grouppanel 表头

设置 run design->optionsview->showgrouppanel 设置为:false

 [转载]DevExpress GridControl 使用方法技巧 总结 收录整理

7、如何禁用 gridcontrol 中列头的过滤器 过滤器如下图所示:     

设置 run design->optionscustomization->allowfilter 设置为:false

8、如何在查询得到 0 条记录时显示自定义的字符提示/显示 如图所示:

 [转载]DevExpress GridControl 使用方法技巧 总结 收录整理

方法如下:

//when no records are being displaye

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); } } }

 

六、如何隐藏gridcontrol的grouppanel表头

设置run design->optionsview->showgrouppanel 设置为:false

七、如何禁用gridcontrol中列头的过滤器

过滤器如下图所示:

devexpress gridcontrol使用方法总结

设置 run design->optionscustomization->allowfilter 设置为:false

八、如何在查询得到0条记录时显示自定义的字符提示/显示

如图所示:

devexpress gridcontrol使用方法总结

方法如下:

 

//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);

           }

      }

 }

 

九、如何显示水平滚动条?

设置this.gridview.optionsview.columnautowidth = false;

十、如何定位到第一条数据/记录?

设置 this.gridview.movefirst()

十一、如何定位到下一条数据/记录?

设置 this.gridview.movenext()

十二、如何定位到最后一条数据/记录?

设置 this.gridview.movelast()

十三、设置成一次选择一行,并且不能被编辑

this.gridview1.focusrectstyle = devexpress.xtragrid.views.grid.drawfocusrectstyle.rowfocus;

 this.gridview1.optionsbehavior.editable = false;

 this.gridview1.optionsselection.enableappearancefocusedcell = false;

十四、如何显示行号?

 

 

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();

      }

 }

 

十五、如何让各列头禁止移动?

设置gridview1.optionscustomization.allowcolumnmoving = false;

十六、如何让各列头禁止排序?

设置gridview1.optionscustomization.allowsort = false;

十七、如何禁止各列头改变列宽?

设置gridview1.optionscustomization.allowcolumnresizing = false;

 normal 0 7.8 磅 0 2 false false false en-us zh-cn x-none

 

dev控件:gridcontrol常用属性设置

1.隐藏最上面的grouppanel

gridview1.optionsview.showgrouppanel=false;

2.得到当前选定记录某字段的值

svalue=table.rows[gridview1.focusedrowhandle][fieldname].tostring();

3.数据只读

gridview1.optionsbehavior.editable=false;

4.不显示masterdetailview

gridview1.optionsdetail.enablemasterviewmode=false;

5.修改最上面的grouppanel内容

gridview1.grouppaneltext="电子灵魂";

6.设置数据源:

gridcontrol1.datasource = dt;

    绑定每一列的filedname--属性

   对于oracle数据库,所有的在设计器里写的程序中的字段名必须大写,否则可能绑定不上字段,sqlserver没有这个限制.

7.读写拷贝权限设置

只读不可拷贝:

columnviewoptionsbehavior.editable = false

只读可拷贝:

columnviewoptionsbehavior.editable = true

     optionscolumn.allowedit = true

     optionscolumn.readonly = true

可编辑:

columnviewoptionsbehavior.editable = true

     optionscolumn.allowedit = true

     optionscolumn.readonly = false

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";

9.设某一列文字和标题局中显示 

gridview1.columns[0].appearanceheader.textoptions.halignment =devexpress.utils.horzalignment.center;

    gridview1.columns[0].appearancecell.textoptions.halignment =devexpress.utils.horzalignment.center;

10.去掉某一列上面的自动筛选功能(filter)

gridview1.columns[0].optionsfilter.allowautofilter = false;

    gridview1.columns[0].optionsfilter.allowfilter =false;             

    gridview1.columns[0].optionsfilter.immediateupdateautofilter =false;

11.设置冻结列(左冻结)

gridview1.columns[0].fixed= devexpress.xtragrid.columns.fixedstyle.left;

12.得到单元格数据(0行0列)

string ss=gridview1.getrowcelldisplaytext(0,gridview1.columns[0]);

    string ss = gridview1.getrowcellvalue(0, gridview1.columns[0]);

13.设置单元格数据(将0行0列的单元格赋值123)

gridview1.setrowcellvalue(0, gridview1.columns[0],"123");

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);

14.设置自动增加的行号,需要先添加给gridview添加事件customdrawrowindicator

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.删除: (修改了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 - 2),gridview1.columns[0])); //复制最后一行的数据到新行

 

           view.setrowcellvalue(e.rowhandle, view.columns[1],gridview1.getrowcellvalue(gridview1.getrowhandle(gridview1.rowcount - 2),gridview1.columns[1])); //复制最后一行的数据到新行

 

    }

 

17. 保存 (第三方控件提供的refreshdata和refreshdatasource方法对于保存数据都不好使,最后还是使用了dgvsave的datagridviewsave方法,用这个方法就可以)

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[]"));

 

            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;

         }

 

        //返回图片的字节流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;

        }

 

19.检查数据的有效性

在gridview的validaterow事件中加入检查代码:

 

#region 检查数据

  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"], "必须指定日期");

   }

 

  }

   #endregion

 

调用gridview.updatecurrentrow()方法执行检查

 

最常用的devexpress winform 4个代码片段:

一 、gridcontrol的删除操作

 

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("操作成功!");

      }

 }

 

二、绑定非数据表中列

 

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,messageboxicon.warning) == dialogresult.yes)

       {

        e.exceptionmode = exceptionmode.ignore;

       }

       else

       {

        e.exceptionmode = exceptionmode.noaction;

       }

      }

     }

     else

     {

      e.exceptionmode = exceptionmode.ignore;

     }

 }

 

 

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

 

9、如何显示水平滚动条?或

设置 this.gridview.optionsview.columnautowidth = false;

.....列表宽度自适应内容

gridview1.bestfitcolumns();

10、如何定位到第一条数据/记录?

设置 this.gridview.movefirst()

11、如何定位到下一条数据/记录?
设置 this.gridview.movenext()

12、如何定位到最后一条数据/记录?

设置 this.gridview.movelast()

13、设置成一次选择一行,并且不能被编辑

this.gridview1.focusrectstyle = devexpress.xtragrid.views.grid.drawfocusrectstyle.rowfocus;

this.gridview1.optionsbehavior.editable = false;

this.gridview1.optionsselection.enableappearancefocusedcell = false;

14、如何显示行号?

 

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、如何让各列头禁止移动?

设置 gridview1.optionscustomization.allowcolumnmoving = false;

16、如何让各列头禁止排序?

设置 gridview1.optionscustomization.allowsort = false;

17、如何禁止各列头改变列宽?

设置 gridview1.optionscustomization.allowcolumnresizing = false;

18.拖动滚动条时固定某一列

设置columns,选择要固定的列。设置fixed属性,可以选择:固定在左边、固定在右边、不固定。

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

return gridview1.getrowcellvalue(prows[0], columname).tostring ();

20.分组显示

optionsview>optionsbehavior>autoexpandallgroups = true
选择要分组的列,将groupindex属性设置为0

21.格式化数据

 

private void gvlist_validatingeditor(object sender, devexpress.xtraeditors.controls.basecontainervalidateeditoreventargs e)

        {

            if (this.gvlist.focusedcolumn.fieldname == "passqty")

            {

                string passqty = e.value.tostring().trim();

                int receiveqty = orderdetaillist[this.gvlist.focusedrowhandle].qty;

                if (!jxtype.isintbigthanzero(passqty))

                {

                    e.valid = false;

                    e.errortext = "合格数量必须为大于等于0小于等于接货数量的整数!";

                }

                else

                {

                    if (int.parse(passqty) > receiveqty)

                    {

                        e.valid = false;

                        e.errortext = "合格数量必须为大于0小于等于接货数量的整数!";

                    }

                }

            }

 

 

 

}

 

22.合并表头

 

///初始化表格

 

 

 

using devexpress.xtragrid.columns;

using devexpress.xtragrid.views.base;

using devexpress.xtragrid.views.bandedgrid;

using devexpress.xtraeditors.repository;

        private void initgrid()

        {

            // advbandedgridview1是表格上的默认视图,注意这里声明的是:bandedgridview

            bandedgridview view = advbandedgridview1 as bandedgridview;

            view.beginupdate(); //开始视图的编辑,防止触发其他事件

            view.begindataupdate(); //开始数据的编辑

            view.bands.clear();

 

 

 

 

            view.optionsview.showcolumnheaders = false;                         //因为有band列了,所以把columnheader隐藏

            //添加列标题

      //添加列标题

            gridband bandid = view.bands.addband("id");

            bandid.visible = false; //隐藏id列

            gridband bandname = view.bands.addband("姓名");

            gridband bandsex = view.bands.addband("性别");

            gridband bandbirth = view.bands.addband("出生日期");

            gridband bandscore = view.bands.addband("分数");

            gridband bandmath = bandscore.children.addband("数学");

            gridband bandchinese = bandscore.children.addband("语文");

            gridband bandenglish = bandscore.children.addband("英语");

            gridband bandsubtotal = bandscore.children.addband("小计");

            gridband bandremark = view.bands.addband("备注");

 

 

 

            bandfile.appearanceheader.textoptions.halignment = devexpress.utils.horzalignment.center;//这是合并表头居中显示

            view.enddataupdate();//结束数据的编辑

            view.endupdate();   //结束视图的编辑

        }

 

具体可看 

dev gridcontrol 合并表头

 [转载]DevExpress GridControl 使用方法技巧 总结 收录整理

23.   //动态添加列

devexpress.xtragrid.columns.gridcolumn col1 = new devexpress.xtragrid.columns.gridcolumn();

            col1.fieldname = "name";

            col1.caption = "名字";

            col1.visible = false;

            col1.visibleindex = gvcountry.columns.count;

            gvcountry.columns.add(col1);

24。设置自动增加的行号

 

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.特效: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[]"));

 

            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;

        }

 

        //返回图片的字节流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;

        }

 

26.检查数据的有效性

在gridview的validaterow事件中加入检查代码:

 

#region 检查数据

  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"], "必须指定日期");

  }

 

  }

 

27.设某一列文字和标题局中显示

gridview1.columns[0].appearanceheader.textoptions.halignment = devexpress.utils.horzalignment.center;

   gridview1.columns[0].appearancecell.textoptions.halignment = devexpress.utils.horzalignment.center;

28.列表过滤条件多选

列名.optionsfilter.filterpopupmode= devexpress.xtragrid.columns.filterpopupmode.checkedlist

29.隔行换色的方法

this.gridview1.appearance.oddrow.backcolor = color.white;  // 设置奇数行颜色 // 默认也是白色 可以省略

this.gridview1.optionsview.enableappearanceoddrow = true;   // 使能 // 和和上面绑定 同时使用有效

this.gridview1.appearance.evenrow.backcolor = color.whitesmoke; // 设置偶数行颜色

this.gridview1.optionsview.enableappearanceevenrow = true;   // 使能 // 和和上面绑定 同时使用有效

 

上一篇:

下一篇: