文本框对象引用问题

时间:2012-11-16 00:18:53

标签: c# .net

我发了一篇关于在文本框中检测粘贴事件的帖子,并被定向到某个地方,代码执行此操作..我得到它的工作,但它要求我从Program.cs主事件创建我自己的文本框控件。这是代码:

    var txtNum = new MyTextBox();
    txtNum.Pasted += (sender, args) => MessageBox.Show("Pasted: " + args.ClipboardText);
    txtNum.Size = new System.Drawing.Size(578, 20);
    txtNum.Location = new System.Drawing.Point(12, 30);
    var form = new Form1();
    form.Controls.Add(txtNum);
    Application.Run(form);

现在新的问题是,当我尝试在txtNum中进行topprocess时,我会收到“对象引用未设置为对象的实例”,我该如何解决这个问题?这是一个winforms应用程序.net 4.0

错误在这里:

    private void button1_Click(object sender, EventArgs e)
    {
        string s = txtNum.Text; //OBJECT REFERENCE ERROR

            string[] numbers = s.Split(' ');
            double sum = 0;
            for (int i = 0; i < numbers.Length; i++)
            {
                double num = double.Parse(numbers[i]);
                sum += num;
            }
            lblRESULT.Text = sum.ToString();
            if (cp == true)
            {
                Clipboard.SetText(lblRESULT.Text);
            }

    }

2 个答案:

答案 0 :(得分:2)

因为您已在Main()范围内声明了文本框。

static TextBox txtNum = new TextBox();
[STAThread]
static void Main()
{
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
// txtNum.Paste += (sender, args) => MessageBox.Show("Pasted: " + args.ClipboardText);
txtNum.Size = new System.Drawing.Size(578, 20);
txtNum.Location = new System.Drawing.Point(12, 30);
Form1 form = new Form1();
form.Controls.Add(txtNum);
Application.Run(form);
}

更好的方法是在Form1s构造函数或Form_Load事件中添加文本框。

TextBox txtNum = new TextBox();
public Form1()
{
InitializeComponent();
txtNum.Size = new System.Drawing.Size(578, 20);
txtNum.Location = new System.Drawing.Point(12, 30);
txtNum.PreviewKeyDown += (sender, e) =>
{
    if (e.KeyValue == 17 && e.Control == true)
    {
        MessageBox.Show("you pasted:" + Clipboard.GetText());
    }
};
this.Controls.Add(txtNum);

}

答案 1 :(得分:0)

好的,在Main中声明文本框的代码只是一个例子。您应该根据Jeremy的回答在表单代码中声明文本框。

或者,您应该能够在工具箱中找到MyTextBox控件 - 只需将其拖动到窗体上,就像任何控件一样,并像平常一样添加Pasted事件处理程序代码。