DataGridView用法笔记

来源:互联网 发布:java中属性是什么意思 编辑:程序博客网 时间:2024/06/06 07:36
  • DataGridView 新加行的默认值的设定

 

需要指定新加行的默认值的时候,可以在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[00]; 
  • 开始编辑状态 
    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 调整列宽,以适合该列中的所有单元格的内容,包括标题单元格。
    AllCell***ceptHeader 调整列宽,以适合该列中的所有单元格的内容,不包括标题单元格。
    ColumnHeader 调整列宽,以适合列标题单元格的内容。
    DisplayedCells 调整列宽,以适合当前屏幕上显示的行的列中的所有单元格的内容,包括标题单元格。
    DisplayedCell***ceptHeader 调整列宽,以适合当前屏幕上显示的行的列中的所有单元格的内容,不包括标题单元格。
    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 == nullreturn;
                
    // 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 

     
    /// <summary> 
     
    /// WebForm30 的摘要说明。 
     
    /// </summary> 
     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.CssClass
    ="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.AppSettings["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); 
      } 
       
      
    /// <summary> 
      
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改 
      
    /// 此方法的内容。 
      
    /// </summary> 
      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(单线,默认)、Fixed3DNone

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

    单元格的边框线的样式是通过 DataGridView.CellBorderStyle属性来设定的。 CellBorderStyle属性设定值是
    DataGridViewCellBorderStyle
    枚举。(详细参见 MSDN
    另外,通过 DataGridView.ColumnHeadersBorderStyle RowHeadersBorderStyle属性可以修改 DataGridView的头部的单元格边框线样式。 属性设定值是 DataGridViewHeaderBorderStyle枚举。(详细参见 MSDN

    3
    单元格的边框颜色的设定
    单元格的边框线的颜色可以通过 DataGridView.GridColor属性来设定的。默认是 ControlDarkDark。但是只有在 CellBorderStyle被设定为 SingleSingleHorizontalSingleVertical 的条件下才能改变其边框线的颜色。同样,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;
    }
}
0 0
原创粉丝点击