user1986144 user1986144 - 2 months ago 9
ASP.NET (C#) Question

listbox selected item in a textbox

I have two listboxes, two text boxes and buttons. When I press the buttons the items of list box 1 is moved to list box2 but i want to display the selected items in the textfields so how do i do it??

txtbox.Text = listbox3.selecteditem.value;


is not working, i also tried

txtbox.Text = listbox3.selecteditem.tostring();


this is my piece of code. 'm a fresher and new to asp .net

if (RadioButton1.Checked == true)
{
a = ListBox3.SelectedValue.ToString();
b = ListBox3.SelectedIndex;
ListBox4.Items.Add(a);
ListBox3.Items.RemoveAt(ListBox3.Items.IndexOf((ListBox3.SelectedItem)));

TextBox1.Text = RadioButton1.Text.ToString();
TextBox2.Text = ListBox3.SelectedItem.Value;
}

Answer
if (RadioButton1.Checked == true)
{    
            var a = ListBox3.SelectedValue.ToString();
            var b = ListBox3.SelectedIndex;

            ListBox4.Items.Add(a);
            ListBox3.Items.RemoveAt(b);

            TextBox1.Text = RadioButton1.Text.ToString();
            TextBox2.Text = a;
}

addtionally, i would suggest you to check the SelectedIndex value, if none item is selected in the ListBox, the SelectedIndex will be -1

Better version of your code

if (RadioButton1.Checked == true)
{    


    var b = ListBox3.SelectedIndex;
    var a = ListBox3.SelectedValue.ToString();

    if (b < 0)
    {
        // no ListBox item selected;
        return;
    }

    ListBox4.Items.Add(a);
    ListBox3.Items.RemoveAt(b);

    TextBox1.Text = RadioButton1.Text.ToString();
    TextBox2.Text = a;
}
Comments