Oedum Oedum - 3 months ago 26
ASP.NET (C#) Question

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??

Answer
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.