When I click on my ListView and write "this text!", I want my Label (or TextBox if that's easier) to change text to "this text!".
How can I do this?
You can use the AfterLabelEdit
event:
private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
yourLabel.Text = e.Label;
}
Don't forget to hook up the event!
If you want to display the new text while typing you can either try to listen to the keyboard between the BeforeLabelEdit and AfterLabelEdit events or you can overlay your own TextBox and use its TextChanged event.
I think this is easier but if you want to do special things, like disallowing editing key etc, it will alway mean some extra work!
Here is a short example how to overlay a TextBox over the Item:
TextBox EditCell = new TextBox();
public Form1()
{
InitializeComponent();
//..
EditCell.TextChanged += EditCell_TextChanged;
EditCell.Leave += EditCell_Leave;
EditCell.KeyDown += EditCell_KeyDown;
}
void EditCell_TextChanged(object sender, EventArgs e)
{
yourLabel.Text = EditCell.Text;
}
void EditCell_Leave(object sender, EventArgs e)
{
ListViewItem lvi = EditCell.Tag as ListViewItem;
if (lvi != null) lvi.Text = EditCell.Text;
EditCell.Hide();
}
void EditCell_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
EditCell_Leave(null, null);
}
else if (e.KeyCode == Keys.Escape)
{
e.Handled = true;
EditCell.Tag = null;
EditCell_Leave(null, null);
}
e.Handled = false;
}
private void listView1_BeforeLabelEdit(object sender, LabelEditEventArgs e)
{
// stop editing the item!
e.CancelEdit = true;
ListViewItem lvi = listView1.Items[e.Item];
EditCell.Parent = listView1;
EditCell.Tag = lvi;
EditCell.Bounds = lvi.Bounds;
EditCell.BackColor = Color.WhiteSmoke; // suit your taste!
EditCell.Text = lvi.Text;
EditCell.Show();
EditCell.SelectionStart = 0;
EditCell.Focus();
EditCell.Multiline = true; // needed to allow enter key
}
The above code works fine but as our chat has established that you actually only want to grab keyboard input and direct it to a Label
, here is the much, much simpler solution to the 'hidden' problem..:
Start by setting your Forms
's KeyPreview
totrue
. Then hook up the KeyPressed
event of the Form
:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (ActiveControl == listView1)
{
e.Handled = true; // needed to prevent an error beep
yourLabel.Text += e.KeyChar.ToString();
}
}
This will not allow any editing and only let the label text grow. You may want to expand with a few extras, like coding for Backspace
, if you like..:
if (e.KeyChar == (char)Keys.Back && yourLabel.Text.Length > 0)
yourLabel.Text = yourLabel.Text.Substring(0, yourLabel.Text.Length - 1);
else yourLabel.Text += e.KeyChar.ToString();