为什么我看不到添加到DataGridView的DataGridViewRow?

我试图在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"; 

执行此代码后,会发生四件值得注意的事情:

  • 我可以在dataGridView1中看到一个新行。
  • 里面没有文字。
  • 执行row.SetValues方法后,rowset为false。
  • 行标记值已正确设置。

为什么DataGridView不显示数据?

 List 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

我发现这不是我的解决方案,因为我不想清除datagridview中的所有行,只需用一个额外的\ new行重新插入它们。 我的collections品数以万计,而上述解决方案是缓慢的方式….

在更多地使用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; } 
 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(); } 

试试这个