Отправка данных из dataGridView в Form2

182
04 июля 2018, 04:00

Есть код для отправки данных из dataGridView в Form2:

private void button1_Click(object sender, EventArgs e)
        {
            int curRowsCount = dataGridView2.Rows.Count;
            int curColumnCount = dataGridView2.ColumnCount;
            for (int i = 0; i < dataGridView2.Columns.Count; i++)
                agenstvo[i] = dataGridView2.Rows[curRowsCount].Cells[curColumnCount].Value.ToString();
            Form2 f = new Form2();
            f.Show();
        }

Но при нажатии на кнопку возникает ошибка в этой строке:

agenstvo[i] = dataGridView2.Rows[curRowsCount].Cells[curColumnCount].Value.ToString();

С таким сообщением:

System.ArgumentOutOfRangeException не обработано
  HResult=-2146233086
  Message=Индекс за пределами диапазона. Индекс должен быть положительным числом, а его размер не должен превышать размер коллекции.
Имя параметра: index
  Source=mscorlib
  ParamName=index
  StackTrace:
       в System.Collections.ArrayList.get_Item(Int32 index)
       в System.Windows.Forms.DataGridViewRowCollection.SharedRow(Int32 rowIndex)
       в System.Windows.Forms.DataGridViewRowCollection.get_Item(Int32 index)
       в RGR_OBD.Form1.button1_Click(Object sender, EventArgs e) в d:\VS\RGR_OBD\RGR_OBD\Form1.cs:строка 322
       в System.Windows.Forms.Control.OnClick(EventArgs e)
       в System.Windows.Forms.Button.OnClick(EventArgs e)
       в System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       в System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       в System.Windows.Forms.Control.WndProc(Message& m)
       в System.Windows.Forms.ButtonBase.WndProc(Message& m)
       в System.Windows.Forms.Button.WndProc(Message& m)
       в System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       в System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       в System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       в System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       в System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       в System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       в System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       в System.Windows.Forms.Application.Run(Form mainForm)
       в RGR_OBD.Program.Main() в d:\VS\RGR_OBD\RGR_OBD\Program.cs:строка 19
       в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       в System.Threading.ThreadHelper.ThreadStart()
  InnerException:

Как исправить?

Answer 1
int curRowsCount = dataGridView2.Rows.Count - 1;
int curColumnCount = dataGridView2.ColumnCount - 1;

но это не "текущие" запись и колонка, а последние. Соответственно, в цикле вы берете одно и то же значение.

На случай если в ячейке ничего нет:

agenstvo[i] = System.Convert.ToString(dataGridView2.Rows[curRowsCount].Cells[curColumnCount].Value.);
Answer 2

Если я правильно понял проблему, тогда как вариант - прописать в Form2 свой конструктор с передачей массива "agenstvo". И тогда:

Form2 f = new Form2(agenstvo[]); 
f.Show();

Но массив сначала инициализировать в исходной форме. В созданной форме массив, соответственно, обработать, как вам нужно.

READ ALSO
Что лучше использовать и как обойти ограничения

Что лучше использовать и как обойти ограничения

Есть Веб приложение (ASP NET MVC), которое досталось на поддержкуЧасть по аутентификации использует подключение к базе MS SQL Server Expres

194
Распарсить svg файлы

Распарсить svg файлы

Есть несколько svg файлов следующего формата

238