簡體   English   中英

如何在列表框中選擇最新項目

[英]how to select latest item in the listbox

我正在使用Winform和C#,我正在列表框中添加項目

5<-----focus on first element
8
9
99
100

默認焦點放在第一個元素上(例如5)。 但是我正在嘗試這樣,如果我在列表框中添加新元素,例如77,那么重點將放在77

 5
    8
    9
    77 <---here i m trying the focus
    99
    100

我嘗試了這個,但這不起作用

   listBox1.SelectedIndex = listBox1.Items.Count - 1;
     listBox1.Focus();

謝謝

只要將新項目添加到列表框中,就可以設置焦點,如下所示:

listBox1.Items.Add(77);
listBox1.SetSelected(listBox1.Items.IndexOf(77), true);

我無法找到任何將最新添加的項目添加到ListBox的方法。 但是,您可以將最后添加的項目保存在某個變量中,然后遍歷整個listBox並搜索具有相同值的項目(僅當該值唯一時才可以正常工作)。 像這樣

listBox1.SelectedIndex = listBox1.Items.IndexOf(yourNumber);

首先使用select MAX(col.name)從數據庫中找到最后插入的值,或者選擇top 1 col.name(如果使用的是SQL Server),然后將其存儲在字符串,標簽或其他名稱中,然后使用“ listBox1.Items.FindByText()“將焦點設置在它上...

string x;
sqlconnection con="...........";
con.open();
sqlcommand cmd = new sqlcommand("select top 1 (your columnname) from yourtable",con);
x = cmd.ExecuteScalar().ToString();
con.Close();

現在您得到了最后插入的項目,然后

if (listBox1.Items.FindByText(x)!= null)
    listBox1.Items.FindByText(x).Selected = true;

Add()方法返回添加的rencently元素的索引。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM