1
我已經編寫了此例程以將TreeView
節點值拖放到DataGridView
單元格上。將TreeView節點拖到DataGridView單元格問題
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
#region Find Row and Cell from Mouse Position
Point grvScreenLocation = dataGridView1.PointToScreen(dataGridView1.Location);
int tempX = DataGridView.MousePosition.X - grvScreenLocation.X + dataGridView1.Left;
int tempY = DataGridView.MousePosition.Y - grvScreenLocation.Y + dataGridView1.Top;
DataGridView.HitTestInfo hit = dataGridView1.HitTest(tempX, tempY);
int cellX = hit.RowIndex;
int cellY = hit.ColumnIndex;
#endregion
string droppedString = e.Data.GetData(typeof(string)) as string;
DataGridViewRow selectedRow = dataGridView1.Rows[cellX];
DataGridViewCell selectedCell = dataGridView1.Rows[cellX].Cells[cellY];
if (!selectedRow.IsNewRow)
{
selectedCell.Value = droppedString;
selectedCell.Tag = droppedString;
selectedCell.OwningRow.Cells[3].Value = colMappingType.Items[0];
}
else
{
dataGridView1.Rows.Add();
dataGridView1.Rows[dataGridView1.Rows.Count-2].Cells[cellY].Value = droppedString;
dataGridView1.Rows[dataGridView1.Rows.Count-2].Cells[cellY].Tag = droppedString;
dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells[3].Value = colMappingType.Items[1];
}
}
}
而且我寫這個程序來測試是否實際上已被填充細胞:
private void button1_Click(object sender, EventArgs e)
{
DataTable dataTable = new DataTable();
dataTable.TableName = "Test";
dataTable.Columns.Add("ColOne", typeof(bool));
dataTable.Columns.Add("ColTwo", typeof(string));
dataTable.Columns.Add("ColThr", typeof(string));
dataTable.Columns.Add("ColFor");
foreach (DataGridViewRow dgvRow in dataGridView1.Rows)
{
DataRow dataRow = dataTable.NewRow();
int i=0;
foreach (DataGridViewCell dgvCell in dgvRow.Cells)
{
dataRow.ItemArray.SetValue(dgvCell.Value, i);
++i;
}
dataTable.Rows.Add(dataRow);
}
Form2 f = new Form2();
f.DataGridView.DataSource = dataTable;
f.Show();
}
}
測試代碼顯示在Form2
新DataGridView
有行數和列數正確。但不包含任何數據。
究竟發生了什麼?
如何解決這個問題?
編輯:
這段代碼解決了這個問題。
private void button1_Click(object sender, EventArgs e)
{
DataTable dataTable = new DataTable();
dataTable.TableName = "Test";
dataTable.Columns.Add("ColOne", typeof(bool));
dataTable.Columns.Add("ColTwo", typeof(string));
dataTable.Columns.Add("ColThr", typeof(string));
dataTable.Columns.Add("ColFor");
foreach (DataGridViewRow dgvRow in dataGridView1.Rows)
{
if (dgvRow.Cells[0].Value != null
&& dgvRow.Cells[1].Value != null
&& dgvRow.Cells[2].Value != null
&& dgvRow.Cells[3].Value != null)
{
DataRow dataRow = dataTable.NewRow();
dataRow[0] = dgvRow.Cells[0].Value;
dataRow[1] = dgvRow.Cells[1].Value;
dataRow[2] = dgvRow.Cells[2].Value;
dataRow[3] = dgvRow.Cells[3].Value;
dataTable.Rows.Add(dataRow);
}
}
Form2 f = new Form2();
f.DataGridView.DataSource = dataTable;
f.Show();
}