0

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

Bheeshamteche
  • 47
  • 4
  • 9

4 Answers4

1

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);
Kurubaran
  • 8,696
  • 5
  • 43
  • 65
0

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);
  • how i can find new entry of item in list box – Bheeshamteche Oct 29 '14 at 08:27
  • Well if it comes from DB, then the newest entry is always the one with biggest index in a table. How do you get the entries from DB? Entity or something similar? – Boris Bucek Oct 29 '14 at 08:36
  • SqlCommand sqlcmd = new SqlCommand("USP_BT_Select_items", con); // stored procedure for loading items sqlcmd.CommandType = CommandType.StoredProcedure; da.SelectCommand = sqlcmd; da.Fill(dt); listBox1.DataSource = dt; listBox1.DisplayMember = "item"; listBox1.ValueMember = "item"; – Bheeshamteche Oct 29 '14 at 09:38
  • Did you write the stored procedure yourself? You might consider changing it to something that returns your primary key + value instead of value only. OR you might change it so it orders all values by primary key. Then you will know that last value on the list is newest entry. If you didnt create the stored procedure yourself or dont even know what it is, consider doing some tutorials. Edit: if all your stored procedure does is only selecting items from one table and you are not sorting them in any way, first value from the bottom is always newest – Boris Bucek Oct 29 '14 at 09:48
0

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;
Saravana
  • 33
  • 1
  • 2
  • 8
0

The Add() method return the index of rencently element added.

listBox1.SelectedIndex = listBox1.Items.Add(77);