How to add a new row to datagridview programmatically

前端 未结 18 1735
滥情空心
滥情空心 2020-11-22 09:40

if add row to DataTable

DataRow row = datatable1.NewRow();
row[\"column2\"]=\"column2\";
row[\"column6\"]=\"column6\";
datatable1.Rows.Add(row);         


        
相关标签:
18条回答
  • 2020-11-22 09:57

    If you are binding a List

    List<Student> student = new List<Student>();
    
    dataGridView1.DataSource = student.ToList();
    student .Add(new Student());
    
    //Reset the Datasource
    dataGridView1.DataSource = null;
    dataGridView1.DataSource = student;
    

    If you are binding DataTable

    DataTable table = new DataTable();
    
     DataRow newRow = table.NewRow();
    
    // Add the row to the rows collection.
    table.Rows.Add(newRow);
    
    0 讨论(0)
  • 2020-11-22 10:01

    Adding a new row in a DGV with no rows with Add() raises SelectionChanged event before you can insert any data (or bind an object in Tag property).

    Create a clone row from RowTemplate is safer imho:

    //assuming that you created columns (via code or designer) in myDGV
    DataGridViewRow row = (DataGridViewRow) myDGV.RowTemplate.Clone();
    row.CreateCells(myDGV, "cell1", "cell2", "cell3");
    
    myDGV.Rows.Add(row);
    
    0 讨论(0)
  • 2020-11-22 10:02
    //header
    dataGridView1.RowCount = 50;
    dataGridView1.Rows[0].HeaderCell.Value = "Product_ID0";
    
    
    //add row by cell 
     dataGridView1.Rows[1].Cells[0].Value = "cell value";
    
    0 讨论(0)
  • 2020-11-22 10:04

    If the grid is bound against a DataSet / table its better to use a BindingSource like

    var bindingSource = new BindingSource();
    bindingSource.DataSource = dataTable;
    grid.DataSource = bindingSource;
    
    //Add data to dataTable and then call
    
    bindingSource.ResetBindings(false)    
    
    0 讨论(0)
  • 2020-11-22 10:04
    string[] splited = t.Split('>');
    int index = dgv_customers.Rows.Add(new DataGridViewRow());
    dgv_customers.Rows[index].Cells["cust_id"].Value=splited.WhichIsType("id;");
    

    But be aware, WhichIsType is the extension method I created.

    0 讨论(0)
  • 2020-11-22 10:07

    An example of copy row from dataGridView and added a new row in The same dataGridView:

    DataTable Dt = new DataTable();
    Dt.Columns.Add("Column1");
    Dt.Columns.Add("Column2");
    
    DataRow dr = Dt.NewRow();
    DataGridViewRow dgvR = (DataGridViewRow)dataGridView1.CurrentRow;
    dr[0] = dgvR.Cells[0].Value; 
    dr[1] = dgvR.Cells[1].Value;              
    
    Dt.Rows.Add(dR);
    dataGridView1.DataSource = Dt;
    
    0 讨论(0)
提交回复
热议问题