1

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);
   ...
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user123
  • 21
  • 1
  • 7

2 Answers2

3

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
Pondidum
  • 11,457
  • 8
  • 50
  • 69
1

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.

Chris Dixon
  • 9,147
  • 5
  • 36
  • 68
  • 1
    When you debug, which is the item that returns null? Place a debug marker and run through your code - is it the ListBox1.SelectedItem? – Chris Dixon Mar 21 '11 at 12:01
  • item.Text = ListBox1.SelectedItem.Text; – user123 Mar 21 '11 at 12:02
  • ListBox1.SelectedItem.Text is not getting if data is inserted from database. but getting value if insertyed manually... – user123 Mar 21 '11 at 12:14
  • Your data binding, is it being performed on every postback? Do you have (!IsPostBack) in your code? If so, remove it and try again - make sure the data is always being bound on postback too. – Chris Dixon Mar 21 '11 at 12:27