对象引用未设置到对象实例”
我正在从数据库和列表框中插入值单击按钮时检索文本。但我收到以下错误
对象引用未设置到实例 对象的
因此“selecteditem.text”不会在所选项目上获得任何值...
String selectemail = "select email_id from [property].[dbo].[user_membership]";
SqlCommand cmd = new SqlCommand(selectemail, con);
cmd.Connection.Open();
ListBox1.DataSource = cmd.ExecuteReader();
ListBox1.DataTextField = "Email_ID";
ListBox1.DataBind();
//on button click//
protected void Button1_Click1(object sender, EventArgs e)
{
ListItem item = new ListItem();
item.Text = ListBox1.SelectedItem.Text;(error comes here)
ListBox2.Items.Add(item.Text);
ListBox1.Items.Remove(item.Text);
...
}
I am inserting values in listbox from database & retrieving text on a button click. but I'm getting the following error
Object reference not set to instance
of object
so "selecteditem.text" does not get any value on item selected...
String selectemail = "select email_id from [property].[dbo].[user_membership]";
SqlCommand cmd = new SqlCommand(selectemail, con);
cmd.Connection.Open();
ListBox1.DataSource = cmd.ExecuteReader();
ListBox1.DataTextField = "Email_ID";
ListBox1.DataBind();
//on button click//
protected void Button1_Click1(object sender, EventArgs e)
{
ListItem item = new ListItem();
item.Text = ListBox1.SelectedItem.Text;(error comes here)
ListBox2.Items.Add(item.Text);
ListBox1.Items.Remove(item.Text);
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将为您阻止错误:
看起来这只是用户没有在
ListBox1
中选择任何内容的问题。编辑
我将一个测试应用程序放在一起进行检查,这对我来说效果很好:
This will stop the error for you:
It looks like it was just a problem of the user not selecting anything in your
ListBox1
.EDIT
I threw a test app together to check, and this works fine for me:
调试代码,但不存在的对象很可能是 ListBox1 控件,或者按下按钮时 ListBox1 控件实际上没有选择项目。
Debug the code, but it's more than likely that the object that doesn't exist will be the ListBox1 control, or the ListBox1 control doesn't actually have an item selected when the button has been pressed.