我需要获取文件的第一行并将字符串的单词放入DataGridView的第一列。
我编写了这段代码,其中csv文件被转换为数组列表:
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是这样的:
**Subject Type**
Name
Surname
Telephone
Address
所以我需要获取文件的第一行并将其放到DataGridView的第一列。
到目前为止,我已经制作了这种方法。
ArrayList forData = new ArrayList();
string stringforData;
public void ToDataGrid()
{
DataGridViewColumn newCol = new DataGridViewTextBoxColumn();
forData.Add(stringforData.Split(';'));
}
方法ToDataGrid必须将名为forData的ArrayList元素放到DataGridView的第一列。
请帮助!!
答案 0 :(得分:3)
下面的代码采用分隔字符串,将其拆分,然后将值添加到datagridview列。虽然我仍然在努力想知道你为什么要这样做。
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);
}
答案 1 :(得分:0)
我提供这个答案是基于您希望将分隔文件的每一行放入datagridview行的假设。如果这实际上不是您想要的,请添加评论。
string csv = "John,Doe,21";
string[] split = csv.Split(',');
DataGridViewTextBoxColumn firstName = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn lastName = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn age = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Add(firstName);
dataGridView1.Columns.Add(lastName);
dataGridView1.Columns.Add(age);
dataGridView1.Rows.Add(split);
上面的代码显然只能在一行上运行,但你可以很容易地在循环中调用它。如果这样做,请注意不要在该循环中添加列!
这可以作为在网格中显示分隔文件的快捷方式,但如果我正在编写此代码,我会将文件解析为对象模型,然后将这些对象的列表绑定到datagridview数据源 - 这将为您提供双向数据绑定和更加可管理的数据处理方式。
即使像我在下面展示的那些简陋的东西也会更清洁:
var users = (from line in File.ReadAllLines(@"C:\mycsv.txt")
let columns = line.Split(',')
select new User()
{
FirstName = columns[0],
Surname = columns[1],
Age = columns[2]
}).ToList();
dataGridView1.DataSource = users;