拆分字符串并将其放在DataGridView的第一列中

拆分字符串并将其放在DataGridView的第一列中

本文介绍了C#:拆分字符串并将其放在DataGridView的第一列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用文件的第一行,并将字符串的单词放入DataGridView的第一列.

I need to take the first line of a file and put the words of the string into the first column of a DataGridView.

我已将以下代码编写为将csv文件转换为数组列表的代码:

I have written this code where a csv file is converted to a array list:

ArrayList fileList = new ArrayList();

private void button2_Click(object sender, EventArgs e)
{
    string line;

    // Read the file and display it line by line.

    //Read the path from the TextBox
    System.IO.StreamReader file = new System.IO.StreamReader(textBox1.Text);

    stringforData=file.ReadLine(); //this line is because I didn't need //the first
    //line of the file
    while ((line = file.ReadLine()) != null)
    {
        // puts elements into array
        fileList.Add(line.Split(';'));
    }

    file.Close();
}

我的文件是这样的:

Name;Surname;Telephone;Address;
george;parado;3434;lili_2;
jennifer;macin;3333;powel_34;
nick;lukas;3322;manchester_44;

我希望DataGridView像这样:

I want the DataGridView to be like this :

**Subject      Type**
Name
Surname
Telephone
Address

因此,我需要将文件的第一行放入到DataGridView的第一列中.

So I need to take the first line of the file and put it to the first column of a DataGridView.

到目前为止,我已经采用了这种方法.

As far as now I have made this method.

ArrayList forData = new ArrayList();
string stringforData;

public void ToDataGrid()
{
    DataGridViewColumn newCol = new DataGridViewTextBoxColumn();

    forData.Add(stringforData.Split(';'));

}

方法ToDataGrid必须将名为forData的ArrayList的元素放入DataGridView的第一列.

The method ToDataGrid must put the elements of the ArrayList named forData to the first column of the DataGridView.

请帮助!

推荐答案

下面的代码采用带分隔符的字符串,将其拆分,然后将值添加到datagridview列.尽管我仍在努力寻找为什么要这样做.

The code below takes a delimited string, splits it and then adds the values to a datagridview column. Though I'm still struggling to see why you want to do this.

string csv = "Name,Surname,Telephone,Address";
string[] split = csv.Split(',');

DataGridViewTextBoxColumn subject = new DataGridViewTextBoxColumn();
subject.HeaderText = "Subject Type";
subject.Name = "Subject";

dataGridView1.Columns.Add(subject);

foreach (string item in split)
{
    dataGridView1.Rows.Add(item);
}

这篇关于C#:拆分字符串并将其放在DataGridView的第一列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 19:34