CSharp - CSV到 ListView

  显示原文与译文双语对照的内容
0 0

我正在尝试将我的CSV文件导出到 ListView 。

ListView的外观如下:

http://screenshooter.net/7827870/vrwwokd

我已经导出了csv文件,但它将所有的东西都放在"姓名"列中。


private void toolStripButton1_Click(object sender, EventArgs e)
{


 using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
 try
 {
 openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
 openFileDialog1.DefaultExt ="csv";
 openFileDialog1.Title ="Open file";
 openFileDialog1.Filter ="CSV (*.csv)|*.csv";
 if (openFileDialog1.ShowDialog() == DialogResult.OK)
 {
 FileStream srcFS;
 srcFS = new FileStream(openFileDialog1.FileName, FileMode.Open);
 StreamReader srcSR = new StreamReader(srcFS,System.Text.Encoding.Default);
 do
 {
 string ins = srcSR.ReadLine();

 ListViewItem lvi = new ListViewItem();
 lvi.SubItems.Add(ins);

 if (ins!= null) listView1.Items.Add(lvi);
 else break;
 } while (true);
 srcSR.Close();
 }
 }
 catch (Exception errorMsg)
 {
 MessageBox.Show(errorMsg.Message,"Error reading a file",MessageBoxButtons.OK,MessageBoxIcon.Error);
 }

} 

谁有线索?

下面是它的外观:


 using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
 try
 {
 openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
 openFileDialog1.DefaultExt ="csv";
 openFileDialog1.Title ="Open file";
 openFileDialog1.Filter ="CSV (*.csv)|*.csv";
 if (openFileDialog1.ShowDialog() == DialogResult.OK)
 {
 FileStream srcFS;
 srcFS = new FileStream(openFileDialog1.FileName, FileMode.Open);
 StreamReader srcSR = new StreamReader(srcFS,System.Text.Encoding.Default);
 do
 {
 string ins = srcSR.ReadLine();
 string[] columns = ins.Split(',');

 ListViewItem lvi = new ListViewItem(columns[0]);

 lvi.SubItems.Add(ins);

 for (int i = 1; i <columns.Count(); i++)
 {
 lvi.SubItems.Add(columns[i]);
 }

 listView1.Items.Add(lvi);

 } while (true);
 srcSR.Close();
 }
 }
 catch (Exception errorMsg)
 {
 MessageBox.Show(errorMsg.Message,"Error reading a file",MessageBoxButtons.OK,MessageBoxIcon.Error);
 }

时间: 原作者:

0 0

现在,你将整个行添加为一个 listviewitem 。 首先,你需要将该行拆分为列:


string[] columns = ins.Split(';');

然后创建一个带有第一列的listviewitem 。


ListViewItem lvi = new ListViewItem(columns[0]);

然后迭代其余的项并为每个列添加一个子项:


for (int i = 1; i <columns.Count(); i++)
{
 lvi.SubItems.Add(columns[i]);
}

最后将listviewitem添加到 listview


listView1.Items.Add(lvi);

...