简体   繁体   中英

Add new row to DataGridView C#

I searching for a easy method for adding new row to datagrid. So, what I have:

dataGridView2.ColumnCount = 4;
int w = 0;
foreach (var item in tInArr)
{...
dataGridView2.Rows.Add();
dataGridView2[0, w].Value = muTat3.ToString();
dataGridView2[1, w].Value = item.ToString();
....
w++;}

Where is my mistake? I've read some articles here, but there's no answers.

if you have no datasource, then you can go the following way:

  int rowIndex = dataGridView1.Rows.Add();
  dataGridView1[0, rowIndex].Value = "value1"; // 0 for first column
  dataGridView1[1, rowIndex].Value = "value2"; // 1 for second column
  rowIndex = dataGridView1.Rows.Add();
  dataGridView1[0, rowIndex].Value = "value3";
  dataGridView1[1, rowIndex].Value = "value4";

in your code it should be:

// dataGridView2.ColumnCount = 4;  
int w = 0;
foreach (var item in tInArr)
{...
  w = dataGridView2.Rows.Add();
  dataGridView2[0, w].Value = muTat3.ToString();
  dataGridView2[1, w].Value = item.ToString();
  ....
  //w++; this is not required
}

Here you can use datable then iterate your loop like this way :

 foreach (DataRow rows in dt.Rows)
 {..

     int w =  dataGridView2.Rows.Add();

     dataGridView2[0, w].Value =  rows[0].ToString();
     dataGridView2[1, w].Value = rows[1].ToString();
  }

First You create the datatable and then you can set the datasource of datagrid its long but easy to maintain.

like this

DataTable table = new DataTable();
table.Columns.Add("Check", typeof(bool));
table.Columns.Add("Path", typeof(string));
table.Columns.Add("Date", typeof(DateTime));


table.Rows.Add(false, "", DateTime.Now);
dataGridView2.DataSource = table;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM