爲了讓您的數據表中的數據的真正快速顯示您可以創建一個表單與DataGridView
。
下面是一個例子,它假設你有一個充滿DataTable
並要顯示的所有數據,即它的所有列和行:
Form form = new Form(); // a blank form
DataGridView DGV = new DataGridView(); // a blank DataGridView
DGV.Parent = form; // we add the DGV to the from
DGV.AutoGenerateColumns = true; // to copy all columns from the DataSource
DGV.DataSource = dt; // set the datasource to the table
form.Width = 500; // some size, change to your needs!
DGV.Dock = DockStyle.Fill; // the DGV fills the form
form.ShowDialog(); // we show it as a dialog
你應該改善這一點通過在很至少列寬設定爲適當的值:
DGV.Columns[0].Width = 40;
DGV.Columns[1].Width = 50;
DGV.Columns[2].Width = 75;
// ..
代替indiviually設置寬度也可以使用許多自動模式中的一個:
DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader;
測試它們,看看它們中的任何一個對你來說效果不錯! (提示:有時它有助於發揮一點與列標題)
以同樣的方式,你可能要設置一些格式的一些列:
DGV.Columns[3].DefaultCellStyle.BackColor = Color.LightSalmon;
DGV.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
DGV.Columns[0].DefaultCellStyle.Format = "#00.00°";
注意,最後一行的數字格式只能在你的DataTable
中的Column.DataType
是一個數字類型!爲了執行它,你可以用這樣一行:
yourDataTable.Columns[0].DataType = typeof(float);
而如果只是爲了顯示我們應該讓只讀:
DGV.ReadOnly = true;
相反,如果你想顯示它作爲一種手段到編輯數據你可能需要更多的代碼;在這種情況下,我建議創建一個專用的表格和代碼所有必要的東西,如驗證代碼,查找,適當的錯誤信息等。還有一個Cancel
按鈕,撤消和什麼不是。這是beyod的範圍雖然這個問題!
對於最簡單的編輯要求,解決方案如圖所示將工作,但!
還要注意的是書面的問題創建一個空DataTable
,只有一些列。請將表移動到課程級別,以便您可以保存並編輯數據!
來源
2015-10-27 15:35:35
TaW
現在,您希望數據顯示在哪裏? DataTable是一個非視覺元素。 – TaW
我希望它彈出時點擊「是」 – Julianna
大聲笑,它仍然是一個非視覺元素。請看看'DataGridView'爲簡單的數據顯示!# – TaW