日期:2014-05-20  浏览次数:20849 次

DataGridView数据源为对象集的两个问题
//数据源
class   A
{

}

Class   B   :   CollationBase
{

}
.....
B   datas   =   ....
//注B   相当于   A[]
--------------------------------
//datagridview   控件
DataGridView   dgv   .....
-----------------------------------
//设置数据源
dgv.DataSource   =   datas;

------------------------------------
问题:
1:这里,A中有多少个属性,   datagridView就有多少个列,且显示顺序与标题头都与属性相关。请问是否有变化更改?

2:由于是数据绑定,请问取得一行时能否直接取出此行所对应的对象。
查看MSDN,看到相关DataGridViewRow.Tag中保存了相关的东西,但调试时却为null;
注:不想通过取得此行的序号,再通过datas[i]来取对象。


------解决方案--------------------
lz:
如果要实现你的要求,最好不要用绑定,尤其是你的第二项要求,DataGridViewRow.Tag在绑定数据源是,不会自动保存对象,必须是手工赋值,(其实对任何控件都是如此)。所以,实现你的要求,你必须手动添加行到datagridView控件。

给你个实例:
private void InitializeDataGridView()
{
// Create an unbound DataGridView by declaring a column count.
dataGridView1.ColumnCount = 4;
dataGridView1.ColumnHeadersVisible = true;

// Set the column header style.
DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();

columnHeaderStyle.BackColor = Color.Beige;
columnHeaderStyle.Font = new Font( "Verdana ", 10, FontStyle.Bold);
dataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle;

// Set the column header names.
dataGridView1.Columns[0].Name = "Recipe ";
dataGridView1.Columns[1].Name = "Category ";
dataGridView1.Columns[2].Name = "Main Ingredients ";
dataGridView1.Columns[3].Name = "Rating ";

// Populate the rows.
string[] row1 = new string[] { "Meatloaf ", "Main Dish ", "ground beef ",
"** " };
string[] row2 = new string[] { "Key Lime Pie ", "Dessert ",
"lime juice, evaporated milk ", "**** " };
string[] row3 = new string[] { "Orange-Salsa Pork Chops ", "Main Dish ",
"pork chops, salsa, orange juice ", "**** " };
string[] row4 = new string[] { "Black Bean and Rice Salad ", "Salad ",
"black beans, brown rice ", "**** " };
string[] row5 = new string[] { "Chocolate Cheesecake ", "Dessert ",
"cream cheese ", "*** " };
string[] row6 = new string[] { "Black Bean Dip ", "Appetizer ",
"black beans, sour cream ", "*** " };
object[] rows = new object[] { row1, row2, row3, row4, row5, row6 };

foreach (string[] rowArray in rows)
{
dataGridView1.Rows.Add(rowArray);
}
}


------解决方案--------------------
TO:1:这里,A中有多少个属性, datagridView就有多少个列,且显示顺序与标题头都与属性相关。请问是否有变化更改?

当然可以更改...

通过设置column.DataPropertyName属性..

参见MSDN:

ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_fxmclictl/html/cb8f29fa-577e-4e2b-883f-3a01c6189b9c.htm