Reputation: 577
I made a post about detecting the paste event in a textbox and was directed to some place with code that does this.. i got it working, but it required that I create my own textbox control from the Program.cs Main event. here is the code:
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);
now the new problem is that when i try toprocess anything in txtNum i receive "Object reference not set to instance of an object" how can I resolve this? it's a winforms application .net 4.0
the error is here:
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);
}
}
Upvotes: 0
Views: 530
Reputation: 103437
OK, that code that declares the textbox in Main is just an example. You should declare the textbox in the form code, as per Jeremy's answer.
Alternatively you should be able to find your MyTextBox
control in the toolbox - just drag it onto the form like any control, and add the Pasted
event handler code like normal.
Upvotes: 0
Reputation: 65534
Its because you have declare the textbox in the scope of the 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);
}
A better approach would be to add the textbox in Form1s constructor or Form_Load
events.
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);
}
Upvotes: 2