【问题标题】:How to copy only numbers from masked textbox to a label?如何仅将数字从蒙面文本框中复制到标签?
【发布时间】:2014-09-03 16:49:25
【问题描述】:

我制作了一个带掩码的文本框来保存带有掩码 (999) 000-0000 的数字,我只想在标签中显示数字,但是当我这样做时,它也会复制括号和行。
我知道它会复制所有文本。我如何只能复制不带掩码输入的数字? (窗口形式)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = maskedTextBox1.Text;
        }
    }
}

【问题讨论】:

    标签: c# winforms maskedtextbox


    【解决方案1】:

    一种解决方案是在读取其值之前将TextMaskFormat 设置为ExcludePromptAndLiterals

    maskedTextBox1.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
    Console.WriteLine(maskedTextBox1.Text); 
    //will print 3123 when value in the mask textbox is (31) 23 for mask (00) 00
    

    并且在设置完这个格式后:

    maskedTextBox1.TextMaskFormat = MaskFormat.IncludeLiterals;
    

    即使您不将格式设置回IncludeLiterals,UI 控件仍会显示屏蔽文本(31) 23,并且会照常工作。如果您的其他逻辑依赖于掩码的 Text 字段,则会执行此操作。

    因此,如果您没有此类依赖项,则可以在 Visual Studio 设计器的属性窗口中为 maskedTextBox1 设置此值

    【讨论】:

    • tnx,但是为什么要写 Console.WriteLine() 而它应该是 label1.Text = maskedTextBox1.Text; ?
    • 没关系。 maskedTextBox1.Text 返回 string,因此如果您将其分配给标签,您的标签将显示原始数字。自己试试。我只是想展示我是如何得到这个数字并在没有表单或调试的情况下阅读它
    猜你喜欢
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多