C# 点击按钮弹出OpenFileDialog找到并选择txt文件打开,txt内容将会分别显示到textBox,dataGridView
TXT内容如下:
! NAME ! LENTH 0! DATE 2014-09-27! FREQ 1880! COUNT 1368! GAIN 0 ! PLANE H! MAIN M ! POLARIZE +45 ! PORT 1180.00 -66.63 -66.54 -180.00 -66.54 -66.54-180.00 -66.54 -66.61-179.99 -66.61 -66.69-179.98 -66.69 -66.69
要求显示效果如下:
===============初学C#,本人菜鸟一个,希望大神们给出具体代码,最好带上注释。我好学习学习 展开
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace txt_datagriview
{
public partial class Form1 : Form
{
private string fileName;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog(); //new一个方法
ofd.Filter = "(*.txt)|*.txt";//删选、设定文件显示类型
ofd.ShowDialog(); //显示打开文件的窗口
fileName = ofd.FileName; //获得选择的文件路径
Read_Settxt();
}
private void Read_Settxt()
{
if (File.Exists(fileName)) //如果文件存在
{
StreamReader sr = new StreamReader(fileName, Encoding.Default);//读文件
string s;
int i = 0;
while ((s = sr.ReadLine()) != null && s != string.Empty) //一行行读,如果读取内空不为空 {
i++;//一行一行读
if(i==1)
{
textBox1.Text = s;
}
else if (i == 2)
{
textBox2.Text = s;
}
else if (i == 3)
{
textBox3.Text = s;
}
else if (i == 4)
{
textBox4.Text = s;
}
else if (i == 5)
{
textBox5.Text = s;
}
else if (i == 6)
{
textBox6.Text = s;
}
else if (i == 7)
{
textBox7.Text = s;
}
else if (i == 8)
{
textBox8.Text = s;
}
else if (i == 9)
{
textBox9.Text = s;
}
else if (i == 10)
{
textBox10.Text = s;
}
else if (i > 10)
{
string[] ch = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);//遇到空格截取,得到数组。
dataGridView1.Rows.Add(ch[0], ch[1], ch[2]);//截得的数组添加到 dataGridView1,此处文本是三列,列数要固定,多少列根据情况修改。行数可以不固定
}
else
{
MessageBox.Show("不能读取此数据格式的数据");
}
}
}
}
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) //datagridview 自动添加行号,可以不要。
{
Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
dataGridView1.RowHeadersWidth - 4,
e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
dataGridView1.RowHeadersDefaultCellStyle.Font,
rectangle,
dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
}
}