使用20个字符后修剪文本框文本,如果包含空格则修剪空格

时间:2016-04-25 20:55:21

标签: c# winforms

我有一个带有2个txtbox(LongName和ShortName)和一个Button的WinFormApp。

当在LongName txtbox中输入txt时,我想按下按钮将LongName txtbox中的所有txt缩短为前20个字符输入并删除'中的任何空格。 txtbox然后在ShortName txtbox中显示结果。我正在努力让这个变得正确。我已经尝试了很多方法尝试,但最终似乎无法做到正确。以下是示例代码:

private void btnGetSN_Click(object sender, EventArgs e)
{
    Regex space = new Regex(@" ");
    MatchCollection spacematch = space.Matches(txtLongName.Text);
    if (txtLongName.Text.Length > 20)
    {
        string toTrim = txtLongName.Text;

        toTrim = toTrim.Trim();

        txtShortName.Text = ("'" + toTrim.ToString() + "'");
    }
    if (spacematch.Count > 0)
    {
        txtLongName.Text.Replace(" ", "");
    }
}//closes method

我已经能够将txtbox限制为属性中只有20个字符,但我想设置一个If变量以允许更多自定义。

我是在正确的轨道上吗?

代码中没有错误,但执行按钮时没有任何反应。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:4)

string.Replace()不会更新字符串本身,而是返回一个被修改的新字符串。

private void btnGetSN_Click(object sender, EventArgs e)
{
    // remove space from txtLongName
    txtLongName.Text = txtLongName.Text.Replace(" ", string.Empty);

    // take only the first 20characters from txtLongName
    txtShortName.Text = txtLongName.Text.Substring(0, Math.Min(txtLongName.Text.Length, 20));
}

编辑:以前的代码将从txtLongName中删除空格。如果不是这样,请改用:

private void btnGetSN_Click(object sender, EventArgs e)
{
    // remove space from txtLongName
    var name = txtLongName.Text.Replace(" ", string.Empty);

    // take only the first 20characters from txtLongName
    txtShortName.Text = name.Substring(0, Math.Min(name.Length, 20));
}

答案 1 :(得分:2)

看起来你需要用不同的方式写

private void button1_Click(object sender, EventArgs e)
    {
        var shortName = txtLongName.Text.Trim().Replace(" ", "");

        var maxLength = (shortName.Length > 20) ? 20 : shortName.Length;

        if(txtLongName.Text.Trim().Length > 0)
            txtShortName.Text = shortName.Substring(0, maxLength);
    }
相关问题