Подтвердить что ты не робот

Как добавить новую строку в datagridview программно

если добавить строку в DataTable

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

Как насчет DataGridView??

4b9b3361

Ответ 1

Вы можете сделать:

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

или

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

Другой способ:

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

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

Ответ 2

Вот так:

var index = dgv.Rows.Add();
dgv.Rows[index].Cells["Column1"].Value = "Column1";
dgv.Rows[index].Cells["Column2"].Value = 5.6;
//....

Ответ 3

Вот так:

 dataGridView1.Columns[0].Name = "column2";
 dataGridView1.Columns[1].Name = "column6";

 string[] row1 = new string[] { "column2 value", "column6 value" };
 dataGridView1.Rows.Add(row1);

Или вам нужно установить там значения индивидуально, используя свойство .Rows(), например:

 dataGridView1.Rows[1].Cells[0].Value = "cell value";

Ответ 4

Предположим, у вас есть datagridview, которое не привязано к набору данных, и вы хотите программно заполнить новые строки...

Вот как вы это делаете.

// 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 it! Quick and painless... :o)

Ответ 5

Добавление новой строки в DGV без строк с Добавить() вызывает событие SelectionChanged, прежде чем вы сможете вставить любые данные (или привязать объект в свойстве Tag).

Создать строку клона от RowTemplate безопаснее 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);

Ответ 6

Если сетка привязана к таблице DataSet/table, лучше использовать BindingSource, например

var bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
grid.DataSource = bindingSource;

//Add data to dataTable and then call

bindingSource.ResetBindings(false)    

Ответ 7

Вот как я добавляю строку, если dgrview пуст: (myDataGridView имеет два столбца в моем примере)

DataGridViewRow row = new DataGridViewRow();
row.CreateCells(myDataGridView);

row.Cells[0].Value = "some value";
row.Cells[1].Value = "next columns value";

myDataGridView.Rows.Add(row);

В соответствии с документами: "CreateCells() очищает существующие ячейки и устанавливает их шаблон в соответствии с предоставленным шаблоном DataGridView".

Ответ 8

вот еще один способ сделать такой

 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        dataGridView1.ColumnCount = 3;

        dataGridView1.Columns[0].Name = "Name";
        dataGridView1.Columns[1].Name = "Age";
        dataGridView1.Columns[2].Name = "City";

        dataGridView1.Rows.Add("kathir", "25", "salem");
        dataGridView1.Rows.Add("vino", "24", "attur");
        dataGridView1.Rows.Add("maruthi", "26", "dharmapuri");
        dataGridView1.Rows.Add("arun", "27", "chennai"); 
    }

Ответ 9

Если вам нужно манипулировать чем-либо, кроме строки Value Cell, например, добавить тег, попробуйте следующее:

DataGridViewRow newRow = (DataGridViewRow)mappingDataGridView.RowTemplate.Clone();
newRow.CreateCells(mappingDataGridView);

newRow.Cells[0].Value = mapping.Key;
newRow.Cells[1].Value = ((BusinessObject)mapping.Value).Name;
newRow.Cells[1].Tag = mapping.Value;

mappingDataGridView.Rows.Add(newRow);

Ответ 10

yourDGV.Rows.Add(column1,column2...columnx); //add a row to a dataGridview
yourDGV.Rows[rowindex].Cells[Cell/Columnindex].value = yourvalue; //edit the value

вы также можете создать новую строку, а затем добавить ее в DataGridView следующим образом:

DataGridViewRow row = new DataGridViewRow();
row.Cells[Cell/Columnindex].Value = yourvalue;
yourDGV.Rows.Add(row);

Ответ 11

Пример строки копирования из dataGridView и добавлена ​​новая строка в том же файле данныхGridView:

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;

Ответ 12

Рассмотрите приложение Windows и с помощью кнопки Click Event поместите этот код в него.

dataGridView1.Rows
                .Add(new object[] { textBox1.Text, textBox2.Text, textBox3.Text });

Ответ 13

//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; 

Ответ 14

Если вы уже определили DataSource, вы можете получить DataGridView DataSource и передать его как Datatable.

Затем добавьте новый DataRow и установите значения полей.

Добавьте новую строку в Datatable и примите изменения.

В С# это будет что-то вроде этого.

DataTable dataTable = (DataTable)dataGridView.DataSource;
DataRow drToAdd = dataTable.NewRow();

drToAdd["Field1"] = "Value1";
drToAdd["Field2"] = "Value2";

dataTable.Rows.Add(drToAdd);
dataTable.AcceptChanges();

Ответ 15

//header
dataGridView1.RowCount = 50;
dataGridView1.Rows[0].HeaderCell.Value = "Product_ID0";


//add row by cell 
 dataGridView1.Rows[1].Cells[0].Value = "cell value";

Ответ 16

string[] splited = t.Split('>');
int index = dgv_customers.Rows.Add(new DataGridViewRow());
dgv_customers.Rows[index].Cells["cust_id"].Value=splited.WhichIsType("id;");

Но имейте в виду, WhichIsType - это метод расширения, который я создал.