TextBox - 对象引用未设置为对象的实例 [英] TextBox - Object Reference Not Set To An Instance of an Object

查看:26
本文介绍了TextBox - 对象引用未设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段非常简单的代码,它抛出了一个意外错误,我正在努力理解可能是什么错误.

I have a very simple piece of code that is throwing an unexpected error and I am struggling to understand what could possibly be wrong.

private void dataNames_CellDoubleClick(object sender, DataGridViewCellEventArgs e) 
{   
    DataGridViewRow row = dataNames.CurrentCell.OwningRow;
    string val = row.Cells["Name"].Value.ToString();
    txtName.Text = val;
}

对象 dataNames 是一个 DataGridView,其中只有一个名为 Names 的列.

The Object dataNames is a DataGridView with only a single Column in it called Names.

当我从网格中双击一个名称时,我希望它填充文本框 (txtName)

When I double click a Name from the Grid I want it to populate the Textbox (txtName)

我看不到文本框如何生成未设置对象"..' 当我所做的只是向其 Text 属性发布值时出现错误.当我遍历字符串 'val' 时,确实从 DataGridView 中获取了正确的值.

I fail to see how a Textbox can produce an 'Object not set . . ' error when all I am doing is posting a value to its Text property. When I step through the string 'val' does pick up the correct value from the DataGridView.

推荐答案

具有讽刺意味的是,花了很长时间找不到问题,我在发布问题后直接找到了.

Ironically, having spent a good while unable to find the problem, I go and spot it straight after posting the question.

该错误发生在 Form_Load 事件的前面,该事件调用自定义 ClearForm 方法,该方法将表单上的所有文本字段清空.但是我做了以下事情:-

The error is earlier in the Form_Load event, which calls a custom ClearForm method, which blanks all text fields on the form. However I had done the following :-

txtTitle.Text = null;
txtAge.Text = null;
txtName = null;

因此我将文本框本身设置为 null,而不是它的文本属性.

Hence I set the textbox itself = null, rather than its text property.

有时最简单的错别字也会产生最令人费解的错误!

Sometimes the simplest of typos produces the most puzzling of errors!

这篇关于TextBox - 对象引用未设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆