我有一个带有带有三列的DataGridView的表单:
[我想做的是复制例如下一个代码:
并在DataGridView的“ Codigo”和“ Superficie”列中进行介绍。我怎样才能做到这一点?我一直在尝试这篇文章的代码:Link of my code,但是使用此代码,我只是将所有代码复制到第一个单元格[0,0]中。例如,如果我尝试将第一行的内容复制到第二行,则会得到以下信息:
并且应该像这样:
这是我尝试执行的方法:
private void PasteClipboard()
{
System.Diagnostics.Debug.WriteLine("Dentro de PasteClipboard .");
try
{
string s = Clipboard.GetText();
string[] lines = s.Split('\n');
int iFail = 0, iRow = dataGridViewTennetPaint.CurrentCell.RowIndex;
int iCol = dataGridViewTennetPaint.CurrentCell.ColumnIndex;
DataGridViewCell oCell;
if (dataGridViewTennetPaint.Rows.Count < lines.Length)
dataGridViewTennetPaint.Rows.Add(lines.Length - 1);
foreach (string line in lines)
{
System.Diagnostics.Debug.WriteLine("Line contiene: " + line);
if (iRow < dataGridViewTennetPaint.RowCount && line.Length > 0)
{
string[] sCells = line.Split('\t');
for (int i = 0; i < sCells.GetLength(0); ++i)
{
if (iCol + i < this.dataGridViewTennetPaint.ColumnCount)
{
oCell = dataGridViewTennetPaint[iCol + i, iRow];
if (!oCell.ReadOnly)
{
if (oCell.Value == null || oCell.Value.ToString() != sCells[i])
{
oCell.Value = Convert.ChangeType(sCells[i],
oCell.ValueType);
// oCell.Style.BackColor = Color.Tomato;
}
else
iFail++;
//only traps a fail if the data has changed
//and you are pasting into a read only cell
}
}
else
{ break; }
}
iRow++;
}
else
{ break; }
if (iFail > 0)
MessageBox.Show(string.Format("{0} updates failed due" +
" to read only column setting", iFail));
}
}
catch (FormatException)
{
MessageBox.Show("The data you pasted is in the wrong format for the cell");
return;
}
}
}
并且DataGridView的定义如下:
private System.Windows.Forms.DataGridView dataGridViewTennetPaint;
private System.Windows.Forms.DataGridViewTextBoxColumn columnCodigo;
private System.Windows.Forms.DataGridViewTextBoxColumn columnSuperficie;
private System.Windows.Forms.DataGridViewTextBoxColumn columnError;
提前感谢!
不要编辑每个单元格。您可以像这样添加整行:
yourDataGrid.Rows.Add("335T1612", "0,5", "");
基本上,dataGridView具有一个名为“行”的集合,您可以使用Add方法向其中添加项目。
此外,由于这只是一个可视控件,而不是向dataGridView添加或删除行,因此最好在内存中存储具有所需值的DataTable,然后将此表用作datagrid的数据源:
DataTable tabla = new DataTable();
tabla.Rows.Add("335T1612", "0,5", "");
yourDataGrid.DataSource = tabla;