2012-11-16 39 views
0

我发布了一篇关于在文本框中检测粘贴事件的文章,并被引导到了一些代码,这样做的地方..我得到它的工作,但它需要我从程序中创建我自己的文本框控件.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尝试麦克罗公司一直供应什么,我收到“未设置为一个对象的实例对象引用”我怎样才能解决这个问题?这是一个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); 
      } 

    } 
+0

你是什么意思“过程”? –

+0

哪一行导致异常? – Blorgbeard

+0

相关问题:http://stackoverflow.com/questions/13406294/pasting-multi-line-text-in-to-single-line-textbox – Blorgbeard

回答

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构造函数或事件。

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); 

} 
+0

为什么会这样呢? – Blorgbeard

+0

@JeremyThompson然后在哪里?它不会去任何其他地方和工作.. – ace007

+0

工作正常,我所有内部声明'Main' .. – Blorgbeard

0

好吧,在Main中声明文本框的代码仅仅是一个例子。按照Jeremy的回答,您应该在表单代码中声明文本框。

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