Oedum
Oedum

Reputation: 816

Focus on last entry in listbox

I am making a chat function on my site. When somebody enter any text to it, I want it to show all messeges from when ever he entered the chat until now. It works fine and all...

var query = from es in gr.chats
                            where es.timestamps > date
                            orderby es.timestamps ascending
                            select es;

                List<chat> list = new List<chat>();
                foreach (chat chat1 in query)
                {
                    list.Add(chat1);
                }

                for (int i = 0; i < list.Count; i++)
                {
                    lbChat.Items.Add("[" + list[i].timestamps + "] " + list[i].personID.ToString() + ": " + list[i].besked);
                }

BUT

I want the focus in my listbox to be on my newest entry... I want to move my listbox focus to the bottom of the listbox all the time.

Anybody got any ideas on how to focus on the last entry in a listbox??

Upvotes: 4

Views: 38348

Answers (3)

Christo Carstens
Christo Carstens

Reputation: 863

When your ListBox's SelectionMode is set to MultiSimple or MultiExtended you have to do a bit of extra work:

listbox.Items.Add( message );

// this won't work as it will select all the items in your listbox as you add them
//listbox.SelectedIndex = listbox.Items.Count - 1;

// Deselect the previous "last" line    
if ( listbox.Items.Count > 1 )
    listbox.SetSelected( listbox.Items.Count - 2, false );
// Select the current last line
listbox.SetSelected( listbox.Items.Count - 1, true );
// Make sure the last line is visible on the screen, this will scroll
// the window as you add items to it
listbox.TopIndex = listbox.Items.Count - 1;

Upvotes: 1

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17380

this.ListBox1.Items.Add(new ListItem("Hello", "1"));
this.ListBox1.SelectedIndex = this.ListBox1.Items.Count - 1;

The first line simply adds an item. The second one sets its SelectedIndex which determines which item in the ListBox item's list should be selected.

Upvotes: 13

James Hill
James Hill

Reputation: 61812

Use SetSelected()

//This selects and highlights the last line
[YourListBox].SetSelected([YourListBox].Items.Count - 1, true);

//This deselects the last line
[YourListBox].SetSelected([YourListBox].Items.Count - 1, false);

Additional Information (MSDN):

You can use this property to set the selection of items in a multiple-selection ListBox. To select an item in a single-selection ListBox, use the SelectedIndex property.

Upvotes: 8

Related Questions