【问题标题】:Drag & Drop Label Text into TextBox using C#使用 C# 将标签文本拖放到 TextBox 中
【发布时间】:2016-10-27 06:30:50
【问题描述】:

每当标签被拖放到文本框中时,我想将文本添加到文本框中,到目前为止,我使用以下方法完成了它。考虑到我在文本框中已经有一些文本,现在当我放下标签时,它会将文本添加到结尾,我明白这是因为我正在添加 textbox=textbox+labelcontents。

有没有其他方法可以将文本添加到放置它的同一位置,并且所有以前的文本都保持不变。我们可以使用位置点吗?

在表单默认构造函数中:

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

将被删除的标签的鼠标按下事件:

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

文本框事件:

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;
    }

【问题讨论】:

  • 刚刚找到解决方案,非常简单,我只需要使用光标位置。 int CursorPos = txtBoxDefaultEnglish.SelectionStart;txtBoxDefaultEnglish.Text=txtBoxDefaultEnglish.Text.Insert(CursorPos, "[" + (string)e.Data.GetData(DataFormats.Text) + "]");
  • 请将此作为答案发布并接受。也许对其他人有帮助;)
  • @Nisar,您可以在光标位置插入文本,但不能在放置位置插入文本

标签: c# events textbox drag-and-drop label


【解决方案1】:

试试这个:

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;
}

【讨论】:

  • 这是一个很好的解决方案,一件小事,如果我们在文本之间放置标签,它会将光标移动到文本框的末尾。我们如何在插入后将光标保持在位置而不将其移动到整行的末尾。我希望你明白我的意思。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多