C# data grid error: “System.IndexOutOfRangeException: ‘Index -1 does not have a value.'”

I want to click on the form data grid view and display the data from the row back in the form. This is the error that i receive: System.IndexOutOfRangeException: ‘Index -1 does not have a value.’
I am new to C#, no experience… Any idea how to solve this?

using System;
using System.Windows.Forms;

namespace Proiect_PAW
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            
            // Setam Interfata ca form principal
            Application.Run(new Interfata());
        }
    }
}

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Proiect_PAW
{
    public partial class Interfata : Form
    {
        // Lista care stocheaza toate conturile
        public List<Cont> conturi = new List<Cont>();

        public Interfata()
        {
            Console.WriteLine("2");
            InitializeComponent(); // Initializam componentele de pe formular
            Console.WriteLine("3");
            RefreshGrid(); // Metoda pentru actualizarea tabelei cu conturi
        }

        private void btnCreareCont_Click(object sender, EventArgs e)
        {
            Console.WriteLine("4");
            // Preluarea datelor din formular
            string nume = numeCont.Text;
            decimal soldInitialValue = soldInitial.Value;
            decimal soldCurentValue = soldCurent.Value;

            // Creem un cont nou
            Cont cont = new Cont(conturi.Count + 1, nume, soldInitialValue, soldCurentValue);

            // Adăugam contul în lista de conturi
            conturi.Add(cont);

            // Actualizam tabelei
            RefreshGrid();

            // Golim text box-urile de informatii
            numeCont.Text = String.Empty;
            soldInitial.Value = 0;
            soldCurent.Value = 0;
        }

        private void btnActualizareCont_Click(object sender, EventArgs e)
        {
            if (dataGridViewConturi.SelectedRows.Count > 0)
            {
                // Obținem indexului rândului selectat
                int index = dataGridViewConturi.SelectedRows[0].Index;

                // Verificam daca indexul este valid
                if (index >= 0 && index < conturi.Count)
                {
                    // Actualizam datele contului
                    conturi[index].NumeCont = numeCont.Text;
                    conturi[index].SoldInitial = soldInitial.Value;
                    conturi[index].SoldCurent = soldInitial.Value;

                    // Actualizam tabelul
                    RefreshGrid();
                }

                // Actualizam tabelul
                RefreshGrid();
            }
        }

        private void btnStergeCont_Click(object sender, EventArgs e)
        {
            if (dataGridViewConturi.SelectedRows.Count > 0)
            {
                // Obținem indexului rândului contului selectat
                int index = dataGridViewConturi.SelectedRows[0].Index;

                // Ștergem contul din lista
                conturi.RemoveAt(index);

                // Actualizam tabelul
                RefreshGrid();
            }
        }

        // Metoda utilizata pentru actualizarea tabelei cu conturi din formular
        private void RefreshGrid()
        {
            Console.WriteLine("5");
            // Resetăm sursa de date
            dataGridViewConturi.DataSource = null;
            // Apoi o resetăm cu cele mai noi date (cu lista actualizată)
            dataGridViewConturi.DataSource = conturi;

            // Asigură-te că numele coloanelor sunt setate corect
            if (dataGridViewConturi.Columns["NumeCont"] == null)
            {
                dataGridViewConturi.Columns.Add("NumeCont", "Nume Cont");
            }
            if (dataGridViewConturi.Columns["SoldInitial"] == null)
            {
                dataGridViewConturi.Columns.Add("SoldInitial", "Sold Initial");
            }
            if (dataGridViewConturi.Columns["SoldCurent"] == null)
            {
                dataGridViewConturi.Columns.Add("SoldCurent", "Sold Curent");
            }
        }

        // Metoda utilizata pentru afisarea datelor inapoi in formular cand utilizatorul apasa pe un cont
        private void dataGridViewConturi_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Console.WriteLine("6");
            try
            {
                Console.WriteLine(sender);
                Console.WriteLine(e);
                if (e.RowIndex >= 0)
                {
                    DataGridViewRow row = dataGridViewConturi.Rows[e.RowIndex];
                    numeCont.Text = row.Cells["NumeCont"].Value.ToString();
                    soldInitial.Value = Convert.ToDecimal(row.Cells["SoldInitial"].Value);
                    soldCurent.Value = Convert.ToDecimal(row.Cells["SoldCurent"].Value);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"An error occurred: {ex.Message}");
            }
        }
    }
}

namespace Proiect_PAW
{
    partial class Interfata
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.numeCont = new System.Windows.Forms.TextBox();
            this.textCampNumeCont = new System.Windows.Forms.Label();
            this.soldInitial = new System.Windows.Forms.NumericUpDown();
            this.textCampSoldInitial = new System.Windows.Forms.Label();
            this.btnCreareCont = new System.Windows.Forms.Button();
            this.btnActualizareCont = new System.Windows.Forms.Button();
            this.btnStergereCont = new System.Windows.Forms.Button();
            this.titluFormular = new System.Windows.Forms.Label();
            this.dataGridViewConturi = new System.Windows.Forms.DataGridView();
            this.textCampSoldCurent = new System.Windows.Forms.Label();
            this.soldCurent = new System.Windows.Forms.NumericUpDown();
            ((System.ComponentModel.ISupportInitialize)(this.soldInitial)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewConturi)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.soldCurent)).BeginInit();
            this.SuspendLayout();
            // 
            // numeCont
            // 
            this.numeCont.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.numeCont.Location = new System.Drawing.Point(231, 81);
            this.numeCont.Name = "numeCont";
            this.numeCont.Size = new System.Drawing.Size(411, 20);
            this.numeCont.TabIndex = 0;
            // 
            // textCampNumeCont
            // 
            this.textCampNumeCont.AutoSize = true;
            this.textCampNumeCont.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.textCampNumeCont.Location = new System.Drawing.Point(127, 81);
            this.textCampNumeCont.Name = "textCampNumeCont";
            this.textCampNumeCont.Size = new System.Drawing.Size(98, 20);
            this.textCampNumeCont.TabIndex = 1;
            this.textCampNumeCont.Text = "Nume cont : ";
            // 
            // soldInitial
            // 
            this.soldInitial.Location = new System.Drawing.Point(231, 117);
            this.soldInitial.Maximum = new decimal(new int[] {
            100000,
            0,
            0,
            0});
            this.soldInitial.Name = "soldInitial";
            this.soldInitial.Size = new System.Drawing.Size(145, 20);
            this.soldInitial.TabIndex = 2;
            // 
            // textCampSoldInitial
            // 
            this.textCampSoldInitial.AutoSize = true;
            this.textCampSoldInitial.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.textCampSoldInitial.Location = new System.Drawing.Point(127, 117);
            this.textCampSoldInitial.Name = "textCampSoldInitial";
            this.textCampSoldInitial.Size = new System.Drawing.Size(94, 20);
            this.textCampSoldInitial.TabIndex = 3;
            this.textCampSoldInitial.Text = "Sold Initial : ";
            // 
            // btnCreareCont
            // 
            this.btnCreareCont.ForeColor = System.Drawing.Color.LimeGreen;
            this.btnCreareCont.Location = new System.Drawing.Point(153, 157);
            this.btnCreareCont.Name = "btnCreareCont";
            this.btnCreareCont.Size = new System.Drawing.Size(121, 47);
            this.btnCreareCont.TabIndex = 4;
            this.btnCreareCont.Text = "Creare cont";
            this.btnCreareCont.UseVisualStyleBackColor = true;
            this.btnCreareCont.Click += new System.EventHandler(this.btnCreareCont_Click);
            // 
            // btnActualizareCont
            // 
            this.btnActualizareCont.ForeColor = System.Drawing.Color.DeepSkyBlue;
            this.btnActualizareCont.Location = new System.Drawing.Point(320, 157);
            this.btnActualizareCont.Name = "btnActualizareCont";
            this.btnActualizareCont.Size = new System.Drawing.Size(121, 47);
            this.btnActualizareCont.TabIndex = 5;
            this.btnActualizareCont.Text = "Actualizare cont";
            this.btnActualizareCont.UseVisualStyleBackColor = true;
            this.btnActualizareCont.Click += new System.EventHandler(this.btnActualizareCont_Click);
            // 
            // btnStergereCont
            // 
            this.btnStergereCont.ForeColor = System.Drawing.Color.Red;
            this.btnStergereCont.Location = new System.Drawing.Point(489, 157);
            this.btnStergereCont.Name = "btnStergereCont";
            this.btnStergereCont.Size = new System.Drawing.Size(121, 47);
            this.btnStergereCont.TabIndex = 6;
            this.btnStergereCont.Text = "Sterge cont";
            this.btnStergereCont.UseVisualStyleBackColor = true;
            this.btnStergereCont.Click += new System.EventHandler(this.btnStergeCont_Click);
            // 
            // titluFormular
            // 
            this.titluFormular.AutoSize = true;
            this.titluFormular.Font = new System.Drawing.Font("Microsoft Sans Serif", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.titluFormular.Location = new System.Drawing.Point(219, 20);
            this.titluFormular.Name = "titluFormular";
            this.titluFormular.Size = new System.Drawing.Size(345, 31);
            this.titluFormular.TabIndex = 7;
            this.titluFormular.Text = "Formular gestionare conturi";
            // 
            // dataGridViewConturi
            // 
            this.dataGridViewConturi.AllowUserToOrderColumns = true;
            this.dataGridViewConturi.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridViewConturi.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridViewConturi.Location = new System.Drawing.Point(12, 228);
            this.dataGridViewConturi.Name = "dataGridViewConturi";
            this.dataGridViewConturi.RowHeadersVisible = false;
            this.dataGridViewConturi.Size = new System.Drawing.Size(776, 210);
            this.dataGridViewConturi.TabIndex = 8;
            this.dataGridViewConturi.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridViewConturi_CellClick);
            // 
            // textCampSoldCurent
            // 
            this.textCampSoldCurent.AutoSize = true;
            this.textCampSoldCurent.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.textCampSoldCurent.Location = new System.Drawing.Point(397, 117);
            this.textCampSoldCurent.Name = "textCampSoldCurent";
            this.textCampSoldCurent.Size = new System.Drawing.Size(93, 20);
            this.textCampSoldCurent.TabIndex = 9;
            this.textCampSoldCurent.Text = "Sold Curent";
            // 
            // soldCurent
            // 
            this.soldCurent.Location = new System.Drawing.Point(497, 117);
            this.soldCurent.Maximum = new decimal(new int[] {
            100000,
            0,
            0,
            0});
            this.soldCurent.Name = "soldCurent";
            this.soldCurent.Size = new System.Drawing.Size(145, 20);
            this.soldCurent.TabIndex = 10;
            // 
            // Interfata
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 450);
            this.Controls.Add(this.soldCurent);
            this.Controls.Add(this.textCampSoldCurent);
            this.Controls.Add(this.dataGridViewConturi);
            this.Controls.Add(this.titluFormular);
            this.Controls.Add(this.btnStergereCont);
            this.Controls.Add(this.btnActualizareCont);
            this.Controls.Add(this.btnCreareCont);
            this.Controls.Add(this.textCampSoldInitial);
            this.Controls.Add(this.soldInitial);
            this.Controls.Add(this.textCampNumeCont);
            this.Controls.Add(this.numeCont);
            this.Name = "Interfata";
            this.Text = "Interfata";
            ((System.ComponentModel.ISupportInitialize)(this.soldInitial)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewConturi)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.soldCurent)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox numeCont;
        private System.Windows.Forms.Label textCampNumeCont;
        private System.Windows.Forms.NumericUpDown soldInitial;
        private System.Windows.Forms.Label textCampSoldInitial;
        private System.Windows.Forms.Button btnCreareCont;
        private System.Windows.Forms.Button btnActualizareCont;
        private System.Windows.Forms.Button btnStergereCont;
        private System.Windows.Forms.Label titluFormular;
        private System.Windows.Forms.DataGridView dataGridViewConturi;
        private System.Windows.Forms.Label textCampSoldCurent;
        private System.Windows.Forms.NumericUpDown soldCurent;
    }
}

This is my code. I tried with text in console to debug. When I debug, it stops here: Application.Run(new Interfata());

New contributor

BaStEr MiX is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật