A ListBox is a read-only list of items. But let us suppose your application needs to edit an item in a listbox at runtime. This example will demonstrate a simple approach to create an editable listbox, i. e., to change ListBox items on the fly.
To edit an item in a listbox, all you need is a simple editbox.that overlays on a listbox item. The idea is to create a TextBox control and keep it hidden and show it whenever required.
private System.Windows.Forms.TextBox editBox ;
private void Form1_Load(object sender, System.EventArgs e)
{
editBox = new System.Windows.Forms.TextBox();
editBox.Location = new System.Drawing.Point(0,0);
editBox.Size = new System.Drawing.Size(0,0);
editBox.Hide();
listBox1.Controls.AddRang
e(new System.Windows.Forms.Control[] {this.editBox});
editBox.Text = "";
editBox.BackColor = Color.Beige;
editBox.Font = new Font("Varanda" , 15 , FontStyle.Regular
| FontStyle.Underline ,GraphicsUnit.Pixel);
editBox.ForeColor = Color.Blue;
editBox.BorderStyle = BorderStyle.FixedSingle;
Two events are added to the EditBox.
KeyPress event to check if the enter key is pressed when the user has finished editing the item.
LostFocus event in case the user edits the item and instead of using the enter key to indicate the end of editing, the user clicks some other item in the list box.
editBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.EditOver);
editBox.LostFocus += new System.EventHandler(this.FocusOver);
When the user hits the enter key or double clicks the mouse on any item in the list or clicks the F2 key, we display our editbox control and overlay the control on the item selected in the list.
private void listBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ( e.KeyChar == 13 )
CreateEditBox(sender);
}
private void listBox1_DoubleClick(object sender, System.EventArgs e)
{
CreateEditBox(sender);
}
private void listBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if ( e.KeyData == Keys.F2 )
CreateEditBox(sender);
}