我正在尝试在DataGridView中显示行。
以下是代码:
foreach (Customers cust in custList)
{
string[] rowValues = { cust.Name, cust.PhoneNo };
DataGridViewRow row = new DataGridViewRow();
bool rowset = row.SetValues(rowValues);
row.Tag = cust.CustomerId;
dataGridView1.Rows.Add(row);
}
在表单加载时,我已将dataGridView1初始化为:
dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Name = "Name";
dataGridView1.Columns[1].Name = "Phone";
执行此代码后,会发生四件值得注意的事情:
为什么DataGridView不显示数据?
答案 0 :(得分:3)
List<customer> custList = GetAllCustomers();
dataGridView1.Rows.Clear();
foreach (Customer cust in custList)
{
//First add the row, cos this is how it works! Dont know why!
DataGridViewRow R = dataGridView1.Rows[dataGridView1.Rows.Add()];
//Then edit it
R.Cells["Name"].Value = cust.Name;
R.Cells["Address"].Value = cust.Address;
R.Cells["Phone"].Value = cust.PhoneNo;
//Customer Id is invisible but still usable, like,
//when double clicked to show full details
R.Tag = cust.IntCustomerId;
}
http://aspdiary.blogspot.com/2011/04/adding-new-row-to-datagridview.html
答案 1 :(得分:1)
我发现这不是我的解决方案,因为我不想清除datagridview中的所有行,只需用一个额外的\ new行重新插入它们。我的收藏品数以万计,而上述解决方案可以减缓......
在更多地使用DataGridViewRow类之后,我找到了NewRow.CreateCells(DataGridView,object [])的方法。
这允许使用datagridview中的格式正确绘制单元格。
似乎此页面顶部的问题代码将单元格留空,因为当新行插入数据网格视图时,类型不匹配。在新行上使用CreateCells方法并解析将插入行的DataGridView,允许将单元格类型传递到新行,而新行实际上会在屏幕上绘制数据。
这也允许您在将新行添加到datagridview之前将标记放在每个项目上,这是我的任务的必要条件。
请参阅下面的代码作为此示例.....
private void DisplayAgents()
{
dgvAgents.Rows.Clear();
foreach (Classes.Agent Agent in Classes.Collections.Agents)
{
DisplayAgent(Agent, false);
}
}
private void DisplayAgent(Classes.Agent Agent, bool Selected)
{
DataGridViewRow NewRow = new DataGridViewRow();
NewRow.Tag = Agent;
NewRow.CreateCells(dgvAgents, new string[]
{
Agent.Firstname,
Agent.Surname,
Agent.Email,
Agent.Admin.ToString(),
Agent.Active.ToString(),
});
dgvAgents.Rows.Add(NewRow);
NewRow.Selected = Selected;
}
答案 2 :(得分:0)
foreach (Customers cust in custList)
{
DataGridViewRow row = new DataGridViewRow();
dataGridView1.BeginEdit();
row.Cells["Name"] = cust.Name;
row.Cells["Phone"] = cust.PhoneNo;
row.Tag = cust.CustomerId;
dataGridView1.Rows.Add(row);
dataGridView1.EndEdit();
}
试试这个