c# 表格控件SourceGrid使用總結


網上SourceGrid相關的資料很少,使用過程中做了下記錄,以便日后查用

1:初始化

this.grid = new SourceGrid.Grid();
this.grid.Size = new System.Drawing.Size(552, 224);
this.grid.Location = new System.Drawing.Point(0, 0);
this.tabPage1.Controls.Add(this.grid);

2:設置行列

方法1: grid.Redim(20,12);
方法2: grid.ColumnsCount = 3;
       grid.RowsCount = 3;
方法3: 在屬性中設置 ColumnsCount和RowsCount的值

grid.Rows.Insert(3);

3:固定行列

grid.FixedRows = 2;
grid.FixedColumns = 3;

4:標題列賦值及標題樣式(標題是否自帶排序)

 grid[0, 0] = new SourceGrid.Cells.ColumnHeader("序號");
 grid[0, 1] = new SourceGrid.Cells.ColumnHeader("區塊名稱");

對標題樣式進行修改
grid1[0, 0] = new MyHeader("序號");

 private class MyHeader : SourceGrid.Cells.ColumnHeader
  {
      public MyHeader(object value) : base(value)
        {
          //1 Header Row
          SourceGrid.Cells.Views.ColumnHeader view = new SourceGrid.Cells.Views.ColumnHeader();
          view.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
          view.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
          View = view;
      //自帶排序true;不實現排序false AutomaticSortEnabled
= false; } }

5:內容列賦值

 字符串類型: grid[1, 3] = new SourceGrid.Cells.Cell("Hello " + r.ToString(), typeof(string));
 復選框類型: grid[1, 5] = new SourceGrid.Cells.CheckBox(null, true);
 按鈕類型:   grid[62, 2] = new SourceGrid.Cells.Button("刪除");
 時間類型:   grid[1, 4] = new SourceGrid.Cells.Cell(DateTime.Today, typeof(DateTime));
        grid[1, 2] = new SourceGrid.Cells.Cell(12121);

 獲取:var aa=grid[1, 4].Value.ToString();
 重新賦值: grid[r + i, 4].Value = "2";  

注意:單元格格式用上面形式,賦值用Value可以避免多次賦值無效的問題  

6:單元格寬高設置

單元格根據內容自動變化:
(不包含標題列,只對內容有效,我感覺不好用,還是根據自己需求設置寬度)
 grid.AutoSizeCells();

 grid.Columns[0].Width = 100;(要在AutoSizeCells()方法后使用,否則無效)
 grid.Rows[0].Height = 30;

7:刪除某行某列

grid.Rows.Remove(3);//刪除下標為3的行
grid.Columns.Remove(3);

8:設置單元格文本/圖片居中及背景色(斑馬線即隔行換色)

/// <summary>
/// 設置表頭字體及樣式
/// </summary>
public class MyHeader : SourceGrid.Cells.ColumnHeader
{
  public MyHeader(object value) : base(value)
  {
  //1 Header Row
  SourceGrid.Cells.Views.ColumnHeader view = new SourceGrid.Cells.Views.ColumnHeader();
  view.Font = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Bold);
  view.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
  View = view;

  AutomaticSortEnabled = false;
  }
}

//使用grid[0, 0] = new MyHeader("序號");

 
SourceGrid.Cells.Views.Cell transparentView = new SourceGrid.Cells.Views.Cell(); transparentView.BackColor = Color.White;
 //字體
//transparentView.Font = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Bold); transparentView.TextAlignment
= DevAge.Drawing.ContentAlignment.MiddleCenter; transparentView.ImageAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter; SourceGrid.Cells.Views.Cell semiTransparentView = new SourceGrid.Cells.Views.Cell(); semiTransparentView.BackColor = Color.LightCyan; semiTransparentView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter; semiTransparentView.ImageAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
CheckBoxBackColorAlternate viewCheckBox = new CheckBoxBackColorAlternate(Color.LightCyan, Color.White);

  隔行顯示

  for (int r = 1; r < grid.RowsCount; r++)
  {
   for (int j = 0; j < grid.ColumnsCount; j++)
   {
    if ((r - 1) % 2 == 0) grid[r, j].View = transparentView;
    else grid[r, j].View = semiTransparentView;
   }
  }

9:按鈕button的相關設置

SourceGrid.Cells.Views.Cell buttonView = new SourceGrid.Cells.Views.Button();
buttonView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
buttonView.Padding = new DevAge.Drawing.Padding(2, 30, 2, 5);
使用:
grid[1, 20] = new SourceGrid.Cells.Button("刪除");

grid[1,20].View=buttonView;

10:復選框checkBox的相關設置

        //使用:
        grid[r, 16] = new SourceGrid.Cells.CheckBox(null, true);
     CheckBoxBackColorAlternate viewCheckBox = new CheckBoxBackColorAlternate(Color.LightCyan, Color.White); grid[
1, 3].View = viewCheckBox; /// <summary> /// 復選框CheckBox的相關設置 /// </summary> public class CheckBoxBackColorAlternate : SourceGrid.Cells.Views.CheckBox { public CheckBoxBackColorAlternate(Color firstColor, Color secondColor) { FirstBackground = new DevAge.Drawing.VisualElements.BackgroundSolid(firstColor); SecondBackground = new DevAge.Drawing.VisualElements.BackgroundSolid(secondColor); } private DevAge.Drawing.VisualElements.IVisualElement mFirstBackground; public DevAge.Drawing.VisualElements.IVisualElement FirstBackground { get { return mFirstBackground; } set { mFirstBackground = value; } } private DevAge.Drawing.VisualElements.IVisualElement mSecondBackground; public DevAge.Drawing.VisualElements.IVisualElement SecondBackground { get { return mSecondBackground; } set { mSecondBackground = value; } } protected override void PrepareView(SourceGrid.CellContext context) { base.PrepareView(context); if (Math.IEEERemainder(context.Position.Row, 2) == 0) Background = FirstBackground; else Background = SecondBackground; } }

注意:SourceGrid中不知道為什么沒有單選按鈕Radio,我為了實現效果直接用了CheckBox復選框,在單元格的點擊事件中實現單選效果

 private void clickEvent_Click(object sender, EventArgs e)
        {
            SourceGrid.CellContext context = (SourceGrid.CellContext)sender;
            if (context.Position.Column == 1)//選擇事件
            {
                for (int r = 1; r < grid.RowsCount; r++)
                {
                    if (r == context.Position.Row)
                    {
                        grid[r, 1].Value = true;
                    }
                    else
                    {
                        grid[r, 1].Value = false;
                    }
                }
            }
        }

11:復制粘貼

1.grid.ClipboardMode = SourceGrid.ClipboardMode.All;
2.也可在屬性中設置
若要實現單元格不可編輯但是可以復制功能的話需要注意:(不能使用14中的單元格不可操作代碼)
上述設置實現后,在賦值地方
grid[1, 3] = new SourceGrid.Cells.Cell("Hello " + r.ToString(), typeof(string));改為
grid[1, 3] = new SourceGrid.Cells.Cell("Hello " + r.ToString());即不要帶賦值類型就可實現不可編輯

12:單元格添加事件(點擊事件/修改編輯后觸發的事件)(點擊/鼠標進入單元格顯示手型,離開現實默認樣式)

SourceGrid.Cells.Controllers.CustomEvents clickEvent = new SourceGrid.Cells.Controllers.CustomEvents();
clickEvent.Click += new EventHandler(clickEvent_Click);//點擊(單擊)
clickEvent.DoubleClick += new EventHandler(clickEvent_DoubleClick);//雙擊
clickEvent.EditEnded += new EventHandler(editEvent_EditEnded);//編輯后
//鼠標進入和離開 clickEvent.MouseEnter += new EventHandler(mouseEvent_MouseEnter); clickEvent.MouseLeave += new EventHandler(mouseEvent_MouseLeave); //綁定事件 grid[r, 8].AddController(clickEvent); //單擊事件 private void clickEvent_Click(object sender, EventArgs e) { SourceGrid.CellContext context = (SourceGrid.CellContext)sender; MessageBox.Show(this, context.Position.ToString()); }
//雙擊事件
private void clickEvent_DoubleClick(object sender, EventArgs e)

  {
    SourceGrid.CellContext context = (SourceGrid.CellContext)sender;
    MessageBox.Show(this, context.Position.ToString());
    //要執行的操作

  }

/// <summary>
/// 進入單元格鼠標顯示手型
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void mouseEvent_MouseEnter(object sender, EventArgs e)
{
  SourceGrid.CellContext context = (SourceGrid.CellContext)sender;
  if (context.Position.Column == 8)
  {
    this.Cursor = Cursors.Hand;
  }
}
/// <summary>
/// 離開單元格鼠標顯示默認狀態
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void mouseEvent_MouseLeave(object sender, EventArgs e)
{
  SourceGrid.CellContext context = (SourceGrid.CellContext)sender;
  if (context.Position.Column == 8)
  {
    this.Cursor = Cursors.Default;
  }
}
        /// <summary>
        /// 單元格編輯結束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void editEvent_EditEnded(object sender, EventArgs e)
        {
            SourceGrid.CellContext context = (SourceGrid.CellContext)sender;
            //進行保存等相關操作
        }    

13:隱藏/顯示行/列

grid1.Columns[0].Visible=true;
grid1.Rows[1].Visible = false;

14:使單元格不可操作(不可編輯)

grid[1, 2].AddController(SourceGrid.Cells.Controllers.Unselectable.Default);

15:ComboBox下拉框的使用

SourceGrid.Cells.Editors.ComboBox cbKFJD = new SourceGrid.Cells.Editors.ComboBox(typeof(string));
cbKFJD.StandardValues = new string[] { "老區","新區" };
cbKFJD.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
grid[1, 2] = new SourceGrid.Cells.Cell("老區", cbKFJD);

16:報錯索引超出界限的特殊性情況處理:

在代碼中設置了足夠的行數和列數但是在colspan或rowspan的時候依然報錯可能原因是在屬性設置中Columnscout或Rowscount設置了值但是值不夠大,

解決辦法:1.屬性設置Columnscout和Rowscount不要設值默認值0(推薦)

    2.屬性設置Columnscout或Rowscount設置一個足夠大的值就行

17:進入頁面不顯示焦點:grid.Selection.FocusStyle = FocusStyle.None;

18:以Excel格式導出當前SourceGrid表格

     /// <summary>
        /// 導出計算報表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void materialButton2_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                string tradeTime = DateTime.Now.ToString("yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
                sfd.FileName = "計算報表" + tradeTime;
                if (sfd.ShowDialog() != DialogResult.OK) return;
                //保存
                var exportFileName = System.IO.Path.Combine(sfd.FileName.Substring(0, sfd.FileName.Length - 18), sfd.FileName.Substring(sfd.FileName.Length - 18) + ".csv");

                using (var writer = new System.IO.StreamWriter(exportFileName, false, System.Text.Encoding.Default))
                {
                    var csv = new SourceGrid.Exporter.CsvExporter();
                    csv.Export(grid, writer);
                    writer.Close();
                    MessageBox.Show("導出成功!");
                }

                DevAge.Shell.Utilities.OpenFile(exportFileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("導出失敗!" + ex.Message);
            }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM