Noelle
Noelle

Reputation: 782

Pasting data into a WPF Datagrid

I am trying to paste data from the clipboard into the bottom a WPF Datagrid using the code below but it keeps saying that index is either negative or above rows count.

CanUSerAddRows is set to true

string text = Clipboard.GetText();

string[] line = Regex.Split(text , ",");

foreach (string word in line)
{

   int index = DgInvoiceLines.Items.Count;
   string prodCode = word ;

   DataGridCell ProdCodeCell = GetCell(index, 0);
   DataGridCellInfo pcell = new DataGridCellInfo(ProdCodeCell);
   string ProdCellContentType = pcell.Column.GetCellContent(pcell.Item).GetType().Name.ToString();
   if (ProdCellContentType == "TextBlock") ((TextBlock)cell.Column.GetCellContent(cell.Item)).Text = prodCode;
   else if (ProdCellContentType == "TextBox") ((TextBox)cell.Column.GetCellContent(cell.Item)).Text = prodCode;

   DataGridCell CommentCodeCell = GetCell(index, 12);
   DataGridCellInfo Ccell = new DataGridCellInfo(CommentCodeCell);
   string CommentCellContentType = Ccell.Column.GetCellContent(Ccell.Item).GetType().Name.ToString();
   if (CommentCellContentType == "TextBlock") ((TextBlock)cell.Column.GetCellContent(cell.Item)).Text = "Ord";
   else if (CommentCellContentType == "TextBox") ((TextBox)cell.Column.GetCellContent(cell.Item)).Text = "Ord";

   index = index + 1;
}

EDIT

If I change the index to 0 it throws a null reference exception

Any help is hugely appreciated. Thanks

Upvotes: 0

Views: 995

Answers (1)

Dean Chalk
Dean Chalk

Reputation: 20461

The best approach in my opinion is to create additional data objects to add to the underlying collection that your grid is (I assume) bound to. If the grids ItemsSource is an ObservableCollection<T> then the new rows will appear automatically

Upvotes: 1

Related Questions