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