思考邏輯:讀每一行資料時,計算是屬於哪一個 TextBox 的資料,並透過 Controls.Find() 來尋找控件,並把值塞進去;TextBox 控件命名,要從 1 - 18 依序命名
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TextBoxCreate();
}
private void TextBoxCreate()
{
for (int i = 1; i <= 18; i++)
{
TextBox control = new TextBox() {
Name = string.Format("TextBox{0}", i) ,
Text = string.Format("TextBox{0}", i)};
flowLayoutPanel1.Controls.Add(control);
if (i % 3 == 0)
flowLayoutPanel1.SetFlowBreak(control, true);
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
ofd.Filter = "(*.txt)|*.txt";
if (ofd.ShowDialog() != DialogResult.OK) return;
ReadTxtContent(ofd.FileName);
}
private void ReadTxtContent(string txtPath)
{
if (string.IsNullOrEmpty(txtPath))
throw new ArgumentNullException(string.Format("ReadTxtContent():txtPath 參數為 NULL"));
if (!File.Exists(txtPath))
throw new FileNotFoundException("ReadTxtContent():txtPath 參數,檔案不存在");
string AllContent = string.Empty;
using (FileStream fs = new FileStream(txtPath, FileMode.Open, FileAccess.Read))
using (StreamReader reader = new StreamReader(fs, Encoding.Default))
{
string
LineContent = string.Empty,
Data = string.Empty;
int
Row = 0,
TextBoxCount = 1;
while ((LineContent = reader.ReadLine()) != null)
{
string[] ColData = LineContent.Split(new char[] {' '} , StringSplitOptions.RemoveEmptyEntries);
if (ColData.Length != 3)
throw new Exception(string.Format("ReadTxtContent():資料異常"));
// 把 txt 檔案內資料放在畫面上,方便和下方的 TextBox 比較
txtContent.Text += LineContent + Environment.NewLine;
for (int ColCount = 0 ; ColCount < ColData.Length; ColCount++)
{
TextBoxCount = 3 * Row + (ColCount + 1);
Data = ColData[ColCount].ToString();
TextBoxDataFill(TextBoxCount, Data);
}
Row++;
}
}
}
private void TextBoxDataFill(int TargetTextbox , string data)
{
if (string.IsNullOrEmpty(data))
throw new ArgumentNullException(string.Format("TextBoxDataFill():data 參數為 NULL"));
string TextBoxName = string.Format("TextBox{0}", TargetTextbox);
Control[] ctls = flowLayoutPanel1.Controls.Find(TextBoxName , false);
TextBox ctl = ctls[0] as TextBox;
if (ctl == null)
throw new Exception(string.Format("TextBoxDataFill():{0} 不是 TextBox 控件", TextBoxName));
ctl.Text = data;
}
}
}
執行程式選擇 txt 檔案後
越搞越複雜的 fu,^^''
- 參考資料
- 論壇問題
- StackOverFlow 討論
- MSDN 討論 - 原 PO 在 MSDN 論壇上的 PO 文,利用正則表示式
沒有留言:
張貼留言