在做一个摇奖程序,但是在从textbox输入时如果多按了一次回车键就会在listbox里多一行空行,请问如何去除空行?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int i,j;
        public Form1()
        {
            InitializeComponent();
        }        private void Form1_Load(object sender, EventArgs e)
        {
            j = 0;
        }        private void button1_Click(object sender, EventArgs e)
        {
            string str = textBox1.Text.ToString();
            string news = str.Replace( " ","" );     //去除全部空格
            for (i = 0; i < listBox1.Items.Count;i++ )
            {
                
                if (news == listBox1.Items[i].ToString())
                {
                    //if (textBox1.Text == " ")
                    //{ listBox1.Items.RemoveAt(i); }
                   
                    listBox1.Items.RemoveAt(i);
                }
            }
            //if (textBox1.Text == " ")
            //{ textBox1.Text = ""; }
            //else
            //{
                listBox1.Items.Add(news);
                textBox1.Text = null;
                i = listBox1.Items.Count;
            //}
            
        }        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer1.Interval = 100;
        }        private void timer1_Tick(object sender, EventArgs e)
        {
            j++;
            if (j < i)
            {                label2.Text = listBox1.Items[j].ToString();            }
           
            else
                j = 0;
            
        }        private void button3_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter)
            {
            string str = textBox1.Text.ToString();
            string news = str.Replace(" ", "");   
            for (i = 0; i < listBox1.Items.Count; i++)
            {                if (news == listBox1.Items[i].ToString())
                {
                    listBox1.Items.RemoveAt(i);
                }
            }
            
            listBox1.Items.Add(news);
            textBox1.Text = null;
            //i = listBox1.Items.Count;
            }
        }
    }
}

解决方案 »

  1.   

    观察你取出来的字符串   看看里面多了什么 比如 \r \n \r\n
    然后用Replace 替换成空就可以了 string s = textBox1.Text.ToString();   
     string s1 = Replace(s,"");
      

  2.   

    搞错了 应该是这样string s = textBox1.Text.ToString();   
     string s1 = s.Replace("\r\n","");
      

  3.   

    那再试试
    string s1 = s.Replace("\n","");

    string s1 = s.Replace("\r","");
      

  4.   

    string news = str.Trim( new char[] { '\r','\n'} )