簡體   English   中英

如何將datagridview中的單元格值保存到列表中 <list<> &gt;

[英]How to save cell value in datagridview into a list<list<>>

我有一個問題,但我不知道如何解決。 我有一個像這張照片的datagridview 在此處輸入圖片說明

如您所見,有兩個(A-> 1,A-> 2,A-> 3)和(B-> 1,B-> 2,B-> 3)我想這樣保存到文本文件,我想這樣保存A {{4.5,4.2,4.3}; {1.2,1.5,1.8}}和B {{4.3,1.8,1.9},{2.2,2.3,4.5}},但我不知道如何使用datagridview C#winform解決它。 有誰能夠幫助我 ? 非常感謝。

這可能會有所幫助: 從.txt文件讀取,然后將數據導出到DataGridView

用於讀取文本文件。 但是為了節省,我相信您可以將其“反向”編碼:)

//Ok, this should work.

//First, represent the datagridview in a more readeable List
class My_row
{
    public My_row(string Chemical, int Place, double Height)
    {
        this.Chemical = Chemical;
        this.Place = Place;
        this.Height = Height;
    }

    public string Chemical;
    public int Place;
    public double Height;
}

//then, the datagridview is this
List<My_row> rows = new List<My_row>;

foreach(var row in datagridview.rows)
{
    My_row my_row = new My_row(
        (string)row.Cells[0].value, 
        (int)row.Cells[1].value, 
        (double)row.Cells[2].value)
}
//with this you can loop the data easier plus you can use LINQ to order, filter and find the data in the datagridview

//Now, represent your final data structure

//In this case you have groups of 3 values of places 1, 2 and 3.
class Group
{
    double value_1;
    double value_2;
    double value_3;
}

//this groups of 3 values are in a bigger group that is the chemical.
class Chemical
{
    char name;
    List<Group> groups;
}

//finally your file is going to be a list of chemical
List<chemical> chemical_list;

//now you have to fill that list, then loop through it to write the file.
char previous_chemical = rows[0].chemical;//initial chemical letter
Chemical chemical = new Chemical();
chemical.name = rows[0].chemical;//initial chemical letter
Group group = new Group();
foreach(My_row row in rows)
{
    if(row.Chemical != previous_chemical)
    {
        previous_chemical = chemical.name;
        chemical_list.Add(chemical);
        chemical = new chemical();
        chemical.name = row.Chemical;
    }

    if(row.Place == 1){ group.value_1 = row.Height; }
    if(row.Place == 2){ group.value_2 = row.Height; }
    if(row.Place == 3)
    {
        group.value_3 = row.Height;
        chemical.Add(group);
        group = new Group();
    }
}

//That was he hard work. Now you have to loop the list (Chemicals, Groups and values) and write the file.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM