2014-01-10 39 views
1

我正在使用C#編寫Windows窗體應用程序。如何將DataGridView內容轉換爲自定義對象的List <>?

我發現有人建議如何從DataGridView控件創建List<>控件,但我需要更多幫助來了解如何提取單元格值。

這是給出的代碼;假設dataGridView1中的兩列是NameAddress
如何構建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); 
} 
+0

是否要獲取所有行列數據並將其插入列表中作爲一個記錄的字符串形式? – Abdul

回答

3

嘗試這種方式

創建類類型的列表

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);  
} 
1

鍵入您的數據如果你能夠使用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(); 
+0

我在你的Linq中發現dgvTest在當前上下文中不存在的錯誤。如何將var projectList轉換爲List?當我們用.ToList()轉換查詢時,爲什麼我們不能直接分配給List。我不想使用var,因爲我將在稍後使用list。 – user2026794

+0

@ user2026794 - 變量'dgvTest'用於說明。使用你的實際變量'dataGridView1',我也更新了我的答案。 'var'是一個隱式本地類型,它與'System.Object'不同,所以在上面的例子中,'var'變成'List '。 – Channs

相關問題