【发布时间】:2020-01-21 12:29:54
【问题描述】:
我在表单中使用 DataGridView,但出现错误。 这是我的 DataGridView:
如您所见,有一行要加值,我加了以下四行:
- (DB)335T1613 0.5
- (DB)335T1642 3.87
- (DB)001122 0.9
- (DB)335T1644 3.71
我的 DataGridView 没问题:
但如果我再次复制这些数据,我有 2 个空白行...
那么问题来了,我该如何避免呢?
这是我的代码,当然,我必须将 AllowUserAddRows 属性设为 true:
private void PasteClipboard()
{
System.Diagnostics.Debug.WriteLine("Inicio 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;
dataGridViewTennetPaint.Rows.Add(lines.Length); //before was lines.Lenght - 1
foreach (string line in lines)
{
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);
}
else
iFail++;
}
}
else
{ break; }
}
iRow++;
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;
}
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dataGridViewTennetPaint);
row.Cells[0].Value = "";
row.Cells[1].Value = "";
row.Cells[2].Value = "";
dataGridViewTennetPaint.Rows.Add(row);
System.Diagnostics.Debug.WriteLine("Fin PasteClipboard.");
}
【问题讨论】:
-
什么是dataGridViewTennetPaint.Rows.Add(row);为了?
-
@JuryGolubev 在 DataGridView 的末尾添加一个空行
-
嗯,我明白这个功能是干什么用的。但是,如果您需要允许用户编辑,您不需要自己添加任何空白行 - 数据网格的 AllowUserAddRows 和数据源的 AllowNew(如果有的话)应该可以解决问题
-
@JuryGolubev 在哪里可以找到 AllowNew? (我是新手)
-
如果您故意添加空行,那么我不明白问题所在。您的行包含空值和用于输入数据的系统行。
标签: c# datagridview