[C#] 프로그래밍 방식으로 datagridview에 새 행을 추가하는 방법

행을 추가하면 DataTable

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

어때요 DataGridView?



답변

넌 할 수있어:

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


답변

이처럼 :

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


답변

데이터 세트에 바인딩되지 않은 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's it! Quick and painless... :o)


답변

이처럼 :

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


답변

아니 행으로 DGV에 새 행을 추가 추가 ()는 던질 수 인 selectionchanged 당신이 어떤 데이터를 삽입하기 전에 이벤트를 (또는 바인드 태그 속성의 객체).

RowTemplate 에서 복제 행을 만드는 것이 더 안전합니다.

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


답변

이것은 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 템플릿에 따라 템플릿을 설정합니다.”


답변

그리드가 DataSet / 테이블에 바인딩되어 있으면 다음과 같은 BindingSource를 사용하는 것이 좋습니다.

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

//Add data to dataTable and then call

bindingSource.ResetBindings(false)