public void FillDataTable(DataTable table) {
if (table == null) throw new ArgumentNullException("table");
myDocument.Clear();
// 1. 標題列
CellRow header = new CellRow(); myDocument.Add(header);
foreach (DataColumn col in table.Columns)
header.Add(col.ColumnName);
// 2. 資料列
foreach (DataRow drow in table.Rows) {
CellRow row = new CellRow();
foreach (DataColumn col in table.Columns) {
object v = drow[col];
string txt = (v == null || v == DBNull.Value) ? "[NULL]" : Convert.ToString(v);
row.Add(txt);
}
myDocument.Add(row);
}
// 3. 排版與重繪
using (Graphics g = CreateGraphics()) {
RefreshSize(g);
Invalidate();
}
}
Text、Left/Top/Width/Height、Selected。CollectionBase,管理單列單元格,提供 Add/索引器。CollectionBase,管理多行,額外提供 Cells 屬性回傳扁平化單元格陣列。極簡設計,**純資料容器,零繪圖邏輯**,完美體現「文檔-視圖分離」。
DataTable.Columns 建立標題列。DataTable.Rows,每行建立 CellRow,轉換每欄值(DBNull→"[NULL]")加入。Graphics,呼叫 RefreshSize 排版,Invalidate 觸發重繪。若需支援資料型別、格式化、唯讀、驗證等,可在 Cell 增加 DataType、FormatString、ReadOnly 等屬性,**完全不影響繪製與互動層**——這就是 DOM 架構的威力。