这是我的代码:
void Main() {
List<Restaurant> restaurants = new List<Restaurant>();
}
class Restaurant {
public int Id;
public List<Complaint> Complaints = new List<Complaints>();
}
class Complaint {
public string Name;
public string Address;
public int Age;
public DateTime ComplaintDate;
}
我想在DataGridView控件中呈现RestaurantData中的数据,这是Class类的一个对象。首先,我想显示餐厅的ID,然后是餐厅投诉的数量,以便它看起来像这样(ID在A栏中,名称在B栏,等等): / p>
我过去对DataGridView的使用仅限于dataGridView1.DataSource =(某些数组)。但是,这次我要呈现的信息显然不是一个数组,所以我被卡住了。
答案 0 :(得分:1)
如果你想将列剔除到你自己的列表中,可以这样做:
private void AddColumns()
{
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn ageColumn =
new DataGridViewTextBoxColumn();
ageColumn.Name = "Age";
ageColumn.DataPropertyName = "Age";
ageColumn.ReadOnly = true;
DataGridViewTextBoxColumn nameColumn =
new DataGridViewTextBoxColumn();
nameColumn.Name = "Name";
nameColumn.DataPropertyName = "Name";
nameColumn.ReadOnly = true;
DataGridViewTextBoxColumn addressColumn =
new DataGridViewTextBoxColumn();
addressColumn.Name = "Address";
addressColumn.DataPropertyName = "Address";
addressColumn.ReadOnly = true;
DataGridViewTextBoxColumn dateColumn =
new DataGridViewTextBoxColumn();
addressColumn.Name = "Date";
addressColumn.DataPropertyName = "Date";
addressColumn.ReadOnly = true;
dataGridView1.Columns.Add(ageColumn);
dataGridView1.Columns.Add(nameColumn);
dataGridView1.Columns.Add(addressColumn);
dataGridView1.Columns.Add(dateColumn);
var ds = (from r in restaurants
from c in r.Complaints
select new {Id = r.Id, Address =c.Address, Age = c.Age, Name = c.Name, Date = c.ComplaintDate}
).ToList();
dataGridView1.DataSource = ds;
}
如果您只想自动生成列,请尝试以下方法:
private void AddColumns()
{
dataGridView1.AutoGenerateColumns = true;
var ds = (from r in restaurants
from c in r.Complaints
select new {Id = r.Id, Address =c.Address, Age = c.Age, Name = c.Name, Date = c.ComplaintDate}
).ToList();
dataGridView1.DataSource = ds;
}