如何删除空白

本文关键字:空白 删除 何删除 | 更新日期: 2023-09-27 17:58:11

我有一个简单的列表;一切都很好,但当我点击按钮,列表为empy时,元素之间会出现一个空格。如何移除它?

  private void button1_Click(object sender, RoutedEventArgs e)
    {
        if (textBox1.Text=="")
        {
            MessageBox.Show("Campul este liber!");
        }
        //ListBox li = sender as ListBox;

        ListBoxItem li = new ListBoxItem();
        li.Content=textBox1.Text;
        textBox1.Clear();
        listBox1.Items.Add(li);
        textBox1.Focus();


    }

代码xaml:

<Window x:Class="Lista.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="250" Width="325">
<Grid>
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="203,176,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    <ListBox Height="111" HorizontalAlignment="Left" Margin="12,59,0,0" Name="listBox1" VerticalAlignment="Top" Width="279" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="12,30,0,0" Name="textBox1" VerticalAlignment="Top" Width="279" />
</Grid>

http://i59.tinypic.com/den49d.png

如何删除空白

问题是添加了空字符串只需在消息框后返回。

private void button1_Click(object sender, RoutedEventArgs e)
    {
        if (textBox1.Text.Trim() =="")
        {
            MessageBox.Show("Campul este liber!");
            return;
        }
        //ListBox li = sender as ListBox;

        ListBoxItem li = new ListBoxItem();
        li.Content=textBox1.Text;
        textBox1.Clear();
        listBox1.Items.Add(li);
        textBox1.Focus();


    }
private void button1_Click(object sender, RoutedEventArgs e)
    {
        if (textBox1.Text=="")
        {
            MessageBox.Show("Campul este liber!");
        }else{
        //ListBox li = sender as ListBox;

        ListBoxItem li = new ListBoxItem();
        li.Content=textBox1.Text;
        textBox1.Clear();
        listBox1.Items.Add(li);
        textBox1.Focus();
        }


    }

您的代码有几个问题。

  1. 您只是在检查用户是否没有输入任何内容。如果他进入太空怎么办?为此,请使用String.IsNullorWhiteSpace
  2. 显示消息框后不会返回。为此,您需要在显示消息框后返回

克服这两个问题。更改此

if (textBox1.Text=="")
{
     MessageBox.Show("Campul este liber!");    
}

if (string.IsNullorWhiteSpace(textBox1.Text))
{
      MessageBox.Show("Campul este liber!");
      return;
}