简体   繁体   中英

How to Copy and Paste from One TextBox to another TextBox on the Same Windows Form

I am trying to copy values from one textbox to another textbox when user clicks a button. It seems to be a simple solution but for some reason when I click the coppyButton1 on the form, the value from uid1 (TextBox1) not getting copied into uid2(TextBox2). Hoping for feedback.

Code:

private void copyButton1_Click(object sender, EventArgs e)
{
     uid2.Text = uid1.Text;
}

You can associate data to the clipboard incredibly easy:

Clipboard.SetText(txtCopyText.Text);

That would take the value of the textbox, then store to the clipboard.

protected void btnCopy_Click(object sender, EventArgs e)
{
     // You would want to validate the contents of the textbox before copying.

     if(!string.IsNullOrEmpty(txtCopy.Text))
          Clipboard.SetText(txtCopy.Text);          
}

If you simply want to force the value from one field to another, then the code you have above would force the value to be set. But to apply to the clipboard for copy and paste, you would do the above.

The only reason that code might not work would be if you don't have the textbox instantiated, or those fields are on another form that deviates from your btnCopy . Or you tabbed and allowed intellisense to reverse your copied data, ie one vs two. Your code:

ui2.Text = ui1.Text;

Is the field you thought you were copying from ui1.Text ?


Update

To get data from the clipboard, you would do the following:

if(Clipboard.ContainsText(TextDataFormat.Text))
     txtPaste.Text = Clipboard.GetText(TextDataFormat.Text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM