手动将行值添加到Gridview

时间:2014-04-20 07:56:55

标签: c# asp.net winforms gridview datagridview

我有一个winform应用程序,其中我有一个网格视图,应该从数据库中搜索数据并显示到gridview。

这是我的代码,用于创建列并向其添加行值。

                while (dr.Read())
                {
                    DataGridViewColumn ad = new DataGridViewColumn();
                    DataGridViewCell cell = new DataGridViewTextBoxCell(); //Specify which type of cell in this column
                    ad.CellTemplate = cell;
                    ad.HeaderText = "Serial No";
                    ad.Name = "Serial No";
                    ad.Visible = true;
                    dataGridView2.Columns.Add(ad);
                    DataGridViewColumn ad1 = new DataGridViewColumn();
                    DataGridViewCell cell1 = new DataGridViewTextBoxCell(); //Specify which type of cell in this column
                    ad1.CellTemplate = cell1;
                    ad1.HeaderText = "Enrollment No.";
                    ad1.Name = "Enrollment No.";
                    ad1.Visible = true;
                    dataGridView2.Columns.Add(ad1);
                    DataGridViewColumn ad2 = new DataGridViewColumn();
                    DataGridViewCell cell2 = new DataGridViewTextBoxCell(); //Specify which type of cell in this column
                    ad2.CellTemplate = cell1;
                    ad2.HeaderText = "Student Name";
                    ad2.Name = "Studen Name";
                    ad2.Visible = true;
                    dataGridView2.Columns.Add(ad2);
                    DataGridViewRow row = new DataGridViewRow();
                    row.CreateCells(dataGridView2);
                    row.Cells[0].Value = dr.GetValue(0).ToString();
                    row.Cells[1].Value = dr.GetValue(1).ToString();
                    row.Cells[2].Value = dr.GetValue(2).ToString();
                    //row.Cells[3].Value = dr.GetValue(3).ToString();
                    //row.Cells[4].Value = dr.GetValue(4).ToString();
                    //row.Cells[5].Value = dr.GetValue(5).ToString();
                    dataGridView1.Rows.Add(row);
                    i++;
                }

我创建了3列,并且我试图将三个值从数据库存储到三个相应的单元格。

但在执行时我收到以下错误

  

没有行可以添加到没有列的DataGridView控件。必须先添加列。

我在做错了什么? 请告诉我。提前感谢您的帮助......

1 个答案:

答案 0 :(得分:1)

问题:您正在将列添加到dataGridView2,但最后您尝试将行添加到dataGridView1

解决方案:如果您打算将行添加到dataGridView2替换以下语句

替换它:

dataGridView1.Rows.Add(row);

有了这个:

dataGridView2.Rows.Add(row);