而不是做下面的下面的代码:
List<Travel> travels = logic.GetAllTravels();
DgvRecorridos.DataSource = travels;
这样做:
List<Travel> travels = logic.GetAllTravels();
BindingSource bs = new BindingSource();
bs.DataSource = travels;
DgvRecorridos.AutoGenerateColumn = false;
DgvRecorridos.DataSource = bs;
然后,手动添加列:
DataGridViewColumn col1 = new DataGridViewTextBoxColumn();
col1.DataPropertyName = "Service.Name";
col1.HeaderText = "Service Name";
dataGridView1.Columns.Add(col1);
DataGridViewColumn col2 = new DataGridViewTextBoxColumn();
col2.DataPropertyName = "City.Name";
col2.HeaderText = "City Name";
dataGridView1.Columns.Add(col2);
DataGridViewColumn col3 = new DataGridViewTextBoxColumn();
col3.DataPropertyName = "City.Name";
col3.HeaderText = "Destiny Name";
dataGridView1.Columns.Add(col3);
DataGridViewColumn col4 = new DataGridViewTextBoxColumn();
col4.DataPropertyName = "Price";
col4.HeaderText = "Price";
dataGridView1.Columns.Add(col4);
然后,添加一个单元格格式事件处理程序的DataGridView:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].DataBoundItem != null &&
dataGridView1.Columns[e.ColumnIndex].DataPropertyName.Contains("."))
{
e.Value = BindProperty(dataGridView1.Rows[e.RowIndex].DataBoundItem,
dataGridView1.Columns[e.ColumnIndex].DataPropertyName);
}
}
private string BindProperty(object property, string propertyName)
{
string retValue = "";
if (propertyName.Contains("."))
{
PropertyInfo[] arrayProperties;
string leftPropertyName;
leftPropertyName = propertyName.Substring(0, propertyName.IndexOf("."));
arrayProperties = property.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in arrayProperties)
{
if (propertyInfo.Name == leftPropertyName)
{
retValue = BindProperty(propertyInfo.GetValue(property, null),
propertyName.Substring(propertyName.IndexOf(".") + 1));
break;
}
}
}
else
{
Type propertyType;
PropertyInfo propertyInfo;
propertyType = property.GetType();
propertyInfo = propertyType.GetProperty(propertyName);
retValue = propertyInfo.GetValue(property, null).ToString();
}
return retValue;
}
对于单元格格式的一个完整的指南,浏览here上安东尼奥·贝洛的博客,它是在那里我得到了主意。^_^ 我也在这里问过两天前的同一个问题,并得到了和你一样的答案,而且我知道这不是你想要做的。希望它可以帮助你。
感谢您的回答。我如何更改标题文本? – ehh
@ehh你指的是DataGrid的头?如果是,您可以在datagridview的属性中更改它。 –
是的,谢谢。我想知道它是否可以作为匿名方法的一部分来完成。 Servicename没有“服务名称”(或不同的语法) – ehh