2014-02-19 37 views
-2

所以我希望做的是加載一個txt文件到C#和TXT文件的每一行有部分寫入從文本文件不同的文本。插入到textBox中

NTM-120 = textBox1 
NTM-130 = textBox2 
NTM-140 etc.... 
NTM-150 
NTM-160 
NTM-170 

這是可能的嗎?

這樣的事?????

using (StreamReader reader = File.OpenText("yourFileName.txt")) 
{ 
    textBox1.Text = reader.ReadLine(); 
    textBox2.Text = reader.ReadLine(); 
    textBox3.Text = reader.ReadLine(); 
    textBox4.Text = reader.ReadLine(); 
    textBox5.Text = reader.ReadLine(); 
    textBox6.Text = reader.ReadLine(); 
    textBox7.Text = reader.ReadLine(); 
    textBox8.Text = reader.ReadLine(); 
    textBox9.Text = reader.ReadLine(); 
} 
+6

是的,這是可能的。 – GvS

+2

你標記這個sql的任何原因?我在這個問題上看不到sql ......或者當然你已經嘗試過的代碼到目前爲止。 – Chris

+0

這取決於。什麼樣的文本框?在網頁上或Windows窗體應用程序? – pid

回答

1

試試這個:

int count=1; 
var lines = File.ReadAllLines("C:\\Data.txt"); 
int totalTxtBoxControls=20; 
if(lines.Count==totalTxtBoxControls) 
{ 
((TextBox)this.Controls.Find("TextBox" + count, true)[0]).Text = line[count-1]; 
count++; 
} 
0

聽起來像是你有沒有想過如何做到這一點,也沒有嘗試過,但基本上

string[] lines = System.IO.File.ReadAllLines("source.txt"); 
foreach(string line in lines) 
{ 
    // put you logic on which line goes to which textbox 
} 

嗯?

0

可以使用

private void button1_Click(object sender, EventArgs e) 
{ 
    using (StreamReader sr = new StreamReader(filePath)) 
    { 
     int lineNumber = 0; 
     while (!sr.EndOfStream) 
     { 
      lineNumber++; 
      var readLine = sr.ReadLine(); 
      if (readLine != null) 
      { 
       TextBox textBox = GetControle(this, "textBox"+lineNumber); 
       if (textBox != null) 
       { 
        textBox.Text = readLine; 
       } 
      } 
     } 
    } 
} 

private TextBox GetControle(Control ctrlContainer, string name) 
{ 
    foreach (Control ctrl in ctrlContainer.Controls) 
    { 
     if (ctrl.GetType() == typeof(TextBox)) 
     { 
      if (ctrl.Name == name) 
      { 
       return (TextBox)ctrl; 
      } 
     } 
     if (ctrl.HasChildren) 
      GetControle(ctrl, name); 
    } 
    return null; 
} 
0

試試這個。它會爲文本文件中的每一行動態創建一個文本框!

TableLayoutPanel tlp = new TableLayoutPanel(); 
tlp.Dock = DockStyle.Fill; 

int row = 0; 
foreach (string s in File.ReadAllLines("file.txt")) 
{ 
    tlp.RowStyles.Add(new RowStyle()); 

    TextBox tb = new TextBox(); 
    tb.Text = s; 
    tlp.Controls.Add(tb, 0, row++); 
} 

this.Controls.Add(tlp);