Форум программистов, компьютерный форум, киберфорум
C# Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/6: Рейтинг темы: голосов - 6, средняя оценка - 5.00
1 / 1 / 0
Регистрация: 13.02.2020
Сообщений: 21

System.IndexOutOfRangeException: "Индексу -1 не присвоено значение"

14.06.2023, 09:51. Показов 1632. Ответов 15
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Моя проблема заключается в следующем- при запуске программы, изначально, я могу нажимать на заголовки столбцов в flightsDataGridView , но стоит добавить новую строчку, так все летит и возникает ошибка - "System.IndexOutOfRangeException: "Индексу -1 не присвоено значение."". У меня есть еще одна форма, где есть resultDataGridView, который берет информацию из flightsDataGridView и в нем ошибок нет, очень прошу помочь в решении проблемы, поставила меня в тупик
Код Form1:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace ekz_sim_4
{
    public partial class Form1 : Form
    {
        private Dictionary<string, int> destinationCounts;
        private List<Flight> flights;
        private Panel panel1;
 
        public Form1()
        {
            destinationCounts = new Dictionary<string, int>();
            flights = new List<Flight>();
 
            InitializeComponent();
            flightsDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
 
            flightsDataGridView.DataSource = flights;
 
 
            flightsDataGridView.Columns["FlightNumber"].HeaderText = "Номер рейса";
            flightsDataGridView.Columns["Destination"].HeaderText = "Пункт назначения";
            flightsDataGridView.Columns["PassengerCount"].HeaderText = "Количество пассажиров";
 
            passengerCountTextBox.MaxLength = 4;
            flightsDataGridView.ReadOnly = true;
         
            // Устанавливаем AutoSize на true
            this.AutoSize = true;
 
            // Устанавливаем AutoSizeMode на GrowAndShrink
            this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
 
 
         
 
 
        }
 
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            
            if (flightNumberTextBox.Text.Length > 0)
            {
                
                if (flightNumberTextBox.Text[0] == '0')
                {
                    
                    flightNumberTextBox.Text = flightNumberTextBox.Text.Substring(1);
                }
 
                
            }
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
 
        }
 
        private void addButton_Click(object sender, EventArgs e)
        {
            // Получаем текст из flightNumberTextBox
            string text_2 = flightNumberTextBox.Text;
 
            // Удаляем лишние пробелы и знаки '-'
            text_2 = RemoveExtraSpacesAndDashes_2(text_2);
 
            // Обновляем значение в flightNumberTextBox
            flightNumberTextBox.Text = text_2;
 
            string text_3 = flightNumberTextBox.Text;
            text_3 = RemoveExtraSpacesAndDashes(text_3); 
            flightNumberTextBox.Text = text_3;
            // Получаем текст из destinationTextBox
            string text = destinationTextBox.Text;
 
            // Удаляем лишние пробелы и знаки '-'
            text = RemoveExtraSpacesAndDashes(text);
 
            // Обновляем значение в destinationTextBox
            destinationTextBox.Text = text;
 
            string flightNumber = RemoveExtraSpacesAndDashes_2(flightNumberTextBox.Text);
            string destination = destinationTextBox.Text;
            int passengerCount;
 
            if (string.IsNullOrEmpty(flightNumber) || string.IsNullOrEmpty(destination) || !int.TryParse(passengerCountTextBox.Text, out passengerCount))
            {
                MessageBox.Show("Пожалуйста, введите данные в поля: номер рейса, пункт назначения, количество пассажиров.");
                return;
            }
            if (flights.Any(f => f.FlightNumber.Equals(flightNumber)))
            {
                MessageBox.Show("Рейс с таким номером уже существует.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
 
            Flight flight = new Flight
            {
                FlightNumber = flightNumber,
                Destination = destination,
                PassengerCount = passengerCount
            };
 
            flights.Add(flight);
            flightsDataGridView.DataSource = null;
            flightsDataGridView.DataSource = flights;
 
            flightNumberTextBox.Clear();
            destinationTextBox.Clear();
            passengerCountTextBox.Clear();
 
            flightsDataGridView.Columns["FlightNumber"].HeaderText = "Номер рейса";
            flightsDataGridView.Columns["Destination"].HeaderText = "Пункт назначения";
            flightsDataGridView.Columns["PassengerCount"].HeaderText = "Количество пассажиров";
            MessageBox.Show("Рейс успешно добавлен.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
            // Перебираем все столбцы в DataGridView
            foreach (DataGridViewColumn column in flightsDataGridView.Columns)
            {
                // Устанавливаем свойство WrapMode каждого столбца в значение True
                column.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            }
        }
        private string RemoveExtraSpacesAndDashes_2(string text)
        {
            // Удаляем лишние пробелы
            text = text.Trim();
 
            // Удаляем повторяющиеся пробелы
            while (text.Contains("  "))
            {
                text = text.Replace("  ", " ");
            }
 
            // Удаляем знаки '-' в начале и конце текста
            text = text.Trim('-');
 
            // Удаляем пробел после знака '-' (только одно сочетание)
            text = text.Replace("- ", "-");
 
            // Удаляем повторяющиеся знаки '-'
            while (text.Contains("--"))
            {
                text = text.Replace("--", "-");
            }
 
            return text;
        }
 
        private string RemoveExtraSpacesAndDashes(string text)
        {
            // Удаляем лишние пробелы
            text = text.Trim();
 
            // Удаляем повторяющиеся пробелы
            while (text.Contains("  "))
            {
                text = text.Replace("  ", " ");
            }
 
            // Удаляем знаки '-' в начале и конце текста
            text = text.Trim('-');
 
            // Удаляем пробел после знака '-' (только одно сочетание)
            text = text.Replace("- ", "-");
 
            // Удаляем последний пробел
            text = text.TrimEnd();
 
            // Удаляем повторяющиеся знаки '-'
            while (text.Contains("--"))
            {
                text = text.Replace("--", "-");
            }
 
            return text;
        }
 
 
        private void analyzeButton_Click(object sender, EventArgs e)
        {
            if (flights.Count == 0)
            {
                MessageBox.Show("Нет данных для анализа.");
                return;
            }
 
            var destinationCounts = flights.GroupBy(flight => flight.Destination)
                                           .Select(group => new
                                           {
                                               Destination = group.Key,
                                               PassengerCount = group.Sum(flight => flight.PassengerCount)
                                           })
                                           .OrderByDescending(group => group.PassengerCount)
                                           .ToList();
 
            if (destinationCounts.Count == 0)
            {
                MessageBox.Show("Нет данных для анализа.");
                return;
            }
 
            string mostPopularDestination = destinationCounts[0].Destination;
            var flightsForMostPopularDestination = flights.Where(flight => flight.Destination == mostPopularDestination)
                                                         .OrderByDescending(flight => flight.PassengerCount)
                                                         .ToList();
 
            ResultForm resultForm = new ResultForm(mostPopularDestination, flights);
            resultForm.Show();
 
        }
 
 
        private void passengerCountTextBox_TextChanged(object sender, EventArgs e)
        {
            string text = passengerCountTextBox.Text;
 
            // Удаляем все символы, кроме цифр
            text = new string(text.Where(char.IsDigit).ToArray());
 
            // Проверяем, является ли первый символ '0'
            if (text.Length > 0 && text[0] == '0')
            {
                // Оставляем только один символ '0', если есть другие цифры
                if (text.Length > 1)
                {
                    text = "0";
                }
            }
            else
            {
                // Ограничиваем количество символов до 4
                if (text.Length > 4)
                {
                    text = text.Substring(0, 4);
                }
            }
 
            // Обновляем значение в textBox
            passengerCountTextBox.Text = text;
            passengerCountTextBox.SelectionStart = text.Length;
        }
 
        private void flightsDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            flightsDataGridView.ClearSelection();
        }
 
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
 
        }
 
        private void deleteButton_Click(object sender, EventArgs e)
        {
            // Получаем номер рейса, который необходимо удалить
            string flightNumberToDelete = flightNumberTextBox.Text;
 
            // Ищем индекс строки с указанным номером рейса
            int rowIndexToDelete = -1;
            for (int i = 0; i < flights.Count; i++)
            {
                if (flights[i].FlightNumber == flightNumberToDelete)
                {
                    rowIndexToDelete = i;
                    break;
                }
            }
 
            // Если найден индекс строки, удаляем ее из списка и из DataGridView
            if (rowIndexToDelete >= 0)
            {
                flights.RemoveAt(rowIndexToDelete);
                flightsDataGridView.DataSource = null;
                flightsDataGridView.DataSource = flights;
                flightsDataGridView.Columns["FlightNumber"].HeaderText = "Номер рейса";
                flightsDataGridView.Columns["Destination"].HeaderText = "Пункт назначения";
                flightsDataGridView.Columns["PassengerCount"].HeaderText = "Количество пассажиров";
                MessageBox.Show("Рейс успешно удален.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Рейс с указанным номером не найден.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
 
            // Очищаем текстовое поле с номером рейса
            flightNumberTextBox.Clear();
            destinationTextBox.Clear();
            passengerCountTextBox.Clear();
 
        }
        private string originalDestination;
        private string originalPassengerCount;
 
        private void deleteButton_MouseEnter(object sender, EventArgs e)
        {
            // Сохраняем исходные значения текстовых полей
            originalDestination = destinationTextBox.Text;
            originalPassengerCount = passengerCountTextBox.Text;
 
            // Очищаем текстовые поля
            destinationTextBox.Clear();
            passengerCountTextBox.Clear();
        }
 
        private void deleteButton_MouseLeave(object sender, EventArgs e)
        {
            // Возвращаем исходные значения при отмене клика
            destinationTextBox.Text = originalDestination;
            passengerCountTextBox.Text = originalPassengerCount;
 
        }
 
        private void editButton_Click(object sender, EventArgs e)
        {
            string flightNumber = flightNumberTextBox.Text;
            string destination = destinationTextBox.Text;
            string passengerCountText = passengerCountTextBox.Text;
            int passengerCount;
 
            if (string.IsNullOrEmpty(flightNumber) || string.IsNullOrEmpty(destination) || !int.TryParse(passengerCountTextBox.Text, out passengerCount))
            {
                MessageBox.Show("Пожалуйста, введите данные в поля: номер рейса, пункт назначения, количество пассажиров.");
                return;
            }
 
            // Проверяем, существует ли рейс с указанным номером
            Flight selectedFlight = flights.FirstOrDefault(f => f.FlightNumber == flightNumber);
            if (selectedFlight == null)
            {
                MessageBox.Show("Рейс с указанным номером не найден. Создайте его для изменения данных.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
 
            // Обновляем данные рейса
            selectedFlight.Destination = destination;
            selectedFlight.PassengerCount = passengerCount;
 
            // Обновляем DataGridView
            flightsDataGridView.Refresh();
        }
 
        private void flightNumberTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
    {
        TextBox textBox = (TextBox)sender;
        int selectionStart = textBox.SelectionStart;
 
        // Проверяем, есть ли перед курсором пробел, и если есть, то удаляем только его
        if (selectionStart > 0 && textBox.Text[selectionStart - 1] == ' ')
        {
            textBox.Text = textBox.Text.Remove(selectionStart - 1, 1);
            textBox.SelectionStart = selectionStart - 1;
            textBox.SelectionLength = 0;
            e.Handled = true;
            e.SuppressKeyPress = true;
        }
    }
        }
 
        private void flightsDataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                // Отменяем клик левой кнопкой мыши
                flightsDataGridView.ClearSelection();
                flightsDataGridView.CurrentCell = null;
            }
        }
    }
 
 
}
Код ResultForm:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace ekz_sim_4
{
    public partial class ResultForm : Form
    {
        private List<Flight> flightsForMostPopularDestination;
        private string mostPopularDestination;
        private List<Flight> flights;
 
        public ResultForm(string popularDestination, List<Flight> flights)
        {
           
            InitializeComponent();
            mostPopularDestination = popularDestination;
            this.flights = flights;
 
            flightsForMostPopularDestination = flights.Where(flight => flight.Destination == mostPopularDestination)
                                                     .OrderByDescending(flight => flight.PassengerCount)
                                                     .ToList(); 
 
            CalculateUniqueDestinations();
            resultDataGridView.ReadOnly = true;
 
            this.AutoScaleMode = AutoScaleMode.Font;
            this.AutoSize = true;
            this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
        }
 
        private void ResultForm_Load(object sender, EventArgs e)
        {
            // Получение суммы пассажиров по каждому пункту назначения
            var passengerCountsByDestination = flights
                .GroupBy(flight => flight.Destination)
                .Select(group => new DestinationCount
                {
                    Destination = group.Key,
                    PassengerCount = group.Sum(flight => flight.PassengerCount)
                })
                .ToList();
 
            // Определение самого популярного пункта назначения
            var mostPopularDestination = passengerCountsByDestination
                .OrderByDescending(destination => destination.PassengerCount)
                .ThenBy(destination => destination.Destination, StringComparer.CurrentCulture)
                .First();
 
            // Получение рейсов для самого популярного пункта назначения
            var flightsForMostPopularDestination = flights
                .Where(flight => flight.Destination == mostPopularDestination.Destination)
                .OrderByDescending(flight => flight.PassengerCount)
                .ToList();
 
            mostPopularDestinationLabel.Text = $"Самый популярный пункт назначения: {mostPopularDestination.Destination}" + "\r\n" + "Список рейсов самого популярного пункта назначения (по уменьшению числа пассажиров в рейсе):";
 
            // Создаем столбец для номера рейса
            DataGridViewTextBoxColumn flightNumberColumn = new DataGridViewTextBoxColumn();
            flightNumberColumn.DataPropertyName = "FlightNumber";
            flightNumberColumn.HeaderText = "Номер рейса";
            flightNumberColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; // Установка AutoSizeMode в Fill
 
            // Создаем столбец для количества пассажиров
            DataGridViewTextBoxColumn passengerCountColumn = new DataGridViewTextBoxColumn();
            passengerCountColumn.DataPropertyName = "PassengerCount";
            passengerCountColumn.HeaderText = "Количество пассажиров";
            passengerCountColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; // Установка AutoSizeMode в Fill
 
            // Создаем столбец для пункта назначения
            DataGridViewTextBoxColumn destinationColumn = new DataGridViewTextBoxColumn();
            destinationColumn.DataPropertyName = "Destination";
            destinationColumn.HeaderText = "Пункт назначения";
            destinationColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; // Установка AutoSizeMode в Fill
 
            // Добавляем столбцы в DataGridView
            resultDataGridView.Columns.AddRange(new DataGridViewColumn[] { flightNumberColumn, passengerCountColumn, destinationColumn });
 
            // Установка источника данных для DataGridView
            resultDataGridView.DataSource = flightsForMostPopularDestination;
 
            // Установка русских названий колонок
            flightNumberColumn.HeaderText = "Номер рейса";
            passengerCountColumn.HeaderText = "Количество пассажиров";
            destinationColumn.HeaderText = "Пункт назначения";
 
            CalculateUniqueDestinations();
        }
 
 
        private void CalculateUniqueDestinations()
        {
            // Получение уникальных пунктов назначения
            var uniqueDestinations = flights.Select(flight => flight.Destination).Distinct();
 
            // Подсчет количества уникальных пунктов назначения
            int destinationCount = uniqueDestinations.Count();
 
            // Отображение количества уникальных пунктов назначения в label
            destinationCountLabel.Text = $"Количество уникальных пунктов назначения: {destinationCount}";
        }
        private void SetDataGridViewHeaders()
        {
            /*flightsDataGridView.Columns["FlightNumber"].HeaderText = "Номер рейса";
            flightsDataGridView.Columns["PassengerCount"].HeaderText = "Количество пассажиров";
            flightsDataGridView.Columns["Destination"].HeaderText = "Пункт назначения";*/
        }
 
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            SetDataGridViewHeaders();
        }
 
        private void flightsDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            resultDataGridView.ClearSelection();
        }
    }
}
Так же подметил, если удалить строчки : flightsDataGridView.DataSource = null;
flightsDataGridView.DataSource = flights; из addButton, то такой ошибки не возникает и вторая форма работает корректно, но не отображаются значения в flightsDataGridView

Добавлено через 2 минуты
Вот еще коды файлов
Flight.cs:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ekz_sim_4
{
    public class Flight
    {
        public string FlightNumber { get; set; }
        public string Destination { get; set; }
        public int PassengerCount { get; set; }
        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
                return false;
 
            Flight otherFlight = (Flight)obj;
            return FlightNumber == otherFlight.FlightNumber;
        }
 
        public override int GetHashCode()
        {
            return FlightNumber.GetHashCode();
        }
 
    }
 
 
}
DestinationCount:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ekz_sim_4
{
    public class DestinationCount
    {
        public string Destination { get; set; }
        public int PassengerCount { get; set; }
    }
}
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
14.06.2023, 09:51
Ответы с готовыми решениями:

Индексу -1 не присвоено значение
есть класс Employee с несколькими полями через Data source на форму кидаю связанный DataGrid В лист добавляю несколько Employee,...

Ошибка "Индексу не присвоено значение" при удалении из DataGridView
Всем привет, У меня таблица и хочу удалить в таблице строку и Наткнулся на такую проблему &quot;Индексу 9 не присвоено значение&quot; ...

System.IndexOutOfRangeException
День добрый. Пожалуйста помогите:help:. Пишу шифровальщик виженера на c#и при запуске программы вызывается исключение...

15
2282 / 1598 / 400
Регистрация: 26.06.2017
Сообщений: 4,732
Записей в блоге: 1
14.06.2023, 10:03
Что за код?!?
Миниатюры
System.IndexOutOfRangeException: "Индексу -1 не присвоено значение"  
0
1 / 1 / 0
Регистрация: 13.02.2020
Сообщений: 21
14.06.2023, 10:34  [ТС]
Я не силен в c#, пытался сам решить проблему, но ничего не получилось, уже 2 сутки пытаюсь все реализовать
0
2393 / 1922 / 763
Регистрация: 27.07.2012
Сообщений: 5,562
14.06.2023, 10:45
Arthas2324, вы неправильно работаете с DataGridView.DataSource. Нужно один раз привязать коллекцию к этому свойству, настроить колонки и всё. Далее все новые данные будут отображаться в таблице автоматически.

Ну а по вашей ошибке - покажите, в какой строке кода возникает, так как искать по всему коду - занятие так себе.
0
1 / 1 / 0
Регистрация: 13.02.2020
Сообщений: 21
14.06.2023, 11:18  [ТС]
John Prick, Visual studio подчеркивает эту строчку Application.Run(new Form1()); и пишет ошибку к ней System.IndexOutOfRangeException: "Индексу -1 не присвоено значение."
Эта строчка находится в :

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace ekz_sim_4
{
    internal static class Program
    {
        /// <summary>
        /// Главная точка входа для приложения.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
Добавлено через 24 минуты
John Prick, чуть выше изложена ошибка и где она возникает
0
2393 / 1922 / 763
Регистрация: 27.07.2012
Сообщений: 5,562
14.06.2023, 11:28
Цитата Сообщение от Arthas2324 Посмотреть сообщение
подчеркивает эту строчку
Это ни о чём не говорит, нужно найти конкретное место возникновения этого исключения. В сообщении об ошибке посмотрите Стек Вызовов.
0
1 / 1 / 0
Регистрация: 13.02.2020
Сообщений: 21
14.06.2023, 12:02  [ТС]
John Prick
Стек вызова прикрепил в jpg.
Вот еще подробности, которые выдает visual studio:
System.IndexOutOfRangeException
HResult=0x80131508
Сообщение = Индексу -1 не присвоено значение.
Источник = System.Windows.Forms
Трассировка стека:
at System.Windows.Forms.CurrencyManager.get _Item(Int32 index)
at System.Windows.Forms.CurrencyManager.get _Current()
at System.Windows.Forms.DataGridView.DataGr idViewDataConnection.OnRowEnter(DataGrid ViewCellEventArgs e)
at System.Windows.Forms.DataGridView.OnRowE nter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
at System.Windows.Forms.DataGridView.SetCur rentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
at System.Windows.Forms.DataGridView.OnCell MouseDown(HitTestInfo hti, Boolean isShiftDown, Boolean isControlDown)
at System.Windows.Forms.DataGridView.OnCell MouseDown(DataGridViewCellMouseEventArgs e)
at System.Windows.Forms.DataGridView.OnMous eDown(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseDown (Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Mes sage& m)
at System.Windows.Forms.DataGridView.WndPro c(Message& m)
at System.Windows.Forms.Control.ControlNati veWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNati veWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Debugg ableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods .DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.Compone ntManager.System.Windows.Forms.UnsafeNat iveMethods.IMsoComponentManager.FPushMes sageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadC ontext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadC ontext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(For m mainForm)
at ekz_sim_4.Program.Main() in C:\Users\egorr\OneDrive\Рабочий стол\Серафим_мп\ekz_sim_14 (попытка)\ekz_sim_4\Program.cs:line 19
Миниатюры
System.IndexOutOfRangeException: "Индексу -1 не присвоено значение"  
0
2393 / 1922 / 763
Регистрация: 27.07.2012
Сообщений: 5,562
14.06.2023, 12:25
Arthas2324, попробуйте так:
C#
1
2
3
4
5
6
7
8
9
        private void flightsDataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                // Отменяем клик левой кнопкой мыши
                flightsDataGridView.ClearSelection();
                flightsDataGridView.CurrentCell = null;
            }
        }
0
1 / 1 / 0
Регистрация: 13.02.2020
Сообщений: 21
14.06.2023, 12:46  [ТС]
John Prick
Все равно выдает эту ошибку:
System.IndexOutOfRangeException
HResult=0x80131508
Сообщение = Индексу -1 не присвоено значение.
Источник = System.Windows.Forms
Трассировка стека:
at System.Windows.Forms.CurrencyManager.get _Item(Int32 index)
at System.Windows.Forms.CurrencyManager.get _Current()
at System.Windows.Forms.DataGridView.DataGr idViewDataConnection.OnRowEnter(DataGrid ViewCellEventArgs e)
at System.Windows.Forms.DataGridView.OnRowE nter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
at System.Windows.Forms.DataGridView.SetCur rentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
at System.Windows.Forms.DataGridView.OnCell MouseDown(HitTestInfo hti, Boolean isShiftDown, Boolean isControlDown)
at System.Windows.Forms.DataGridView.OnCell MouseDown(DataGridViewCellMouseEventArgs e)
at System.Windows.Forms.DataGridView.OnMous eDown(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseDown (Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Mes sage& m)
at System.Windows.Forms.DataGridView.WndPro c(Message& m)
at System.Windows.Forms.Control.ControlNati veWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNati veWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Debugg ableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods .DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.Compone ntManager.System.Windows.Forms.UnsafeNat iveMethods.IMsoComponentManager.FPushMes sageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadC ontext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadC ontext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(For m mainForm)
at ekz_sim_4.Program.Main() in C:\Users\egorr\OneDrive\Рабочий стол\Серафим_мп\ekz_sim_14 (попытка)\ekz_sim_4\Program.cs:line 19
0
2393 / 1922 / 763
Регистрация: 27.07.2012
Сообщений: 5,562
14.06.2023, 12:48
Цитата Сообщение от Arthas2324 Посмотреть сообщение
Все равно выдает эту ошибку
А если вообще убрать этот обработчик (или оставить пустым)?
0
1 / 1 / 0
Регистрация: 13.02.2020
Сообщений: 21
14.06.2023, 13:33  [ТС]
John Prick
То же самое :
System.IndexOutOfRangeException
HResult=0x80131508
Сообщение = Индексу -1 не присвоено значение.
Источник = System.Windows.Forms
Трассировка стека:
at System.Windows.Forms.CurrencyManager.get _Item(Int32 index)
at System.Windows.Forms.CurrencyManager.get _Current()
at System.Windows.Forms.DataGridView.DataGr idViewDataConnection.OnRowEnter(DataGrid ViewCellEventArgs e)
at System.Windows.Forms.DataGridView.OnRowE nter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
at System.Windows.Forms.DataGridView.SetCur rentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
at System.Windows.Forms.DataGridView.SetAnd SelectCurrentCellAddress(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick, Boolean clearSelection, Boolean forceCurrentCellSelection)
at System.Windows.Forms.DataGridView.MakeFi rstDisplayedCellCurrentCell(Boolean includeNewRow)
at System.Windows.Forms.DataGridView.OnCell MouseDown(DataGridViewCellMouseEventArgs e)
at System.Windows.Forms.DataGridView.OnMous eDown(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseDown (Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Mes sage& m)
at System.Windows.Forms.DataGridView.WndPro c(Message& m)
at System.Windows.Forms.Control.ControlNati veWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNati veWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Debugg ableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods .DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.Compone ntManager.System.Windows.Forms.UnsafeNat iveMethods.IMsoComponentManager.FPushMes sageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadC ontext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadC ontext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(For m mainForm)
at ekz_sim_4.Program.Main() in C:\Users\egorr\OneDrive\Рабочий стол\Серафим_мп\ekz_sim_14 (попытка)\ekz_sim_4\Program.cs:line 19
Пишет исключение не обработано, ошибка - System.IndexOutOfRangeException: "Индексу -1 не присвоено значение."

Код закометил:
C#
1
2
3
4
5
6
7
8
9
private void flightsDataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
          /*  if (e.Button == MouseButtons.Left && e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                // Отменяем клик левой кнопкой мыши
                flightsDataGridView.ClearSelection();
                flightsDataGridView.CurrentCell = null;
            }*/
        }
Добавлено через 30 минут
John Prick
Я могу прислать вам исходный файл, чтобы вам было удобнее просмотреть его
0
2393 / 1922 / 763
Регистрация: 27.07.2012
Сообщений: 5,562
14.06.2023, 13:36
Цитата Сообщение от Arthas2324 Посмотреть сообщение
Я могу прислать вам исходный файл
Скиньте ахривом в эту тему
0
1 / 1 / 0
Регистрация: 13.02.2020
Сообщений: 21
14.06.2023, 13:44  [ТС]
John Prick Заранее огромное спасибо, просто сам уже зашел в тупик с этой проблемой
Вложения
Тип файла: zip ekz_sim_14 (попытка).zip (503.6 Кб, 6 просмотров)
0
2282 / 1598 / 400
Регистрация: 26.06.2017
Сообщений: 4,732
Записей в блоге: 1
14.06.2023, 14:21
Может так сделать?
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows.Forms;
 
namespace AirTikets
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
 
    private Dictionary<string, int> destinationCounts;
    private BindingList<Flight> flights;
    private BindingSource flightsBindingSource;
    private Flight currentFlight;
 
    private void Form1_Load(object sender, EventArgs e)
    {
      flightsDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
      flightsDataGridView.AllowUserToAddRows = false;
      flightsDataGridView.AllowUserToDeleteRows = false;
 
      flights = new BindingList<Flight>();
      flightsBindingSource = new BindingSource();
      flightsBindingSource.DataSource = flights;
      flightsDataGridView.DataSource = flightsBindingSource;
 
      passengerCountTextBox.MaxLength = 4;
      flightsDataGridView.ReadOnly = true;
 
      // Устанавливаем AutoSize на true
      this.AutoSize = true;
 
      // Устанавливаем AutoSizeMode на GrowAndShrink
      this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
    }
 
    private void flightsDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      currentFlight = (Flight)flightsBindingSource.Current;
      if (currentFlight != null)
      {
        flightNumberTextBox.Text=currentFlight.FlightNumber;
        destinationTextBox.Text = currentFlight.Destination;
        passengerCountTextBox.Text=currentFlight.PassengerCount.ToString();
      }
    }
 
    private void btnAddFlight_Click(object sender, EventArgs e)
    {
      Flight newFlight = new Flight();
 
      int passengerCount;
 
      if (!int.TryParse(passengerCountTextBox.Text, out passengerCount))
      {
        MessageBox.Show("Пожалуйста, укажите правильное количество пассажиров.");
        return;
      }
 
      if (checkFlightNumber(flightNumberTextBox.Text))
      {
        MessageBox.Show("Рейс с таким номером уже существует.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
      }
 
      newFlight.FlightNumber = flightNumberTextBox.Text;
      newFlight.Destination = destinationTextBox.Text;
      newFlight.PassengerCount = passengerCount;
 
      flights.Add(newFlight);
 
      flightNumberTextBox.Clear();
      destinationTextBox.Clear();
      passengerCountTextBox.Clear();
      flightsDataGridView.ClearSelection();
    }
 
    private bool checkFlightNumber(string flightNumber)
    {
      if (flights.Any(f => f.FlightNumber.Equals(flightNumber)))
      {
        return true;
      }
      return false;
    }
 
    private void btnSaveFlight_Click(object sender, EventArgs e)
    {
      if (currentFlight == null)
      {
        return;
      }
 
      int passengerCount;
 
      if (!int.TryParse(passengerCountTextBox.Text, out passengerCount))
      {
        MessageBox.Show("Пожалуйста, укажите правильное количество пассажиров.");
        return;
      }
 
      currentFlight.FlightNumber = flightNumberTextBox.Text;
      currentFlight.Destination = destinationTextBox.Text;
      currentFlight.PassengerCount = passengerCount;
      flightsBindingSource.ResetBindings(false);
    }
  }
}


Добавлено через 2 минуты
Кнопка btnSaveFlight это кнопка редактирования.

Добавлено через 3 минуты
Изменённый класс Flight
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.ComponentModel;
 
namespace AirTikets
{
  public class Flight
  {
    [DisplayName("Номер рейса")]
    public string FlightNumber { get; set; }
    [DisplayName("Пункт назначения")]
    public string Destination { get; set; }
    [DisplayName("Количество пассажиров")]
    public int PassengerCount { get; set; }
 
    public override bool Equals(object obj)
    {
      if (obj == null || GetType() != obj.GetType())
        return false;
 
      Flight otherFlight = (Flight)obj;
      return FlightNumber == otherFlight.FlightNumber;
    }
 
    public override int GetHashCode()
    {
      return FlightNumber.GetHashCode();
    }
 
  }
}
0
2393 / 1922 / 763
Регистрация: 27.07.2012
Сообщений: 5,562
14.06.2023, 14:24
Лучший ответ Сообщение было отмечено Arthas2324 как решение

Решение

Arthas2324, в общем, проблема именно в том что вы
Цитата Сообщение от John Prick Посмотреть сообщение
неправильно работаете с DataGridView.DataSource
В конструкторе формы уберите вот эти строчки:
C#
1
2
3
4
5
            flightsDataGridView.DataSource = flights;
 
            flightsDataGridView.Columns["FlightNumber"].HeaderText = "Номер рейса";
            flightsDataGridView.Columns["Destination"].HeaderText = "Пункт назначения";
            flightsDataGridView.Columns["PassengerCount"].HeaderText = "Количество пассажиров";
и всё вроде бы работает.

Но ещё лучше - почитайте как правильно использовать DataSource с объектами типа BindingSource или DataTable. И примените у себя.
1
1 / 1 / 0
Регистрация: 13.02.2020
Сообщений: 21
14.06.2023, 17:32  [ТС]
John Prick Огромное вам спасибо, вы меня очень выручили

Добавлено через 2 часа 43 минуты
John Prick Извини, мне еще нужна небольшая помощь, я хочу сделать так, чтобы колонки автоматически занимали все доступное место в datagridview, независимо от информации в них, а если тест будет превышать ширину колонки, то она должна удлиняться, попытался сам это реализовать, но никак не выходит
public Form1()
{
destinationCounts = new Dictionary<string, int>();
flights = new List<Flight>();

InitializeComponent();
flightsDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

passengerCountTextBox.MaxLength = 4;
flightsDataGridView.ReadOnly = true;

this.AutoSize = true;

// Устанавливаем AutoSizeMode на GrowAndShrink
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;

pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
pictureBox1.Image = Image.FromFile(@"C:\Users\egorr\OneDrive \Рабочий стол\Серафим_мп\ekz_sim_14\Аэрофлот.jpg" );


// Установить запрет на изменение ширины столбцов
flightsDataGridView.AllowUserToResizeCol umns = false;

// Установить запрет на изменение высоты строк
flightsDataGridView.AllowUserToResizeRow s = false;

flightsDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells ;
flightsDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
flightsDataGridView.DefaultCellStyle.Wra pMode = DataGridViewTriState.True;


}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
14.06.2023, 17:32
Помогаю со студенческими работами здесь

System.IndexOutOfRangeException Index was outside the bounds of the array
Приветствую всех. Столкнулся с проблемой System.IndexOutOfRangeException Index was outside the bounds of the array. Имеется код ...

System.IndexOutOfRangeException: Index was outside the bounds of the array
System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.Windows.Forms.Control.MarshaledInvoke(Control...

Ошибка: "Индексу -1 не присвоено значение" при выделении ячейки DataGridView
Доброго времени суток! Пишу приложение для работы с БД MySQL. На форму поместил компонент dataGridView1. Создал запрос к БД....

System.IndexOutOfRangeException
Console.WriteLine(&quot;Сумма элементов в тех строках, которые содержат &gt;=1 отрицательных элементов:&quot;); for (int i = 0; i...

System.IndexOutOfRangeException
подскажите почему в 20 строке выдает ошибку using System; namespace ConsoleApp1 { class Program { static...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
16
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru