Hey there.

i have a listbox thats databound. Now i want to select in that massive list, lets say a sting "dog", i want it to hightligh that word in there. But i cant seem to get it to work with this databound listbox.

Coz i know how to do it if it wasnt databound.

its this

txtCity.Text = listBox1.SelectedItem.ToString();

but this code doesnt seem to work on a databound listbox...

What can i do to fix this??:?:

Thank you.

Recommended Answers

All 3 Replies

This should do it:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string[] array ={"A", "B", "C", "D", "E"};
            listBox1.DataSource = array;
            listBox1.SelectedIndex = -1;
            listBox1.SelectedIndexChanged+=new EventHandler(listBox1_SelectedIndexChanged);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //1. automatic selection - insert the number of the index into textBox
            try
            {
                listBox1.SelectedIndex = int.Parse(textBox1.Text);
            }
            catch { }
            
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //2. when you select a row in the listBox, the value get written into textBox:
            textBox2.Text = listBox1.GetItemText(listBox1.SelectedItem);
        }
    }
commented: Easy and Simple. +1

This should do it:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string[] array ={"A", "B", "C", "D", "E"};
            listBox1.DataSource = array;
            listBox1.SelectedIndex = -1;
            listBox1.SelectedIndexChanged+=new EventHandler(listBox1_SelectedIndexChanged);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //1. automatic selection - insert the number of the index into textBox
            try
            {
                listBox1.SelectedIndex = int.Parse(textBox1.Text);
            }
            catch { }
            
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //2. when you select a row in the listBox, the value get written into textBox:
            textBox2.Text = listBox1.GetItemText(listBox1.SelectedItem);
        }
    }

This worked great.. =) Thank you Mitja.
You always help out in a time of need =)

hehe, no problem I like to help you guys. I know how its being on the beginning.
cheers,
Mitja

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.