Xer*_*erx 19 .net c# data-binding
我如何将以下对象Car绑定到gridview?
public class Car
{
long Id {get; set;}
Manufacturer Maker {get; set;}
}
public class Manufacturer
{
long Id {get; set;}
String Name {get; set;}
}
原始类型很容易绑定,但我发现无法为Maker显示任何内容.我想让它显示Manufacturer.Name.它甚至可能吗?
怎么办呢?我是否还必须将ManufacturerId存储在Car中,然后使用制造商列表设置lookupEditRepository?
kar*_*ins 27
好吧......这个问题已经发布了回来,但我刚刚发现了一个相当不错的简单方法,通过在cell_formatting事件中使用反射来检索嵌套属性.
像这样:
private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridView grid = (DataGridView)sender;
DataGridViewRow row = grid.Rows[e.RowIndex];
DataGridViewColumn col = grid.Columns[e.ColumnIndex];
if (row.DataBoundItem != null && col.DataPropertyName.Contains("."))
{
string[] props = col.DataPropertyName.Split('.');
PropertyInfo propInfo = row.DataBoundItem.GetType().GetProperty(props[0]);
object val = propInfo.GetValue(row.DataBoundItem, null);
for (int i = 1; i < props.Length; i++)
{
propInfo = val.GetType().GetProperty(props[i]);
val = propInfo.GetValue(val, null);
}
e.Value = val;
}
}
Run Code Online (Sandbox Code Playgroud)
就是这样!您现在可以在列的DataPropertyName中使用熟悉的语法"ParentProp.ChildProp.GrandChildProp".
我在最近的一个应用程序中解决这个问题的方法是创建我自己的DataGridViewColumn和DataGridViewCell类继承一个现有的类,如DataGridViewTextBoxColumn和DataGridViewTextBoxCell.
根据所需的单元格类型,您可以使用其他类型,如Button,Checkbox,ComboBox等.只需查看System.Windows.Forms中可用的类型.
单元格将它们的值作为对象处理,因此您可以将Car类传递给单元格的值.
重写SetValue和GetValue将允许您具有处理该值所需的任何其他逻辑.
例如:
public class CarCell : System.Windows.Forms.DataGridViewTextBoxCell
{
protected override object GetValue(int rowIndex)
{
Car car = base.GetValue(rowIndex) as Car;
if (car != null)
{
return car.Maker.Name;
}
else
{
return "";
}
}
}
Run Code Online (Sandbox Code Playgroud)
在列类中,您需要做的主要事情是将CellTemplate设置为自定义单元类.
public class CarColumn : System.Windows.Forms.DataGridViewTextBoxColumn
{
public CarColumn(): base()
{
CarCell c = new CarCell();
base.CellTemplate = c;
}
}
Run Code Online (Sandbox Code Playgroud)
通过在DataGridView上使用这些自定义Column/Cells,它允许您向DataGridView添加许多额外功能.
我使用它们来改变显示的格式,重写GetFormattedValue以将自定义格式应用于字符串值.
我还对Paint进行了覆盖,以便我可以根据值条件进行自定义单元格高亮显示,根据值将单元格Style.BackColor更改为我想要的.
public class Manufacturer
{
long Id {get; set;}
String Name {get; set;}
public override string ToString()
{
return Name;
}
}
Run Code Online (Sandbox Code Playgroud)
覆盖to string方法.
| 归档时间: |
|
| 查看次数: |
21695 次 |
| 最近记录: |