【www.gdgbn.com--邮件处理】

需要指定新加行的默认值的时候,可以在datagridview.defaultvaluesneeded事件里处理。在该事件中处理除了可以设定默认值以外,还可以指定某些特定的单元格的readonly属性等。

 

// defaultvaluesneeded 事件处理方法
private void datagridview1_defaultvaluesneeded(object sender,
    datagridviewroweventargs e)
{
    // 设定单元格的默认值
    e.row.cells["column1"].value = 0;
    e.row.cells["column2"].value = "-";
}
datagridview获得焦点
dgv_details.focus();
datagridview指定当前单元格
dgv_details.currentcell = dgv_details[0, 0];
开始编辑状态 
dgv_details.beginedit(false);
单元格颜色(前景色和背景色)
dgv.rows[0].cells[0].style.backcolor = color.darkorange;
dgv.rows[1].cells[0].style.forecolor = color.darkred;
datagridview中删除行主要代码:
private void btndelete_click(object sender, eventargs e)
        {
            //判断用户是否选择一行数据,true为没选择,false为选择
            if (this.dgv.rows[this.dgv.currentrow.index].cells[0].value.tostring()=="")
            {
                messagebox.show("请选择一项进行删除");
            }
            else
            {
                //判断用户是否点击确定按钮,true为点击,false为没有点击
                if (messagebox.show("确认删除?","提示", messageboxbuttons.yesno)==dialogresult.yes)
                {
                    //定义数组,用循环赋值
                    string[] array = new string[];
                    for (int i = 0; i < this.dgv.selectedrows.count; i++)
                    {
                        string str = this.dgv.rows[this.dgv.selectedrows[i].index].cells[0].value.tostring();
                        string strdelete = "delete from students where studentnumber="" + str + """;
                        array[i] = strdelete;
                    }
                    //遍历数组
                    foreach (string str in array)
                    {
                        this.update(str);
                    }
                        //这里写刷新的方法
                }
            }
        }
列宽的调整
datagridview有一个属性是autosizecolumnmode,他有几个属性:
allcells 调整列宽,以适合该列中的所有单元格的内容,包括标题单元格。
allcellsexceptheader 调整列宽,以适合该列中的所有单元格的内容,不包括标题单元格。
columnheader 调整列宽,以适合列标题单元格的内容。
displayedcells 调整列宽,以适合当前屏幕上显示的行的列中的所有单元格的内容,包括标题单元格。
displayedcellsexceptheader 调整列宽,以适合当前屏幕上显示的行的列中的所有单元格的内容,不包括标题单元格。
fill 调整列宽,使所有列的宽度正好填充控件的显示区域,只需要水平滚动保证列宽在 datagridviewcolumn.minimumwidth 属性值以上。相对列宽由相对 datagridviewcolumn.fillweight 属性值决定。
none 列宽不会自动调整。
notset 列的大小调整行为从 datagridview.autosizecolumnsmode 属性继承。
设置为fill.
然后先给datagridview绑定数据源.然后
dataset ds2 = momedal.binddvg(flagcbb);
this.dgvmain.datasource = ds2.tables[0];
this.dgvmain.columns[0].fillweight = 8; //第一列的相对宽度为8%
this.dgvmain.columns[1].fillweight = 22; //第一列的相对宽度为22%
this.dgvmain.columns[2].fillweight = 70; //第一列的相对宽度为70%
设置标题字段(先把columnsheadersvisible设置为true)
this.dgvmain.columns[0].headertext = "编号";
this.dgvmain.columns[1].headertext = "日期";
this.dgvmain.columns[2].headertext = "标题";
颜色设置,相隔行颜色不同
public void setdatagridcolor(int ncount)
  {
    for (int i = 0; i < this.datagridview1.rows.count; )
    {
      this.datagridview1.rows[i].defaultcellstyle.backcolor = system.drawing.color.lightgray;
      i += 2;
    }
  }

 
在cellmouseclick里操作,添加右键菜单
private void datagridview_cellmouseclick(object sender, datagridviewcellmouseeventargs e)
  {
    if (e.button == mousebuttons.right)
    {
      if (e.rowindex >= 0)
      {
        datagridview1.clearselection();
        datagridview1.rows[e.rowindex].selected = true; //选中
        datagridview1.currentcell = datagridview1.rows[e.rowindex].cells[e.columnindex];//选中单元
        datagridrightmenu.show(mouseposition.x, mouseposition.y); //在点击处显示右键菜单
      }
    }
  }
冻结
列冻结
datagridviewcolumn.frozen 属性为 true 时, 该列左侧的所有列被固定, 横向滚动时固定列不随滚动条滚动而左右移动。这对于重要列固定显示很有用。

[c#]
// datagridview1的左侧2列固定
datagridview1.columns[1].frozen = true;
但是,datagridview.allowusertoordercolumns = true 时,固定列不能移动到非固定列, 反之亦然。

行冻结
datagridviewrow.frozen 属性为 true 时, 该行上面的所有行被固定, 纵向滚动时固定行不随滚动条滚动而上下移动。
[c#]
// datagridview1 的上3行固定
datagridview1.rows[2].frozen = true;

datagridview 列顺序的调整
设定 datagridview 的 allowusertoordercolumns 为 true 的时候, 用户可以自由调整列的顺序。
当用户改变列的顺序的时候,其本身的 index 不会改变,但是 displayindex 改变了。你也可以通过程序改变 displayindex 来改变列的顺序。 列顺序发生改变时会引发 columndisplayindexchanged 事件:
[c#]
// datagridview1的columndisplayindexchanged事件处理方法
private void datagridview1_columndisplayindexchanged(object sender,
    datagridviewcolumneventargs e)
{
    console.writeline("{0} 的位置改变到 {1} ",
        e.column.name, e.column.displayindex);
}

datagridview 行头列头的单元格
 [c#]
// 改变datagridview1的第一列列头内容
datagridview1.columns[0].headercell.value = "第一列";
// 改变datagridview1的第一行行头内容
datagridview1.rows[0].headercell.value = "第一行";

// 改变datagridview1的左上头部单元内容
datagridview1.topleftheadercell.value = "左上";
另外你也可以通过 headertext 来改变他们的内容。

[c#]
// 改变datagridview1的第一列列头内容
datagridview1.columns[0].headertext = "第一列";

定义单元格验证
要求:验证错误后焦点不离开。
实现:

单元格的验证可以使用dgv_details_cellvalidating事件。
验证不通过时调用e.cancel = true;终止事件链,单元格将保持编辑状态。
调用dgv_details.canceledit();可以使单元格的内容会滚到修改前的值。
使用system.windows.forms.sendkeys.send("^a");将全选单元格的内容。

 

设置列的背景色
实现:
color gridreadonlycolor = color.lightgoldenrodyellow;
dgv_details.columns[1].defaultcellstyle.backcolor = ((winkeys.))gridreadonlycolor;


datagridview合并单元格 编辑单元格
同事的一个项目需要将datagridview单元格中的内容分不同颜色显示,想了想只有重绘了。
这种方法还可以用做合并单元格。
参考代码:
view code
private void datagridview1_cellpainting(object sender, datagridviewcellpaintingeventargs e)
        {
            if (e.rowindex == 0 && e.columnindex >= 0)
            {
                int left = e.cellbounds.left;
                int top = e.cellbounds.top;
                int right = e.cellbounds.right;
                int bottom = e.cellbounds.bottom;
                e.graphics.fillrectangle(new solidbrush(color.white), e.cellbounds);
                e.handled = true;
                brush gridbrush = new solidbrush(this.datagridview1.gridcolor);
                pen gridlinepen = new pen(gridbrush);
                e.graphics.drawline(gridlinepen, right - 1,
                           top, right - 1,
                           bottom - 1);
                e.graphics.drawline(gridlinepen, left,
                           bottom - 1, right,
                           bottom - 1);
                brush b1 = new solidbrush(color.black);
                e.graphics.drawstring((string)e.value, e.cellstyle.font,
                                        b1, left + 2,
                                        top + 1, stringformat.genericdefault);
                brush b2 = new solidbrush(color.red);
                e.graphics.drawstring((string)e.value, e.cellstyle.font,
                                        b2, left + 2,
                                        top + 10, stringformat.genericdefault);
            }
            datagridviewselectedcellcollection dgvscc = this.datagridview1.selectedcells;
            foreach (datagridviewcell dgvc in dgvscc)
            {
                    if (e.rowindex == 0
                        && e.rowindex == dgvc.rowindex
                        && e.columnindex == dgvc.columnindex)
                    {
                        int left = e.cellbounds.left;
                        int top = e.cellbounds.top;
                        int right = e.cellbounds.right;
                        int bottom = e.cellbounds.bottom;
                        // 绘制背景,覆盖单元格区域
                        e.graphics.fillrectangle(new solidbrush(color.fromargb(10,36,106)), e.cellbounds);
                        
                        // 绘制边框
                        brush gridbrush = new solidbrush(this.datagridview1.gridcolor);
                        pen gridlinepen = new pen(gridbrush);
                        e.graphics.drawline(gridlinepen, right - 1,
                                   top, right - 1,
                                   bottom - 1);
                        e.graphics.drawline(gridlinepen, left,
                                   bottom - 1, right,
                                   bottom - 1);
                        // 绘制文字
                        brush b1 = new solidbrush(color.white);
                        e.graphics.drawstring((string)e.value, e.cellstyle.font,
                                                b1, left + 2,
                                                top + 1, stringformat.genericdefault);
                        brush b2 = new solidbrush(color.white);
                        e.graphics.drawstring((string)e.value, e.cellstyle.font,
                                                b2, left + 2,
                                                top + 10, stringformat.genericdefault);
                    }
            }
            e.handled = true;           
        }


cellpainting事件,一般用于合并单元格用
windows forms datagridview 没有提供合并单元格的功能,要实现合并单元格的功能就要在cellpainting事件中使用graphics.drawline和 graphics.drawstring 自己来“画”。
下面的代码可以对datagridview第1列内容相同的单元格进行合并:
view code
#region"合并单元格的测试"
private int? nextrow = null;
private int? nextcol = null;
private void datagridview1_cellformatting(object sender, system.windows.forms.datagridviewcellformattingeventargs e)
{
    if (this.datagridview1.columns["description"].index == e.columnindex && e.rowindex >= 0)
    {
        if (this.nextcol != null & e.columnindex == this.nextcol)
        {
            e.cellstyle.backcolor = color.lightblue;
            this.nextcol = null;
        }
        if (this.nextrow != null & e.rowindex == nextrow)
        {
            e.cellstyle.backcolor = color.lightpink;
            this.nextrow = null;
        }
        if (e.rowindex != this.datagridview1.rowcount - 1)
        {
            if (e.value.tostring() == this.datagridview1.rows[e.rowindex + 1].cells[e.columnindex].value.tostring())
            {
                e.cellstyle.backcolor = color.lightpink;
                nextrow = e.rowindex + 1;
            }
        }
    }
    if (this.datagridview1.columns["name"].index == e.columnindex && e.rowindex >= 0)
    {
        if (e.value.tostring() == this.datagridview1.rows[e.rowindex].cells[e.columnindex + 1].value.tostring())
        {
            e.cellstyle.backcolor = color.lightblue;
            nextcol = e.columnindex + 1;
        }
    }
}
//==========================
       
//绘制单元格
private void datagridview1_cellpainting(object sender, system.windows.forms.datagridviewcellpaintingeventargs e)
{
 
    //纵向合并
    if (this.datagridview1.columns["description"].index == e.columnindex && e.rowindex >= 0)
    {
        using (
            brush gridbrush = new solidbrush(this.datagridview1.gridcolor),
            backcolorbrush = new solidbrush(e.cellstyle.backcolor))
        {
            using (pen gridlinepen = new pen(gridbrush))
            {
                // 擦除原单元格背景
                e.graphics.fillrectangle(backcolorbrush, e.cellbounds);
                ////绘制线条,这些线条是单元格相互间隔的区分线条,
                ////因为我们只对列name做处理,所以datagridview自己会处理左侧和上边缘的线条
                if (e.rowindex != this.datagridview1.rowcount - 1)
                {
                    if (e.value.tostring() != this.datagridview1.rows[e.rowindex + 1].cells[e.columnindex].value.tostring())
                    {
                        e.graphics.drawline(gridlinepen, e.cellbounds.left, e.cellbounds.bottom - 1,
                        e.cellbounds.right - 1, e.cellbounds.bottom - 1);//下边缘的线
                        //绘制值
                        if (e.value != null)
                        {
                            e.graphics.drawstring((string)e.value, e.cellstyle.font,
                                brushes.crimson, e.cellbounds.x + 2,
                                e.cellbounds.y + 2, stringformat.genericdefault);
                        }
                    }
                }
                else
                {
                    e.graphics.drawline(gridlinepen, e.cellbounds.left, e.cellbounds.bottom - 1,
                        e.cellbounds.right - 1, e.cellbounds.bottom - 1);//下边缘的线
                    //绘制值
                    if (e.value != null)
                    {
                        e.graphics.drawstring((string)e.value, e.cellstyle.font,
                            brushes.crimson, e.cellbounds.x + 2,
                            e.cellbounds.y + 2, stringformat.genericdefault);
                    }
                }
                //右侧的线
                e.graphics.drawline(gridlinepen, e.cellbounds.right - 1,
                    e.cellbounds.top, e.cellbounds.right - 1,
                    e.cellbounds.bottom - 1);
                e.handled = true;
            }
        }
    }
    //横向合并
    if (this.datagridview1.columns["name"].index == e.columnindex && e.rowindex >= 0)
    {
        using (
            brush gridbrush = new solidbrush(this.datagridview1.gridcolor),
            backcolorbrush = new solidbrush(e.cellstyle.backcolor))
        {
            using (pen gridlinepen = new pen(gridbrush))
            {
                // 擦除原单元格背景
                e.graphics.fillrectangle(backcolorbrush, e.cellbounds);
                if (e.value.tostring() != this.datagridview1.rows[e.rowindex].cells[e.columnindex + 1].value.tostring())
                {
                    //右侧的线
                    e.graphics.drawline(gridlinepen, e.cellbounds.right - 1, e.cellbounds.top,
                        e.cellbounds.right - 1, e.cellbounds.bottom - 1);
                    //绘制值
                    if (e.value != null)
                    {
                        e.graphics.drawstring((string)e.value, e.cellstyle.font,
                            brushes.crimson, e.cellbounds.x + 2,
                            e.cellbounds.y + 2, stringformat.genericdefault);
                    }
                }
                //下边缘的线
                e.graphics.drawline(gridlinepen, e.cellbounds.left, e.cellbounds.bottom - 1,
                                            e.cellbounds.right - 1, e.cellbounds.bottom - 1);
                e.handled = true;
            }
        }
    }
}
#endregion

 
cellformatting事件,一般重绘单元格属性。
view code
    private bitmap highpriimage;
    private bitmap mediumpriimage;
    private bitmap lowpriimage;
    private void datagridview1_cellformatting(object sender,
        system.windows.forms.datagridviewcellformattingeventargs e)
    {
        // set the background to red for negative values in the balance column.
        if (datagridview1.columns[e.columnindex].name.equals("balance"))
        {
            int32 intvalue;
            if (int32.tryparse((string)e.value, out intvalue) &&
                (intvalue < 0))
            {
                e.cellstyle.backcolor = color.red;
                e.cellstyle.selectionbackcolor = color.darkred;
            }
        }
        // replace string values in the priority column with images.
        if (datagridview1.columns[e.columnindex].name.equals("priority"))
        {
            // ensure that the value is a string.
            string stringvalue = e.value as string;
            if (stringvalue == null) return;
            // set the cell tooltip to the text value.
            datagridviewcell cell = datagridview1[e.columnindex, e.rowindex];
            cell.tooltiptext = stringvalue;
            // replace the string value with the image value.
            switch (stringvalue)
            {
                case "high":
                    e.value = highpriimage;
                    break;
                case "medium":
                    e.value = mediumpriimage;
                    break;
                case "low":
                    e.value = lowpriimage;
                    break;
            }
        }
    }
在dgv中加入控件列
view code
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.data.sqlclient;
using system.drawing;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
namespace csdn
{
 ///


 /// webform30 的摘要说明。
 ///

 public class webform30 : system.web.ui.page
 {
  datagrid datagrid1=new datagrid();
  private void page_load(object sender, system.eventargs e)
  {
   // 在此处放置用户代码以初始化页面
   createdatagrid(); 
  }
  
  protected void createdatagrid()
  {
   datagrid1.autogeneratecolumns=false;
   datagrid1.css教程class="border";
   datagrid1.borderwidth=0;
   datagrid1.cellspacing=1;
   datagrid1.cellpadding=5;
   datagrid1.itemstyle.cssclass="item";
   datagrid1.headerstyle.cssclass="header";
   datagrid1.datakeyfield="stuid";
//以上设定datagrid的样式
   templatecolumn tm=new templatecolumn();
   tm.itemtemplate=new columntemplate1();
   tm.headertext="姓名";
   datagrid1.columns.add(tm);
//建立第一个模板列
   templatecolumn tm2=new templatecolumn();
   tm2.itemtemplate=new columntemplate2();
   tm2.headertext="学院";
   datagrid1.columns.add(tm2);
//建立第二个模板列
   buttoncolumn bc=new buttoncolumn();
   bc.buttontype=buttoncolumntype.pushbutton;
   bc.commandname="del";
   bc.text="删除";
   datagrid1.columns.add(bc);
//建立删除按钮列
   setbind();
//填充数据
   page.controls[1].controls.add(datagrid1);
//给页面的form加入这个datagrid1
  }

  protected void setbind()
  {
   sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.apps教程ettings["conn"]);
   sqldataadapter da=new sqldataadapter("select * from stu,dep where stu.studepid=dep.depid",conn);
   dataset ds=new dataset();
   da.fill(ds,"table1");
   this.datagrid1.datasource=ds.tables["table1"];
   this.datagrid1.databind();
   
  }

  private void datagrid1_itemdatabound(object sender, system.web.ui.webcontrols.datagriditemeventargs e)
  {
//和上面连接给出的例子中的代码一样,给下拉框绑定数据,并且选择默认的
   sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings["conn"]);
   sqldataadapter da=new sqldataadapter("select * from dep",conn);
   dataset ds=new dataset();
   da.fill(ds,"table1");
   if(e.item.itemtype==listitemtype.item||e.item.itemtype==listitemtype.alternatingitem)
   {
    dropdownlist ddl=(dropdownlist)e.item.findcontrol("dep");
    ddl.datasource=ds.tables["table1"];
    ddl.datatextfield="depname";
    ddl.datavaluefield="depid";
    ddl.databind();
    ddl.items.findbyvalue(convert.tostring(databinder.eval(e.item.dataitem,"depid"))).selected=true;
   }
  }

  private void datagrid1_itemcommand(object source, system.web.ui.webcontrols.datagridcommandeventargs e)
  {
   if(e.commandname=="del")
   {
    sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings["conn"]);
    sqlcommand comm=new sqlcommand("delete from stu where mailto:stuid=@id%22,conn);
    sqlparameter parm1=new sqlparameter("@id",sqldbtype.int);
    parm1.value=this.datagrid1.datakeys[e.item.itemindex];
    comm.parameters.add(parm1);
    conn.open();
    comm.executenonquery();
    conn.close();
    setbind();
   }
  }

  #region web 窗体设计器生成的代码
  override protected void oninit(eventargs e)
  {
   //
   // codegen: 该调用是 asp教程.net web 窗体设计器所必需的。
   //
   initializecomponent();
   base.oninit(e);
  }
  
  ///


  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///

  private void initializecomponent()
  {   
   this.load += new system.eventhandler(this.page_load);
   this.datagrid1.itemdatabound += new system.web.ui.webcontrols.datagriditemeventhandler(this.datagrid1_itemdatabound);
   this.datagrid1.itemcommand += new system.web.ui.webcontrols.datagridcommandeventhandler(this.datagrid1_itemcommand);//这里的两个事件千万别忘记,因为datagrid是后台创建的,这些事件需要自己来写上,vs.net也不会为你创建
  }
  #endregion
 }

 public class columntemplate1 : itemplate
 {
//第一个模板列
  public void instantiatein(control container)      
  {
   literalcontrol l = new literalcontrol();
   l.databinding += new eventhandler(this.ondatabinding);
//数据绑定
   container.controls.add(l);
//为模板列加入literalcontrol
  }

  public void ondatabinding(object sender, eventargs e)
  {
   literalcontrol l = (literalcontrol) sender;//literalcontrol发送绑定请求
   datagriditem container = (datagriditem) l.namingcontainer;
   l.text = ((datarowview)container.dataitem)["stuname"].tostring();//绑定stuname字段
  }
 }

 public class columntemplate2 : itemplate
 {
//第二个模板列
  public void instantiatein(control container)      
  {
   dropdownlist dpl = new dropdownlist();
   dpl.id="dep";
   container.controls.add(dpl);
//加入一个id="dep"的下拉框,数据在datagrid的itemdatabound中绑定
  }
 } 
}
 
datagridviewcheckboxcolumn 类
view code
private void addoutofofficecolumn()
{
    datagridviewcheckboxcolumn column = new datagridviewcheckboxcolumn();
    {
        column.headertext = columnname.outofoffice.tostring();
        column.name = columnname.outofoffice.tostring();
        column.autosizemode =
            datagridviewautosizecolumnmode.displayedcells;
        column.flatstyle = flatstyle.standard;
        column.threestate = true;
        column.celltemplate = new datagridviewcheckboxcell();
        column.celltemplate.style.backcolor = color.beige;
    }

    datagridview1.columns.insert(0, column);
}
datagridview 的单元格的边框、 网格线样式的设定
1) datagridview 的边框线样式的设定
datagridview 的边框线的样式是通过 datagridview.borderstyle 属性来设定的。 borderstyle 属性设定值是一个
borderstyle 枚举: fixedsingle(单线,默认)、fixed3d、none。

2) 单元格的边框线样式的设定

单元格的边框线的样式是通过 datagridview.cellborderstyle 属性来设定的。 cellborderstyle 属性设定值是
datagridviewcellborderstyle 枚举。(详细参见 msdn)
另外,通过 datagridview.columnheadersborderstyle 和 rowheadersborderstyle 属性可以修改 datagridview 的头部的单元格边框线样式。 属性设定值是 datagridviewheaderborderstyle 枚举。(详细参见 msdn)

3) 单元格的边框颜色的设定
单元格的边框线的颜色可以通过 datagridview.gridcolor 属性来设定的。默认是 controldarkdark 。但是只有在 cellborderstyle 被设定为 single、singlehorizontal、singlevertical  的条件下才能改变其边框线的颜色。同样,columnheadersborderstyle 以及 rowheadersborderstyle 只有在被设定为 single 时,才能改变颜色。

4) 单元格的上下左右的边框线式样的单独设定
cellborderstyle只能设定单元格全部边框线的式样。要单独改变单元格某一边边框式样的话,需要用到datagridview.advancedcellborderstyle属性。如示例:

同样,设定行头单元格的属性是: advancedrowheadersborderstyle, 设定列头单元格属性是:advancedcolumnheadersborderstyle。

 

datagridview 单元格表示值的自定义

通过cellformatting事件,可以自定义单元格的表示值。(比如:值为error的时候,单元格被设定为红色)
下面的示例:将“colmn1”列的值改为大写。

  

view code
[c#]
//cellformatting 事件处理方法
private void datagridview1_cellformatting(object sender,
    datagridviewcellformattingeventargs e)
{
    datagridview dgv = (datagridview)sender;

 // 如果单元格是“column1”列的单元格
    if (dgv.columns[e.columnindex].name == "column1" && e.value is string)
    {
        // 将单元格值改为大写
        string str = e.value.tostring();
        e.value = str.toupper();
        // 应用该format,format完毕。
        e.formattingapplied = true;
    }
}

本文来源:http://www.gdgbn.com/jiaocheng/29725/