Good day. I have a button on the main form, by clicking on which another form opens. When I open this form, I fill in the DataGridView with data from the database.
int bonus = 0; private void ClientsLoad(int b) { CommandText = "SELECT Clients_info.Id, Clients_info.Surname+' '+Left(Clients_info.Name,1)+'.'+Left(Clients_info.Patronymic,1)+'.', Clients_info.Phone_number FROM Clients_info INNER JOIN Bonus_card ON Bonus_card.Id = Clients_info.Id_bonus_card WHERE (Clients_info.SMS_sending = 1) AND Bonus_card.Accrued_bonuses >= " + b.ToString() + " AND Bonus_card.Id > 1;"; dataGridView1.AllowUserToAddRows = false; myCommand = new SqlCommand(CommandText, myConnection); mySqlDataAdapter = new SqlDataAdapter(myCommand); myDataSet = new DataSet(); mySqlDataAdapter.Fill(myDataSet); if (myDataSet.Tables.Count > 0) dataGridView1.DataSource = myDataSet.Tables[0].DefaultView; } private void Form_SMSSending_Load(object sender, EventArgs e) { this.Left = Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2; this.Top = Screen.PrimaryScreen.Bounds.Height / 2 - this.Height / 2; ClientsLoad(bonus); if (dataGridView1.Columns.Count < 4) dataGridView1.Columns.Add(SMS_check); dataGridView1.Columns[0].Width = 45; dataGridView1.Columns[0].HeaderText = "№ п/п"; dataGridView1.Columns[1].HeaderText = "ФИО"; dataGridView1.Columns[2].HeaderText = "Телефон"; dataGridView1.Columns[3].HeaderText = "Выбрать"; } So, as you can see from the code, I get 4 columns. But when the form is closed and when it is reopened, the headers of the 3 and 0 columns change places. I can not understand why. I tried to completely clear when closing DGV like this:
private void Form_SMS_Sending_FormClosing(object sender, FormClosingEventArgs e) { myDataSet.Clear(); dataGridView1.SelectAll(); dataGridView1.ClearSelection(); dataGridView1.Columns.Clear(); } So:
private void Form_SMS_Sending_FormClosing(object sender, FormClosingEventArgs e) { while (dataGridView1.Columns.Count != 0) { dataGridView1.Columns.RemoveAt(dataGridView1.Columns.Count - 1); } } But in this case, the reopening ends with an error on the line: dataGridView1.Columns [0] .Width = 45; Tell me, please, how to fix the first problem and what is the problem with the second one? PS Regarding the second, the feeling that I deleted all the columns of the code, I could not reuse the same column indices as if I deleted the record in the database. But I have never encountered such a problem.
dataGridView1.Columns[0].Width = 45?ArgumentOutOfRangeException? - Anton Komyshannullbefore accessing the indexer. - Anton Komyshan