[英]How to add a Table in a cell of DataGridView in C# windows application dynamically?
我正在用C#開發一個Windows應用程序,我有一個DataGridView
,目前顯示數據源的值。 我想添加一個列,其中每一行都有一個表。現在有沒有辦法動態地這樣做? 因為表格結構在每一行都會有所不同。
提前致謝。
編輯: -我的意思是,我想動態地在單元格中插入一個表格。
當我嘗試在每一行中動態添加TableLayoutPanel
,您可以看到Entity Details
列。
1)。 試試MSDN的Mark Ridout的TreeGridView並閱讀他關於使用它的文章 。
另請參閱使用Mark Ridout的TreeGridView的帶有分層數據綁定的CodeProject DataGridView是否有用。
2)。 如果免費控制不起作用,請看看第三方(我不隸屬於這些公司):
Devexpress XtraGrid
Telerik Gridview
Infragistics Grid
VIBlend DataGridView for WinForms
Janus Grid
xceed的網格
3)。 我很確定將TablePanelLayout添加到Grids單元格中並不是您想要的,這里是代碼,因此您可以看到它對您自己有多么狡猾:
DataTable dt = new DataTable();
dt.Columns.Add("name");
for (int j = 0; j < 10; j++)
{
dt.Rows.Add("");
}
this.dataGridView1.DataSource = dt;
this.dataGridView1.Columns[0].Width = 200;
//add tableLayoutPanel1 into the control collection of the DataGridView
this.dataGridView1.Controls.Add(tableLayoutPanel1);
//resize the row
this.dataGridView1.Rows[1].Height = 100;
//set its location and size to fit the cell
tableLayoutPanel1.Location = this.dataGridView1.GetCellDisplayRectangle(0,1, true).Location;
tableLayoutPanel1.Size = this.dataGridView1.GetCellDisplayRectangle(0, 1, true).Size;
本文是這樣的: 如何:Windows窗體DataGridView單元中的主機控件
在MSDN
DataGridView控件提供多種列類型,使您的用戶可以通過各種方式輸入和編輯值。 但是,如果這些列類型不滿足您的數據輸入需求, 則可以使用托管您選擇的控件的單元格創建自己的列類型 。
為此,您必須定義從DataGridViewColumn和DataGridViewCell派生的類 。
您還必須定義一個派生自Control的類並實現IDataGridViewEditingControl接口。
所以我建議,首先使用屬性或方法將表作為獨立控件,然后使用該控件顯示每一行 - 當您進行數據綁定時,讓每一行為您的TableControl設置數據。
另一種方法可能是這個(假設你沒有在網格中編輯) - 你可以創建一個像usercontrol一樣的行(創建一個usercontrol,其中所有的文本框或標簽都像datagridrow一樣放置它們,使它看起來像一行)和然后在帶滾動條的面板中添加它們。
我不認為這可以(輕松地)使用微軟開箱即用的控件。
如果你有預算,也許可以查看Telerik的控件。
http://www.telerik.com/products/winforms/gridview.aspx
他們有一個gridview控件作為他們的.NET WinForm控件的一部分,看起來它會做你想要的。
否則,是否可以更改您的體系結構並使用基於ASP.NET的Web方法來解決此問題?
希望有所幫助。 祝好運。
根據我的說法,在DataGridView
添加一個帶有表的列是不可能的。你的問題的最佳替代方法是通過自己創建一個動態表並重復行來顯示你的數據,在那一行中你可以放棄一個單元格里面有一張桌子。
您可以使用RowDatabound事件將表添加到單元格控件集合中。 像這個例子的東西(對不起 - 與你正在做的不同,但也許類似於你想要的,也在VB而不是C#)
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim i As Integer
Dim myTable As Table
Dim myRow As TableRow
Dim mycell As TableCell
If e.Row.RowType = DataControlRowType.DataRow Then
myTable = New Table
myRow = New TableRow
For i = 1 To 3
mycell = New TableCell
mycell.Text = i.ToString
mycell.BorderStyle = BorderStyle.Solid
mycell.BorderWidth = 0.2
mycell.Width = 15
If i = 1 Then mycell.BackColor = Drawing.Color.Beige
If i = 2 Then mycell.BackColor = Drawing.Color.Yellow
If i = 3 Then mycell.BackColor = Drawing.Color.Green
myRow.Cells.Add(mycell)
Next
myTable.Rows.Add(myRow)
e.Row.Cells(12).Controls.Add(myTable)
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.