예제 #1
0
        /// <summary>
        /// Вствляет или заменяет строки в таблице DataGridView c заданной выделенной строки текст
        /// из заданного текста который разделен символом "\t" обозначающим разделение мезжу ячейками и "\r\n" между строками.
        /// </summary>
        /// <param name="dataGridView">Текщая таблица DataGridView.</param>
        /// <param name="text">Вставляемый текст.</param>
        public static void AddRowsFromText(this DataGridView dataGridView, string text)
        {
            // Проверяем входные параметры.
            if (dataGridView == null || text == null)
            {
                return;
            }
            // Получаем кол-во колонок в таблице.
            int columnCount     = dataGridView.ColumnCount;
            int currentRowIndex = 0;

            // В случае отсутствия колонок операция неудачна.
            if (columnCount <= 0)
            {
                return;
            }

            // Устанавливаем из выбранных строк индекс первой с начала которой будем производить вставку.
            if (dataGridView.SelectedRows.Count > 0)
            {
                currentRowIndex = dataGridView.SelectedRows[0].Index;
                foreach (DataGridViewRow row in dataGridView.SelectedRows)
                {
                    if (row.Index < currentRowIndex)
                    {
                        currentRowIndex = row.Index;
                    }
                }
            }

            string [] rowParts = text.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            // Преобразовываем входной текст в массивы построчно.
            foreach (string rowPart in rowParts)
            {
                string[] textRowParts = rowPart.Split("\t".ToCharArray());
                if (textRowParts.Length <= columnCount)
                {
                    if (dataGridView.Rows[currentRowIndex].IsNewRow || dataGridView.RowCount <= currentRowIndex)
                    {
                        dataGridView.Rows.Add();
                    }

                    // Заполняем значения строки в таблице dataGridView.
                    for (int colIndex = 0; colIndex < textRowParts.Length; colIndex++)
                    {
                        DataGridViewCell cell = dataGridView.Rows[currentRowIndex].Cells[colIndex];
                        if (cell.GetType() == typeof(DataGridViewTextBoxCell))
                        {
                            cell.Value = textRowParts[colIndex];
                        }
                        else if (cell.GetType() == typeof(DataGridViewComboBoxCell))
                        {
                            if (!cell.SetComboBoxCellValue(textRowParts[colIndex]))
                            {
                                cell.SetComboBoxCellIndex(0);
                            }
                        }
                    }
                    currentRowIndex++;
                }
            }
        }