DataGridView 콘텐츠를 사용자 정의 개체의 List<>로 변환하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com//questions/21036679

문제

저는 C#으로 작성된 Windows Forms 응용 프로그램을 개발 중입니다.

만드는 방법에 대한 누군가의 제안을 찾았습니다. List<> ~에서 DataGridView 제어할 수 있지만 셀 값을 추출하는 방법에 대해서는 추가 도움이 필요합니다.

주어진 코드는 다음과 같습니다.두 개의 열이 있다고 가정해 보겠습니다. dataGridView1 ~이다 Name 그리고 Address.
구축 방법 List<ProjList> 물체?

foreach (DataGridViewRow dr in dataGridView1.Rows)
{
    ProjList = new List<ProjectMasterRec>();

    foreach (DataGridViewCell dc in dr.Cells)
    {
        // build out MyItem
        // based on DataGridViewCell.OwningColumn and DataGridViewCell.Value
        // how do we code this?
    }

    ProjList.Add(item);
}
도움이 되었습니까?

해결책

이렇게 해보세요

수업 유형 목록 만들기

List<ProjectMasterRec>() ProjList = new List<ProjectMasterRec>(); 

목록 유형이 Datagridview의 데이터 유형에 속하는지 확인하십시오.

foreach (DataGridViewRow dr in dataGridView1.Rows)
{
    //Create object of your list type pl
    ProjectMasterRec pl = new ProjectMasterRec();
    pl.Property1 = dr.Cells[1].Value;
    pl.Property2 = dr.Cells[2].Value;
    pl.Property3 = dr.Cells[3].Value;

    //Add pl to your List  
    ProjList.Add(pl);     
}

다른 팁

LINQ를 사용할 수 있으면 다음과 같이 할 수 있습니다.

var projectList = (from row in dataGridView1.Rows.OfType<DataGridViewRow>()
                   select new ProjectMasterRec() 
                   { Name = row.Cells["Name"].Value.ToString(),
                     Address = row.Cells["Address"].Value.ToString() 
                   }).ToList();

다음이 작동해야합니다. myArray 필요한 유형의 배열이어야 합니다. 다음을 사용하여 배열 크기를 확인할 수 있습니다. (DataGrid1.DataSource as BindingSource).List.Count.

(DataGrid1.DataSource as BindingSource).List.CopyTo(myArray, 0);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top