首页 > 解决方案 > 将行从 datagridview 拖放到 TextBox

问题描述

不传输文本。该代码不是我的,它最初与listBox.
我可以移动单个单元格,但我需要在这里移动一行。DataGridview在表单中选择数据源。

public Form1()
{
    InitializeComponent();
    textBox1.AllowDrop = true;
    dataGridView1.AllowDrop = true;
}

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
    dataGridView1.DoDragDrop(dataGridView1.SelectedRows, DragDropEffects.Move);
}


private void textBox1_DragEnter(object sender, DragEventArgs e){
    if (e.Data.GetDataPresent(typeof(DataGridViewSelectedRowCollection)))
    {
        e.Effect = DragDropEffects.Move;
    }
}


private void textBox1_DragDrop(object sender, DragEventArgs e)
{
    DataGridViewSelectedRowCollection rows = (DataGridViewSelectedRowCollection)e.Data.GetData(typeof(DataGridViewSelectedRowCollection));

    foreach (DataGridViewRow row in rows)
    {
        textBox1.Text = row.Cell[1].Value.ToString();
    }
}

标签: c#

解决方案


尝试添加和修改代码textBox1_DragDrop如下。

foreach (DataGridViewRow row in rows)
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        textBox1.Text += cell.Value.ToString() + " ";
    }
}

测试结果,

在此处输入图像描述

更新

private void textBox1_DragDrop(object sender, DragEventArgs e)
{
    foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
    {
        for (int i = 0; i < dataGridView1.Columns.Count; i++)
        {
            textBox1.Text += dataGridView1.Rows[cell.RowIndex].Cells[i].Value.ToString() + " ";
        }
    }
}

推荐阅读