Skip to main content
 首页 » 编程设计

c#之如何将datagridview中的值存储到集合类C#

2024年02月27日35exmyth

首先,我将一个 csv 文件导入到 datagridview 并将其更改为我想要的格式。

我可以通过单击按钮过滤掉不需要的数据,然后使用 console.writeline 在控制台中获取我想要的数据。 (只是为了测试,所以我可以看到实际发生了什么)。有相当多的列不包含我要计算的数据,所以我使用 .contains() 和 .replace 将其过滤掉。

现在,我想将保存值的 cell.value.toString() 存储到数组中,但我不知道如何将数组植入其中。

这是代码

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
 
 
namespace test2 
{ 
    public partial class Form1 : Form 
    {    
        OpenFileDialog openFile = new OpenFileDialog(); 
 
        public int colC { get; private set; } 
 
        public Form1() 
        { 
            InitializeComponent(); 
        } 
 
 
        public void Button1_Click(object sender, EventArgs e) 
        { 
            if (openFile.ShowDialog() == DialogResult.OK) 
            { 
                List<string[]> rows = File.ReadLines(openFile.FileName).Select(x => x.Split(',')).ToList(); 
                DataTable dt = new DataTable(); 
                List<string> headerNames = rows[0].ToList(); 
 
                foreach (var headers in rows[0]) 
                { 
                    dt.Columns.Add(headers); 
                } 
                foreach (var x in rows.Skip(1).OrderBy(r => r.First())) 
                { 
                    if (x[0] == "Lot ID")   //linq to check if 2 lists are have the same elements (perfect for strings) 
                        continue;     //skip the row with repeated headers 
                    if (x.All(val => string.IsNullOrWhiteSpace(val))) //if all columns of the row are whitespace / empty, skip this row 
                        continue; 
                    dt.Rows.Add(x); 
                } 
 
                dataGridView1.DataSource = dt; 
                dataGridView1.ReadOnly = true; 
               // dataGridView1.Columns["Lot ID"].ReadOnly = true;     
                //dataGridView1.Columns[" Magazine ID"].ReadOnly = true; 
                //dataGridView1.Columns["Frame ID"].ReadOnly = true; 
 
            } 
        } 
 
        public void Form1_Load_1(object sender, EventArgs e) 
        { 
            openFile.Filter = "CSV|*.csv"; 
 
        } 
 
        public void Button2_Click(object sender, EventArgs e) 
        { 
 
            SaveFileDialog sfd = new SaveFileDialog(); 
            sfd.Filter = "txt files (*.txt)|*.txt|Csv files (*.csv)|*.csv"; 
            sfd.FilterIndex = 2; 
 
 
            if (sfd.ShowDialog() == DialogResult.OK) 
            { 
                try 
                { 
                    StreamWriter sw = new StreamWriter(sfd.FileName, false); 
                    { 
                        string columnHeaderText = ""; 
 
                        int countColumn = dataGridView1.ColumnCount - 1; 
 
                        if (countColumn >= 0) 
                        { 
                            columnHeaderText = dataGridView1.Columns[0].HeaderText; 
                        } 
 
                        for (int i = 1; i <= countColumn; i++) 
                        { 
                            columnHeaderText = columnHeaderText + ',' + dataGridView1.Columns[i].HeaderText; 
                        } 
 
 
                        sw.WriteLine(columnHeaderText); 
 
                        foreach (DataGridViewRow dataRowObject in dataGridView1.Rows) 
                        { 
                            if (!dataRowObject.IsNewRow) 
                            { 
                                string dataFromGrid = ""; 
 
                                dataFromGrid = dataRowObject.Cells[0].Value.ToString(); 
 
                                for (int i = 1; i <= countColumn; i++) 
                                { 
                                    dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString(); 
 
                                } 
                                sw.WriteLine(dataFromGrid); 
                            } 
                        } 
 
                        sw.Flush(); 
                        sw.Close(); 
                    } 
                } 
                catch (Exception exceptionObject) 
                { 
                    MessageBox.Show(exceptionObject.ToString()); 
                } 
                } 
            } 
 
        public void Button3_Click(object sender, EventArgs e) 
        { 
 
 
            foreach (DataGridViewRow row in dataGridView1.Rows) 
            { 
                foreach (DataGridViewCell cell in row.Cells) 
                { 
                    //prevent error occur coz , only execute the not null line 
                    if(cell.Value != null) 
                    { 
                        string cellV = cell.Value.ToString(); 
 
                        //do operations with cell, filter out the unnecessary data  
                        if (!cellV.Contains("=")) 
                        { 
                            continue; 
                        } 
                       else if (cellV.Contains("P = ")) 
                        { 
                            cellV = cellV.Replace("P = ", ""); 
                        } 
                        else if (cellV.Contains("F = n/a")) 
                        { 
                            cellV =cellV.Replace("F = n/a", "0"); 
 
                        } 
                        else if (cellV.Contains("F = ")) 
                        { 
                            cellV = cellV.Replace("F = ", ""); 
 
                        } 
 
                        Console.WriteLine(cellV + "\n"); 
                    } 
 
                } 
            } 
 
        } 
 
    } 
    } 

请看最后的方法和图片。

这是输出。

我使用continue跳过所有与计算无关的数据

如何将筛选出的数据存储到数组中???

如果您对这个问题有任何疑问,请随时询问。

请您参考如下方法:

希望对您有所帮助。首先也是更重要的是,当您循环遍历 DataGridView 时有一个DataSource , 最好通过 DataSource 进行修改/添加等……而不是网格。在此示例中,它没有任何区别,但是,下面的代码循环遍历 DataSource (DataTable)而不是网格。

下面是经过修改的按钮 3 单击它将把包含等号“=”的字符串转换为 decimal值。如果字符串包含等号“=”字符并且在等号后没有有效的十进制数……返回零 (0)。辅助方法用于获取字符串“P = XX.xx”并返回有效的 decimal。数字或零 (0)(如果数字无效)。希望这是有道理的。

private void button3_Click(object sender, EventArgs e) { 
  decimal decimalNumber = 0.0m; 
  foreach (DataRow row in dt.Rows) { 
    for (int i = 0; i < dt.Columns.Count; i++) { 
      if (row.ItemArray[i] != null) { 
        if (row.ItemArray[i].ToString().Contains("=")) { 
          decimalNumber = GetDecimalFromEquation(row.ItemArray[i].ToString()); 
          textBox1.Text += decimalNumber.ToString() + Environment.NewLine; 
        } 
      } 
    } 
    textBox1.Text += Environment.NewLine; 
  } 
} 
 
private decimal GetDecimalFromEquation(string numberString) { 
  decimal parsedValue = 0.0m; 
  if (numberString.Contains("=")) { 
    numberString = numberString.Replace(" ", ""); 
    string[] splitArray = numberString.Split('='); 
    if (splitArray.Length >= 2) { 
      decimal.TryParse(splitArray[1], out parsedValue); 
    } 
  } 
  return parsedValue; 
} 

读取 csv 方法的可能更简洁的版本。

private void button1_Click(object sender, EventArgs e) { 
  if (openFile.ShowDialog() == DialogResult.OK) { 
    List<string[]> rows = File.ReadLines(openFile.FileName).Select(x => x.Split(',')).ToList(); 
    List<string> headerNames = rows[0].ToList(); 
    foreach (var headers in rows[0]) { 
      dt.Columns.Add(headers); 
    } 
    foreach (var x in rows.Skip(1).OrderBy(r => r.First())) { 
      if ((!(x[0] == "Lot ID")) || (!(x.All(val => string.IsNullOrWhiteSpace(val))))) 
        dt.Rows.Add(x); 
    } 
    dataGridView1.DataSource = dt; 
    dataGridView1.ReadOnly = true; 
  } 
} 

最后,可能是 write 方法的更简洁版本。它使用 DataTable而不是网格本身。

private void button2_Click(object sender, EventArgs e) { 
  SaveFileDialog sfd = new SaveFileDialog(); 
  sfd.Filter = "txt files (*.txt)|*.txt|Csv files (*.csv)|*.csv"; 
  sfd.FilterIndex = 2; 
  if (sfd.ShowDialog() == DialogResult.OK) { 
    try { 
      using (StreamWriter sw = new StreamWriter(sfd.FileName, false)) { 
        string columnString = ""; 
        for (int i = 0; i < dt.Columns.Count - 1; i++) { 
          columnString += dt.Columns[i].ColumnName; 
          if (i < dataGridView1.Columns.Count - 2) 
            columnString += ","; 
        } 
        sw.WriteLine(columnString); 
        string rowString = ""; 
        foreach (DataRow dr in dt.Rows) { 
          rowString = ""; 
          for (int i = 0; i < dt.Columns.Count - 1; i++) { 
            rowString += dr.ItemArray[i].ToString(); 
            if (i < dt.Columns.Count - 2) 
              rowString += ","; 
          } 
          sw.WriteLine(rowString); 
        } 
      } 
    } 
    catch (Exception exceptionObject) { 
      MessageBox.Show(exceptionObject.ToString()); 
    } 
  } 
}