Reputation: 47
i am using winform and C#,i am adding items in the list box
5<-----focus on first element
8
9
99
100
Default focus coming on first element(like 5). But I am trying like that if i am adding new element in the list box like 77 then focus will be on 77
5
8
9
77 <---here i m trying the focus
99
100
i tried this but this is not working
listBox1.SelectedIndex = listBox1.Items.Count - 1;
listBox1.Focus();
thanks
Upvotes: 0
Views: 5115
Reputation: 68
The Add() method return the index of rencently element added.
listBox1.SelectedIndex = listBox1.Items.Add(77);
Upvotes: 0
Reputation: 33
First find the last inserted value from database by using select MAX(col.name) or select top 1 col.name (if you are using SQL Server), and store it in a string,or a label or something else, then use "listBox1.Items.FindByText()" to set focus on it...
string x;
sqlconnection con="...........";
con.open();
sqlcommand cmd = new sqlcommand("select top 1 (your columnname) from yourtable",con);
x = cmd.ExecuteScalar().ToString();
con.Close();
now you got the last inserted item,then
if (listBox1.Items.FindByText(x)!= null)
listBox1.Items.FindByText(x).Selected = true;
Upvotes: 0
Reputation: 8902
You could set the focus whenever you add a new item to the listbox as follows,
listBox1.Items.Add(77);
listBox1.SetSelected(listBox1.Items.IndexOf(77), true);
Upvotes: 1
Reputation: 76
I failed to found any method for latest added item to ListBox. You can however save the last added item in some variable and then go through whole listBox and search for item with the same value (will work properly only if the value is unique). Something like this
listBox1.SelectedIndex = listBox1.Items.IndexOf(yourNumber);
Upvotes: 0