您好,登錄后才能下訂單哦!
當(dāng)用戶選擇不同的項(xiàng)時(shí),ListBox 控件會(huì)觸發(fā) SelectedIndexChanged 事件。可以在這個(gè)事件處理程序中獲取用戶選擇的項(xiàng),并進(jìn)行相應(yīng)的操作。
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
MessageBox.Show("You selected: " + listBox1.SelectedItem.ToString());
}
}
如果希望用戶雙擊某一項(xiàng)時(shí)觸發(fā)事件,可以使用 MouseDoubleClick 事件。
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
int index = listBox1.IndexFromPoint(e.Location);
if (index != ListBox.NoMatches)
{
MessageBox.Show("You double-clicked: " + listBox1.Items[index].ToString());
}
}
如果想讓用戶可以拖拽 ListBox 中的項(xiàng),可以使用 DragDrop 事件和 DragEnter 事件。
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
if (listBox1.SelectedItem != null)
{
listBox1.DoDragDrop(listBox1.SelectedItem, DragDropEffects.Move);
}
}
private void listBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text) && e.AllowedEffect == DragDropEffects.Move)
{
e.Effect = DragDropEffects.Move;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void listBox1_DragDrop(object sender, DragEventArgs e)
{
int index = listBox1.IndexFromPoint(listBox1.PointToClient(new Point(e.X, e.Y)));
if (index != ListBox.NoMatches)
{
object data = e.Data.GetData(DataFormats.Text);
listBox1.Items.Remove(data);
listBox1.Items.Insert(index, data);
}
}
這些是處理 ListBox 控件事件的一些常見技巧,可以根據(jù)實(shí)際需求進(jìn)行相應(yīng)的調(diào)整和擴(kuò)展。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。