How to add a new row to datagridview programmatically

前端 未结 18 1734
滥情空心
滥情空心 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:50
    //Add a list of BBDD
    var item = myEntities.getList().ToList();
    //Insert a new object of type in a position of the list       
    item.Insert(0,(new Model.getList_Result { id = 0, name = "Coca Cola" }));
    
    //List assigned to DataGridView
    dgList.DataSource = item; 
    
    0 讨论(0)
  • 2020-11-22 09:51

    If you´ve already defined a DataSource, You can get the DataGridView´s DataSource and cast it as a Datatable.

    Then add a new DataRow and set the Fields Values.

    Add the new row to the DataTable and Accept the changes.

    In C# it would be something like this..

    DataTable dataTable = (DataTable)dataGridView.DataSource;
    DataRow drToAdd = dataTable.NewRow();
    
    drToAdd["Field1"] = "Value1";
    drToAdd["Field2"] = "Value2";
    
    dataTable.Rows.Add(drToAdd);
    dataTable.AcceptChanges();
    
    0 讨论(0)
  • 2020-11-22 09:53

    You can do:

    DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
    row.Cells[0].Value = "XYZ";
    row.Cells[1].Value = 50.2;
    yourDataGridView.Rows.Add(row);
    

    or:

    DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
    row.Cells["Column2"].Value = "XYZ";
    row.Cells["Column6"].Value = 50.2;
    yourDataGridView.Rows.Add(row);
    

    Another way:

    this.dataGridView1.Rows.Add("five", "six", "seven","eight");
    this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");
    

    From: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rows.aspx

    0 讨论(0)
  • 2020-11-22 09:53

    Like this:

    var index = dgv.Rows.Add();
    dgv.Rows[index].Cells["Column1"].Value = "Column1";
    dgv.Rows[index].Cells["Column2"].Value = 5.6;
    //....
    
    0 讨论(0)
  • 2020-11-22 09:56

    Consider a Windows Application and using Button Click Event put this code in it.

    dataGridView1.Rows
                    .Add(new object[] { textBox1.Text, textBox2.Text, textBox3.Text });
    
    0 讨论(0)
  • 2020-11-22 09:57

    Lets say you have a datagridview that is not bound to a dataset and you want to programmatically populate new rows...

    Here's how you do it.

    // Create a new row first as it will include the columns you've created at design-time.
    
    int rowId = dataGridView1.Rows.Add();
    
    // Grab the new row!
    DataGridViewRow row = dataGridView1.Rows[rowId];
    
    // Add the data
    row.Cells["Column1"].Value = "Value1";
    row.Cells["Column2"].Value = "Value2";
    
    // And that's it! Quick and painless... :o)
    
    0 讨论(0)
提交回复
热议问题