Как я могу решить выбранную проблему с одной строкой?
Привет, у меня тут небольшая проблема.
Что мне нужно, так это:
Скопируйте одну строку из datagrid. Копирование нескольких строк прекрасно и работает очень хорошо. Только когда я хочу выбрать одну строку, это не работает.
Это и есть код:
<pre lang="c#"> /// <summary> /// Method which will copy entire row. /// </summary> private void CopyRow(object obj) { var datagrid = obj as System.Windows.Controls.DataGrid; var valsCollection = new List<string>(); foreach (ENotifiedTruck item in datagrid.SelectedItems) { valsCollection.Add(item.ToStringLP()); } var rows = GetDataGridRows(datagrid); int i1 = 1; bool selectedRows = false; foreach (DataGridRow r in rows) { DataGridColumn column = datagrid.Columns[0]; TextBlock cellcontent = column.GetCellContent(r) as TextBlock; valsCollection[i1] = string.Format("{0}\t{1}", cellcontent.Text, valsCollection[i1]); i1++; } datagrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader; valsCollection.Insert(0, string.Empty); ApplicationCommands.Copy.Execute(null, datagrid); string oldresult = (string)Clipboard.GetData(DataFormats.Text); List<string> rowCollection = new List<string>(); rowCollection = oldresult.Split(new char[] { '\n' }).ToList<string>(); if (rowCollection.Count == 0) return; string last = rowCollection[0]; rowCollection = new List<string>(); rowCollection.Add(last); rowCollection.AddRange(valsCollection); oldresult = string.Join("\n", rowCollection); Clipboard.SetText($"{oldresult}"); } public IEnumerable<DataGridRow> GetDataGridRows(System.Windows.Controls.DataGrid grid) { var itemsSource = grid.ItemsSource as IEnumerable; if (null == itemsSource) yield return null; foreach (var item in itemsSource) { var rows = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(item); if (null != rows) yield return rows; } }
Для меня проблема возникает, когда я выбираю одну строку. В этой конкретной линии:
Я получаю ошибку:
valsCollection[i1] = string.Format("{0}\t{1}", cellcontent.Text, valsCollection[i1]);
Ошибка заключается в следующем: "
"{Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}"
Есть идеи, как ее решить? Спасибо!
Что я уже пробовал:
Я попытался сделать это через selectedIndex, но это не сработало.