日期:2014-05-18  浏览次数:20970 次

摇奖程序如何去掉空行
在做一个摇奖程序,但是在从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;
  }
  }
  }
}


------解决方案--------------------
搞错了 应该是这样

string s = textBox1.Text.ToString();
 string s1 = s.Replace("\r\n","");

------解决方案--------------------
那再试试
string s1 = s.Replace("\n","");

string s1 = s.Replace("\r"