CSV to Gridview in c#.net

本文关键字:net in Gridview to CSV | 更新日期: 2023-09-27 18:00:23

请告诉我如何上传csv文件以显示在网格视图中?

  private void button1_Click(object sender, EventArgs e)
  {
  }    
  private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
  {
  }

更新:

请告诉我哪里错了

我想在提交表单中的数据时添加行

private void button1_Click(object sender, EventArgs e)
    {
        if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "" )
        {
            dataGridView1.Rows.Add(1);
            dataGridView1.Rows[0].Cells[0].Value = textBox1.Text;
            dataGridView1.Rows[0].Cells[1].Value = textBox2.Text;
            dataGridView1.Rows[0].Cells[2].Value = textBox3.Text;
        }
    }

CSV to Gridview in c#.net

而不是这个:

 dataGridView1.Rows.Add(1);
 dataGridView1.Rows[0].Cells[0].Value = textBox1.Text;
 dataGridView1.Rows[0].Cells[1].Value = textBox2.Text;
 dataGridView1.Rows[0].Cells[2].Value = textBox3.Text;

尝试

dataGridView1.Rows.Add(textBox1.Text, textBox2.Text, textBox3.Text);

datagridview属性AllowUserToAddRows设置为false

这应该允许在Rows[0]处添加新行。

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "" )
    {
        dataGridView1.Rows.Add(1);
        dataGridView1.Rows[0].Cells[0].Value = textBox1.Text;
        dataGridView1.Rows[0].Cells[1].Value = textBox2.Text;
        dataGridView1.Rows[0].Cells[2].Value = textBox3.Text;
    }
}

注意:重复单击button1时,您将在网格中添加空白行。

在DataGridView中直接加载CSV文件的解决方案

string[] allRows = File.ReadAllLines(@"yourcsvfilepath.csv");
foreach (string sRow in allRows)
{
     string[] arrRow = sRow.Split(new char[] { ',' });
     dataGridView1.Rows.Add(arrRow);
}

假设:在设计时添加的列数。