0

I am getting this error "No row can be added to a DataGridView control that does not have columns. Columns must be added first." what am i doing wrong here?

        //create datagridview1
          DataGridView dataGridView1 = new DataGridView();

         // DataGridViewColumn column = new DataGridViewTextBoxColumn();

          // Initialize the DataGridView.
          dataGridView1.AutoGenerateColumns = false;
          dataGridView1.AutoSize = true;

          DataGridViewColumn column1 = new DataGridViewTextBoxColumn();
          column1.DataPropertyName = "Column1";
          column1.Name = "title";
          dataGridView1.Columns.Add(column1);

          DataGridViewColumn column2 = new DataGridViewTextBoxColumn();
          column2.DataPropertyName = "Column2";
          column2.Name = "imageurl";
          dataGridView1.Columns.Add(column2);

          DataGridViewColumn column3 = new DataGridViewTextBoxColumn();
          column3.DataPropertyName = "Column3";
          column3.Name = "videourl";
          dataGridView1.Columns.Add(column3);

          DataGridViewColumn column4 = new DataGridViewTextBoxColumn();
          column4.DataPropertyName = "Column4";
          column4.Name = "done";
          dataGridView1.Columns.Add(column4);
3
  • that code is directly underneath private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { Commented Feb 20, 2014 at 13:33
  • dataGridView1.Rows.Add(title, "image", "videourl", "no"); Commented Feb 20, 2014 at 13:34
  • @mxadam Show the code that invokes backgroundWorker1.RunWorkerAsync();. It looks like a synchronization issue, could be that your thread is running before you add columns to your DataGrdiView. Commented Feb 20, 2014 at 14:41

1 Answer 1

0

try

dataGridView1.Columns.Add("Column","Test");

or if you want to choose coulmn type

DataGridViewColumn  newCol = new DataGridViewColumn(); // add a column to the grid
DataGridViewCell cell = new DataGridViewCell(); //Specify which type of cell in this column
newCol.CellTemplate = cell;

newCol.HeaderText = "test2";
newCol.Name = "test2";
newCol.Visible = true;
newCol.Width = 40;

gridColors.Columns.Add(newCol);

from here

You also can see MSDN example

Sign up to request clarification or add additional context in comments.

1 Comment

@mxadam, strange. I verify it and it's work to me. Pay attention: Add function receivce 2 parameters. one is column name and the second is the header.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.