簡體   English   中英

如何添加連字符“-”以將文本框中每個輸入或單擊的值與C#中的許多按鈕分開?

[英]How to add a hyphen “-” to separate each entered or clicked value in Textbox from many buttons in C#?

我是C#(WinForms)的初學者,現在遇到一個問題,如何添加“-”來分隔從不同按鈕單擊或輸入的每個值。

例:

btn1 = "01", btn2 = "02", btn3="03", btn4 = "04"

如果單擊第一個按鈕,則將01插入到TextBox中,如果也單擊第二個按鈕,則再次將02插入到文本框中,但TextBox格式應為01-02,依此類推。

如何在C#中處理此語句?

編輯:這是我嘗試過的代碼:

private void txtFixedTypeTwo_TextChanged(object sender, EventArgs e)
    {
        string sVal = txtFixedTypeTwo.Text;
        if (!string.IsNullOrEmpty(sVal))
        {
            if(txtFixedTypeTwo.Text.Length <= 11)
            {
                var cVal = sVal.Substring(sVal.Length - 2);
                string nVal = sVal + "-" + cVal;
                txtFixedTypeTwo.Text = nVal;
                txtFixedTypeTwo.SelectionStart = txtFixedTypeTwo.Text.Length;
                txtFixedTypeTwo.Focus();
            }

        }
    }

我喜歡這樣的Button click事件:

private void btn01_Click(object sender, EventArgs e)
    {
        if (focusedTextbox != null)
        {
            // put something in textbox
           focusedTextbox.Text += "01";
        }

    }

您可以這樣進行:

        Action<string> append = t =>
            textBox.Text +=
                (textBox.Text.Length > 0 ? "-" : "") + t;

        btn1.Click += (s, _) => append("01");
        btn2.Click += (s, _) => append("02");
        btn3.Click += (s, _) => append("03");
        btn4.Click += (s, _) => append("04");

只需將此代碼添加到Form1_Load方法中

嘗試這個:

if(textBox1.Text.Length >= 2)
{
    textBox1.Text += "-00"
}
else
{
    textBox1.Text += "00"
}

TextBox的長度大於等於2時,它將添加“-”。

第一單擊00第二單擊00-00第三單擊00-00-00

為防止重復,您需要創建方法。

void TextBoxValue(object sender, TextBox textBox, string value)
{
    if(textBox.Text.Length >= 2)
    {
        textBox.Text += String.Format("-{0}", value)
    }
    else
    {
        textBox.Text += value;
    }
}
public void Button1_Click(object sender, EventArgs e)
{
    if(textBox.Text.Length > 0)
         textBox.Text += "-";

    Button butt = (Button)sender;

    textBox.Text += butt.Text;
}

據我了解,您有Button.Text = 01,02,依此類推。 您需要為所有按鈕添加此事件單擊。

Button butt = (Button)sender;

在此行中,您正在單擊的按鈕。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM