DataGridView用法筆記

  • 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;
    }
}
發佈了136 篇原創文章 · 獲贊 4 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章