2011-10-10 76 views
1

我有字符串的列表框。當我選擇其中一個字符串時,我將它分開。C#,將值發送到文本框

我想發送到textboxes該字符串的拆分值。如何將值發送到文本框?

我有這樣的C#代碼:

private void button8_Click(object sender, EventArgs e) 
{ 
    string Code; 
    string Name; 
    string PName; 
    string Cost; 
    string Num; 
    string Level; 

    using (var streamReader = new StreamReader(filePath, Encoding.Default)) 
    { 
     if (!streamReader.EndOfStream) 
     { 
      Items.Add(streamReader.ReadLine());//list Items 
     } 
    } 

    string z = listBox1.SelectedItem.ToString(); 

    string[] words = x.Split(','); 
    foreach (string word in words) 
    { 
     if (words.Length == 6) 
     { 
      Code = words[0]; 
      Name = words[1]; 
      PName = words[2]; 
      Cost = words[3]; 
      Num = words[4]; 
      Level = words[5]; 
     }     
    } 

    textBox1.Text = Code;  //This does not send anything to the textbox 
    textBox2.Text = Name; 
    textBox3.Text = PName; 
    textBox4.Text = Cost; 
    textBox5.Text = Num; 
    textBox6.Text = Level; 

    using (var streamWriter = new StreamWriter(
      filePath, false, Encoding.Default)) 
    { 
     foreach (string op in Items) 
     { 
      streamWriter.WriteLine(op); 
     } 
    } 
} 

的C#代碼,不會textBox1.Text = Code;不發送任何文字文本框,我如何分配一個字符串的文本框?

+0

你應該命名你的控件。 – SLaks

+1

你有什麼錯誤? – rohit89

+0

你得到什麼確切的錯誤?它看起來像你的分割失敗,你會把默認值,但String.Empty應該罰款TextBox.Text ... – AlG

回答

1

Code變量仍空當你把它分配給TextBox

將其更改爲:

string Code = string.Empty; 
// etc. 

基於您的示例代碼,雖然,你應該不需要任何的字符串變量或您的foreach。只需將其直接分配給您的文本框。

textBox1.Text = words[0]; 
textBox2.Text = words[1]; 
textBox3.Text = words[2]; 
textBox4.Text = words[3]; 
textBox5.Text = words[4]; 
textBox6.Text = words[5]; 

並嘗試給出您的控件名稱。 textBox4並沒有告訴你它與成本有關。

0

嘗試使用像直接分配它的語句,如textBox1.Text = Code.ToString();或 textBox1.Text = words [0] .ToString();也許它可以幫助你

1

如果你的變量Code只包含一個值,如果words.Length == 6。確保變量包含一個值。

使用,看看是否文本被保存到文本框:

textBox1.Text = "test"; 
1
  1. 分配列表框到z的設定值,但隨後調用拆分對未聲明的變量x
  2. 在foreach(文字串詞)是沒有意義的。你不需要它。刪除它(但不是它的主體代碼)
相關問題