简体   繁体   中英

Object reference not set to instance of object"

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

This will stop the error for you:

//on button click//       
protected void Button1_Click1(object sender, EventArgs e)
{
        if (ListBox1.SelectedItem == null) return;

        ListItem item = new ListItem();
        item.Text = ListBox1.SelectedItem.Text;(error comes here)
        ListBox2.Items.Add(item.Text);
        ListBox1.Items.Remove(item.Text);
}

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:

    var dt = New DataTable()
    dt.Columns.Add("email_id");

    dt.Rows.Add("first");
    dt.Rows.Add("second");
    dt.Rows.Add("thrid");
    dt.Rows.Add("fourth");

    var lst = New System.Web.UI.WebControls.ListBox;

    lst.DataSource = dt;
    lst.DataTextField = "Email_ID";
    lst.DataBind();

    //lst.SelectedItem is null here
    lst.SelectedIndex = 1;

    //lst.SelectedItem is NOT null here

调试代码,但很可能不存在的对象将是ListBox1控件,或者ListBox1控件在按下按钮时实际上没有选择项目。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM