DataGridViewコンテンツをカスタムオブジェクトのリスト<>に変換する方法
-
21-12-2019 - |
質問
C#で書かれたWindowsフォームアプリケーションに取り組んでいます。
List<>
コントロールからDataGridView
を作成する方法についての誰かの提案を見つけましたが、セル値の抽出方法についてはもう少し助けが必要です。
これは与えられたコードです。dataGridView1
の2列の2列を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.CopyTo(myArray, 0);
. 所属していません StackOverflow