所以,我想要实现的是从Excel复制并将其粘贴到一个非空的DataGridView视图中。我也希望对不同的角色具有可读性。我试图在粘贴之后不要松开那一行(第一张图片)。先谢谢你。
First Image: http://postimg.org/image/u656ou22v/
错误图片:http://postimg.org/image/63o1evn77/
这是我在添加按钮中的代码:
DataObject o = (DataObject)Clipboard.GetDataObject();
if (o.GetDataPresent(DataFormats.Text))
{
if (dataGridView1.RowCount > 0)
dataGridView1.Rows.Clear();
if (dataGridView1.ColumnCount > 0)
dataGridView1.Columns.Clear();
bool columnsAdded = false;
string[] pastedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("\r\n".ToCharArray()), "\r\n");
int j = 0;
foreach (string pastedRow in pastedRows)
{
string[] pastedRowCells = pastedRow.Split(new char[] { '\t' });
if (!columnsAdded)
{
for (int i = 0; i < pastedRowCells.Length; i++)
dataGridView1.Columns.Add("col" + i, pastedRowCells[i]);
columnsAdded = true;
continue;
}
dataGridView1.Rows.Add();
int myRowIndex = dataGridView1.Rows.Count - 1;
using (DataGridViewRow myDataGridViewRow = dataGridView1.Rows[j])
{
for (int i = 0; i < pastedRowCells.Length; i++)
myDataGridViewRow.Cells[i].Value = pastedRowCells[i];
}
j++;
}
}
答案 0 :(得分:1)
如果要保留标题,则必须不删除DataGridView的列。
这样可以通过这种方式简化您的代码:
DataObject o = (DataObject)Clipboard.GetDataObject();
if (o.GetDataPresent(DataFormats.Text))
{
if (dataGridView1.RowCount > 0)
dataGridView1.Rows.Clear();
string[] pastedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("\r\n".ToCharArray()), "\r\n");
int j = 0;
foreach (string pastedRow in pastedRows)
{
string[] pastedRowCells = pastedRow.Split(new char[] { '\t' });
dataGridView1.Rows.Add();
int myRowIndex = dataGridView1.Rows.Count - 1;
using (DataGridViewRow myDataGridViewRow = dataGridView1.Rows[j])
{
for (int i = 0; i < pastedRowCells.Length; i++)
myDataGridViewRow.Cells[i].Value = pastedRowCells[i];
}
j++;
}
}
我甚至建议您不要删除行,因为您的按钮被称为“添加”而不是“替换”:
DataObject o = (DataObject)Clipboard.GetDataObject();
if (o.GetDataPresent(DataFormats.Text))
{
string[] pastedRows = Regex.Split(o.GetData(DataFormats.Text).ToString().TrimEnd("\r\n".ToCharArray()), "\r\n");
int j = 0;
foreach (string pastedRow in pastedRows)
{
string[] pastedRowCells = pastedRow.Split(new char[] { '\t' });
dataGridView1.Rows.Add();
int myRowIndex = dataGridView1.Rows.Count - 1;
using (DataGridViewRow myDataGridViewRow = dataGridView1.Rows[j])
{
for (int i = 0; i < pastedRowCells.Length; i++)
myDataGridViewRow.Cells[i].Value = pastedRowCells[i];
}
j++;
}
}
我的最后一个建议是,您可以添加一些粘贴的数据检查,例如if (pastedRows.length == dataGridView1.RowCount)
。