Добавить пустую строку в конце DataGridView для добавления значений c# - PullRequest
0 голосов
/ 21 января 2020

Я работаю с DataGridView в форме и получаю сообщение об ошибке. Это мой DataGridView:

enter image description here

Как видите, есть строка для добавления значений, и я добавляю следующие четыре строки:

  • (DB) 335T1613 0,5
  • (DB) 335T1642 3,87
  • (DB) 001122 0,9
  • (DB) 335T1644 3,71

И мой DataGridView в порядке:

enter image description here

Но если я снова скопирую эти данные, у меня будет 2 пустых строки ...

enter image description here

Итак, проблема в том, как мне избежать этого?

Это мой код, и, конечно, я должен получить собственность 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.");
    }

Ответы [ 2 ]

1 голос
/ 21 января 2020

В случае, если строка буфера обмена содержит только значения вашей ячейки + '\n' & '\t':

Проверьте наличие пустых строк в вашем выражении foreach, вырежьте '\n' и '\t' и проверьте если строка пуста

0 голосов
/ 22 января 2020

Чтобы иметь возможность добавлять новые строки в представление данных, вам необходимо привязать его к источнику данных, в котором будут храниться данные.

Попробуйте что-то вроде ниже:

public class SomeClass{
public string Codigo {get;set;}
public string Superficie {get;set;}
public string Error {get;set;}
}

.....

var srcList = new List<SomeClass>();

.....

BindingSource bs = new BindingSource();
bs.DataSource = srcList;
bs.AllowNew = true;
bs.AddingNew += new AddingNewEventHandler(BindingSource_AddingNew); //(you may or may not need it depending on the collection used as bs.DataSource.

dataGridViewTennetPaint.AllowUserAddRows = true;
dataGridViewTennetPaint.DataSource = bs;
dataGridViewTennetPaint.DataBind();

Это мета -код. Но должен дать вам представление.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...