Hunter Mitchell
Hunter Mitchell

Reputation: 7293

Cut, Copy, and paste in C#?

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

Answers (3)

Mark Hall
Mark Hall

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

Anuraj
Anuraj

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

matthewr
matthewr

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

Related Questions