2014-03-02 1 views
13

, 나는 그것에 DataGridViewRows를 삽입하여 수동으로 DataGridView을 채우기 위해 노력하고있어, 그래서 내 코드는 다음과 같습니다 그러나DataGridViewRow의 셀 값을 열 이름으로 설정하는 방법은 무엇입니까? 창 형태에서

DataGridViewRow row = new DataGridViewRow(); 
row.CreateCells(dgvArticles); 
row.Cells[0].Value = product.Id; 
row.Cells[1].Value = product.Description; 
. 
. 
. 
dgvArticles.Rows.Add(row); 

, 나는 열 이름 셀 값을 추가하는 대신 싶습니다 이 같은 인덱스, 무언가에 의해 그 일 :

row.Cells["code"].Value = product.Id; 
row.Cells["description"].Value = product.Description; 

을하지만, 그런 식으로 일을하는 것은 "코드"라는 이름의 열을 찾을 수 없다는 오류가 발생합니다. 다음과 같이 디자이너의 DataGridView 열을 설정합니다.

잘못된 것이 있습니까? 내가하고 싶은 것을 어떻게 성취 할 수 있습니까?

답변

14

그래서 당신이 할이 방법이 필요 원하는 방식 달성하기 위해 : 당신이의의 ColumnName 인덱서를 사용하는 경우

//Create the new row first and get the index of the new row 
int rowIndex = this.dataGridView1.Rows.Add(); 

//Obtain a reference to the newly created DataGridViewRow 
var row = this.dataGridView1.Rows[rowIndex]; 

//Now this won't fail since the row and columns exist 
row.Cells["code"].Value = product.Id; 
row.Cells["description"].Value = product.Description; 
2

나는 그것을 시도하고 동일한 결과를 얻었다. 이것은 좀 장황하지만, 작동 :

row.Cells[dataGridView1.Columns["code"].Index].Value = product.Id; 
3

DataGridViewCellCollection, 내부적으로 소유/부모 DataGridView의 ColumnName을 사용하여이 DataGridViewRow 인스턴스의 열 인덱스를 가져 오려고합니다. 귀하의 경우 행은 DataGridView에 추가되지 않았으므로 소유 DataGridView는 null입니다. 그래서 코드 이름의 열을 찾을 수 없습니다. 하여 DataGridView에 행을 추가하고 그리드에서 행을 얻을 인스턴스에 반환 된 인덱스를 사용하고 세포에 액세스하려면 열 이름을 사용

는 IMO (데릭과 동일) 가장 좋은 방법이 될 것입니다.