开发者

I am using ListBox to get the text of the selected item, but I am getting an error "Object reference not set to an instance of an object."

开发者 https://www.devze.com 2023-02-19 04:09 出处:网络
protected void Button1_Click1(object sender, EventArgs e) { if (ListBox1.SelectedItem.Text != null)//(error come开发者_JAVA技巧s here)
    protected void Button1_Click1(object sender, EventArgs e)
    {
        if (ListBox1.SelectedItem.Text != null)//(error come开发者_JAVA技巧s here)
        {
            string text = null;
            text = ListBox1.SelectedItem.ToString();
            ListBox2.Items.Add(text);
            ListBox1.Items.Remove(text);


The Error occur when there is no item selected :

Replace with this to verify that SelectedItem is not null:

protected void Button1_Click1(object sender,EventArgs e)
     {
         if (ListBox1.SelectedItem != null && ListBox1.SelectedItem.Text != null)
         {
             string text = null;
             text = ListBox1.SelectedItem.ToString();
             ListBox2.Items.Add(text);
             ListBox1.Items.Remove(text);
0

精彩评论

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