textbox1.text = 123 ;
textbox2.text = examples ;
我在listbox1
在listbox = 123 examples
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));
DataGridView.HitTestInfo hti = dataGridView1.HitTest(clientPoint.X, clientPoint.Y);
DataGridViewCell targetCell = dataGridView1[hti.ColumnIndex, hti.RowIndex];
if (targetCell.Value == null)
{
targetCell.Value = e.Data.GetData(DataFormats.Text);
}
else
{
if (targetCell.Value.ToString().Contains(e.Data.GetData(DataFormats.Text).ToString().Split(' ')[1]))
{
}
else
{
targetCell.Value = targetCell.Value.ToString().Split(' ')[1] + System.Environment.NewLine + e.Data.GetData(DataFormats.Text);
}
}
textBox3.Text = e.Data.GetData("System.String").ToString().Split()[0];
}
现在,如果我从我的列表框项目(123个示例)拖放到我的datagridview任何单元格,它应该被拆分,如textbox3.text = 123;和datagridview单元格的例子。
上面的代码使用但是它的分裂却没有解决。
视觉示例:
答案 0 :(得分:0)
问题是,你的逻辑错了。
只需替换此代码段
即可if (targetCell.Value == null)
{
targetCell.Value = e.Data.GetData(DataFormats.Text);
}
else
{
if (targetCell.Value.ToString().Contains(e.Data.GetData(DataFormats.Text).ToString().Split(' ')[1]))
{
}
else
{
targetCell.Value = targetCell.Value.ToString().Split(' ')[1] + System.Environment.NewLine + e.Data.GetData(DataFormats.Text);
}
}
这一行:
targetCell.Value = e.Data.GetData(DataFormats.Text).ToString().Split(' ')[1];
动态选择“TextBoxes:”
创建一个 TextBoxes 的全局数组,并在表单的构造函数中初始化它:
TextBox[] arrTextBox;
public Form1()
{
InitializeComponent();
//initializing the array
arrTextBox = new TextBox[] { textBox1, textBox2, textBox3, textBox4 };
}
现在使用它:
//get RowIndex of selected Cell and get the same index TextBox from the array
arrTextBox[targetCell.RowIndex].Text = e.Data.GetData("System.String").ToString().Split()[0];
完整代码:
TextBox[] arrTextBox;
public Form1()
{
InitializeComponent();
//initializing the array
arrTextBox = new TextBox[] { textBox1, textBox2, textBox3, textBox4 };
}
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));
DataGridView.HitTestInfo hti = dataGridView1.HitTest(clientPoint.X, clientPoint.Y);
DataGridViewCell targetCell = dataGridView1[hti.ColumnIndex, hti.RowIndex];
targetCell.Value = e.Data.GetData(DataFormats.Text).ToString().Split(' ')[1]; //for GridCell
arrTextBox[targetCell.RowIndex].Text = e.Data.GetData("System.String").ToString().Split()[0]; //for TextBox
}