开发者

Object reference not set to instance of object"

开发者 https://www.devze.com 2023-02-18 21:26 出处:网络
I am inserting values in listbox from database & retrieving text on a button click. but I\'m getting the following error

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(selec开发者_StackOverflowtemail, 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消