Monday, November 2, 2009

Editable ListBox User Control

using System;

using System.Collections.Generic;

using System.Text;

using System.Windows.Forms;

using System.Drawing;

using System.Data;

namespace ExByTejas

{

public class EditableListBox : ListBox

{

TextBox editBox = new TextBox();

public EditableListBox()

{

editBox.Location = new System.Drawing.Point(0, 0);

editBox.Size = new System.Drawing.Size(0, 0);

editBox.Hide();

this.Controls.AddRange(new Control[] {this.editBox});

editBox.Text = "";

editBox.BackColor = Color.Beige;

editBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.EditOver);

editBox.LostFocus += new System.EventHandler(this.FocusOver);

}

protected override void OnKeyPress(KeyPressEventArgs e)

{

if (e.KeyChar == 13)

CreateEditBox();

base.OnKeyPress(e);

}

protected override void OnDoubleClick(EventArgs e)

{

CreateEditBox();

base.OnDoubleClick(e);

}

protected override void OnKeyDown(KeyEventArgs e)

{

if (e.KeyData == Keys.F2)

CreateEditBox();

base.OnKeyDown(e);

}

protected void CreateEditBox()

{

Rectangle r = this.GetItemRectangle(this.SelectedIndex);

string itemText = string.Empty;

if(this.DataSource == null)

itemText = (string)this.Items[SelectedIndex];

else

itemText = this.Text;

editBox.Location = new System.Drawing.Point(r.X, r.Y);

editBox.Size = new System.Drawing.Size(r.Width - 10, r.Height);

editBox.Show();

this.Controls.AddRange(new System.Windows.Forms.Control[] {this.editBox});

editBox.Text = itemText;

editBox.Focus();

editBox.SelectAll();

editBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.EditOver);

editBox.LostFocus += new System.EventHandler(this.FocusOver);

}

protected void FocusOver(object sender, System.EventArgs e)

{

UpdateEditedValue();

}

protected void EditOver(object sender, System.Windows.Forms.KeyPressEventArgs e)

{

if (e.KeyChar == 13)

UpdateEditedValue();

}

private void UpdateEditedValue()

{

if (this.DataSource == null)

{

this.Items[SelectedIndex] = editBox.Text;

editBox.Hide();

}

else

{

DataRowView rowView = (DataRowView)this.SelectedItem;

rowView.Row[this.DisplayMember] = editBox.Text;

editBox.Hide();

}

}

}

}

No comments:

Post a Comment