Reputation: 7293
I have a lot of textboxes. I have a button that will cut the selected text of the Focused textbox. How do i do that? I have tried this:
if (((TextBox)(pictureBox1.Controls[0])).SelectionLength > 0)
{
((TextBox)(pictureBox1.Controls[0])).Cut();
}
Upvotes: 2
Views: 2634
Reputation: 54562
Try using common Enter
and Leave
events to set the last TextBox that had Focus.
private void textBox_Enter(object sender, EventArgs e)
{
focusedTextBox = null;
}
private void textBox_Leave(object sender, EventArgs e)
{
focusedTextBox = (TextBox)sender;
}
private void button1_Click(object sender, EventArgs e)
{
if (!(focusedTextBox == null))
{
if (focusedTextBox.SelectionLength > 0)
{
Clipboard.SetText(focusedTextBox.SelectedText);
focusedTextBox.SelectedText = "";
focusedTextBox = null;
}
}
}
Upvotes: 1
Reputation: 19608
Hope it is WinForms
var textboxes = (from textbox in this.Controls.OfType<TextBox>()
where textbox.SelectedText != string.Empty
select textbox).FirstOrDefault();
if (textboxes != null)
{
textboxes.Cut();
}
Upvotes: 6
Reputation: 4749
Loop through the controls to find the one with selected text:
foreach (Control x in this.PictureBox1.Controls)
{
if (x is TextBox)
{
if (((TextBox)x).SelectionLength > 0)
{
((TextBox)(x).Cut(); // Or some other method to get the text.
}
}
}
Hope this helps!
Upvotes: 4