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

Nul*_*ead 5 .net c# datagridview winforms

我试图在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);
            }
Run Code Online (Sandbox Code Playgroud)

在表单加载时,我已将dataGridView1初始化为:

dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Name = "Name";
dataGridView1.Columns[1].Name = "Phone";
Run Code Online (Sandbox Code Playgroud)

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

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

为什么DataGridView不显示数据?

Nul*_*ead 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;
            }
Run Code Online (Sandbox Code Playgroud)

http://aspdiary.blogspot.com/2011/04/adding-new-row-to-datagridview.html