C# 为什么可以';我没有看到DataGridViewRow添加到DataGridView中吗?
我试图在DataGridView中显示行 代码如下:C# 为什么可以';我没有看到DataGridViewRow添加到DataGridView中吗?,c#,.net,winforms,datagridview,C#,.net,Winforms,Datagridview,我试图在DataGridView中显示行 代码如下: foreach (Customers cust in custList) { string[] rowValues = { cust.Name, cust.PhoneNo }; DataGridViewRow row = new DataGridViewRow(); bool rowset = row.SetValues(r
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
- 行标记值设置正确
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();
}
试试这个List custList=GetAllCustomers();
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;
}
dataGridView1.Rows.Clear();
foreach(客户列表中的客户)
{
//首先添加行,因为它就是这样工作的!不知道为什么!
DataGridViewRow R=dataGridView1.Rows[dataGridView1.Rows.Add()];
//然后编辑它
R.Cells[“Name”].Value=cust.Name;
R.单元格[“地址”]。值=客户地址;
R.Cells[“Phone”]。Value=cust.PhoneNo;
//客户Id不可见但仍可使用,例如,
//双击以显示完整详细信息时
R.标记=cust.IntCustomerId;
}
我发现这不是我的解决方案,因为我不想清除datagridview中的所有行,而只是用一个额外的\新行重新插入它们。我的收藏是为数万人准备的,而上面的解决方案是一种缓慢的方式 在进一步使用DataGridViewRow类之后,我找到了NewRow.CreateCells(DataGridView,object[])的一个方法 这允许使用datagridview中的格式正确绘制单元格 该页面顶部的问题代码似乎将单元格留空,因为在将新行插入数据gridview时,类型不匹配。在新行上使用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;
}
row.cells[“”]需要一个单元格,但您提供的是字符串。但是,在根据您的解决方案进一步思考之前,行如何知道它有一个名为name或Phone的列?有什么想法吗?@Reddy S R in form load您已经使用BindingList初始化了iTunes我可以看到行中的数据,但我必须为行设置标记值,这在BindingList中是不可能的!