2011-10-10 81 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(文字串词)是没有意义的。你不需要它。删除它(但不是它的主体代码)
相关问题