Nisar Afridi Nisar Afridi - 1 year ago 155
C# Question

Drag & Drop Label Text into TextBox using C#

I want to add text into textbox whenever label is drag and dropped inside textbox, so far i accomplished it using below methods. Consider i have already some text in textbox, now when i drop the label it adds the text to end, i understand it's because of i am adding textbox=textbox+labelcontents.

Is there any other way, to add text to that same location where it is being dropped, and all previous text remain same. Can we use location points?

In the form default Constructor:

lblBreakStartTime.MouseDown += new MouseEventHandler(lblBreakStartTime_MouseDown);
txtBoxDefaultEnglish.AllowDrop = true;
txtBoxDefaultEnglish.DragEnter += new DragEventHandler(txtBoxDefaultEnglish_DragEnter);
txtBoxDefaultEnglish.DragDrop += new DragEventHandler(txtBoxDefaultEnglish_DragDrop);

Mouse Down Event for label which will be dropped:

private void lblBreakStartTime_MouseDown(object sender, MouseEventArgs e)
DoDragDrop("START_TIME", DragDropEffects.Copy);

Textbox events:

private void txtBoxDefaultEnglish_DragEnter(object sender, DragEventArgs e)
if (e.Data.GetDataPresent(DataFormats.Text)) e.Effect = DragDropEffects.Copy;
private void txtBoxDefaultEnglish_DragDrop(object sender, DragEventArgs e)

txtBoxDefaultEnglish.Text = txtBoxDefaultEnglish.Text + " " + "[" + (string)e.Data.GetData(DataFormats.Text) + "]";
txtBoxDefaultEnglish.SelectionStart = txtBoxDefaultEnglish.Text.Length;

Answer Source

Try this:

private void txtBoxDefaultEnglish_DragDrop(object sender, DragEventArgs e)
    //Get index from dropped location
    int selectionIndex = txtBoxDefaultEnglish.GetCharIndexFromPosition(txtBoxDefaultEnglish.PointToClient(new Point(e.X, e.Y)));
    string textToInsert = string.Format(" [{0}]", (string)e.Data.GetData(DataFormats.Text));
    txtBoxDefaultEnglish.Text = txtBoxDefaultEnglish.Text.Insert(selectionIndex, textToInsert);
    txtBoxDefaultEnglish.SelectionStart = txtBoxDefaultEnglish.Text.Length;

    //Set cursor start position
    txtBoxDefaultEnglish.SelectionStart = selectionIndex;
    //Set selction length to zero
    txtBoxDefaultEnglish.SelectionLength = 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download