This example shows how to use buttons to slide a ListBox's selection up or down in C# .NET.
Keywords: ListBox, select, selection, SelectedItem, SelectedIndex, SetSelected, C#.NET,Csharp.NET
To slide the selection up, see if the SelectedIndex property is greater than 0. If it is, subtract 1 from it.
To slide the selection down, see if the SelectedIndex property is less than the second largest item index. If it is, add 1 to it.
Here the complete Code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace testc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender,
EventArgs e)
{
}
private void button1_Click(object sender,
EventArgs e)
{
if (listBox1 .SelectedIndex > 0)
listBox1.SelectedIndex -= 1;
}
private void button2_Click(object sender,
EventArgs e)
{
if (listBox1.SelectedIndex < listBox1.Items.Count - 1)
listBox1.SelectedIndex += 1;
}
}
}
No comments:
Post a Comment