拆分后获取不正确的值

时间:2015-05-08 18:02:39

标签: c#

我想向string[] words存储了ID的用户发送消息。我试图将其输出到lable_name.Text。 ID显示正确,但在下一个方法中看起来string user_id看起来不正确。 我试图更改lable_name.Text = words[2] lable_name.Text = "65896237",但一切都很好。

我只是调查了Debuger - 它说,lable_name.Text="65896237\r\n" 是这个原因吗?我怎样才能获得明确的价值?

  private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            int count = listBox1.Items.Count -1;
            for (int counter = count; counter >= 0; counter--)
            {
                if (listBox1.GetSelected(counter))
                { 
                     string[] words= listBox1.Items[counter].ToString().Split(' ');
                     lable_name.Text = words[2];
                }
            }
        }

        private void send_Click(object sender, EventArgs e)
        {
            if (radioMessage.Checked==true)
            {
            string user_id = lable_name.Text;
            string message = textBox1.Text;
            string url = "https://api.vk.com/method/messages.send?user_id="+user_id+"&message="+message+"&v=5.31&access_token=...";
            WebClient client = new WebClient();
            string json = client.DownloadString(url);
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            RootObject response = (RootObject)json_serializer.Deserialize(json, typeof(RootObject));
            MessageBox.Show("This is Message");
            }
            else
            {...

2 个答案:

答案 0 :(得分:2)

  

我只是调查了Debuger - 它说,lable_name.Text =“65896237 \ r \ n”是什么原因?我怎样才能获得明确的价值?

你可以trim white space,例如空格,制表符,回车符和来自变量的换行符,如

string trimmed = lable_name.Text.Trim();

答案 1 :(得分:1)

您可以在拆分

之前或之后移除/n/r
int count = listBox1.Items.Count -1;
for (int counter = count; counter >= 0; counter--)
{
    if (listBox1.GetSelected(counter))
    { 
        string[] words= listBox1.Items[counter].ToString().Replace("\r\n", string.Empty).Split(' ');
        lable_name.Text = words[2];
    }
}