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

| 我正在尝试在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<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     
我发现这不是我的解决方案,因为我不想清除datagridview中的所有行以简单地用额外的\\ new行重新插入它们。我的收藏数以万计,而上述解决方案是减慢速度的方法。 在与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;
    }
    
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();
            }
尝试这个     

要回复问题请先登录注册