I cannot change the header in "dataGridView"

-1

This is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DuyuTekStokApp
{
    public partial class StockCard : Form
    {
        //SqlConnection connect = new SqlConnection("Data Source = (localdb)\\MSSQLLocalDB; AttachDbFilename=|DataDirectory|StockControl.mdf; Integrated Security = True");
        SqlConnection connect = new SqlConnection("Data Source=DESKTOP-L01MAVE;Initial Catalog='StockControl';Integrated Security=True");
        string imageUrl = null;
        public StockCard()
        {
            InitializeComponent();
        }

        public void changeHeader()
        {
            dataGridViewStok.Columns[0].HeaderText = "Stok Kodu";
            dataGridViewStok.Columns[1].HeaderText = "Stok Cinsi";
            dataGridViewStok.Columns[2].HeaderText = "Barkod Numarası";
            dataGridViewStok.Columns[3].HeaderText = "Birimi";
            dataGridViewStok.Columns[4].HeaderText = "Grubu";
            dataGridViewStok.Columns[5].HeaderText = "Tarih";
            dataGridViewStok.Columns[6].HeaderText = "Açıklama";
            dataGridViewStok.Columns[7].HeaderText = "Resim";
        }
        public void VerileriGoster(string Veriler)
        {
            SqlDataAdapter da = new SqlDataAdapter(Veriler, connect);
            DataSet ds = new DataSet();
            da.Fill(ds);
            dataGridViewStok.DataSource = ds.Tables[0];
        }
        private void StockCard_Load(object sender, EventArgs e)
        {
            changeHeader();
            // TODO: This line of code loads data into the 'stockControlDataSet.Gruplar' table. You can move, or remove it, as needed.
            this.gruplarTableAdapter.Fill(this.stockControlDataSet.Gruplar);
            // TODO: This line of code loads data into the 'stockControlDataSet.Birimler' table. You can move, or remove it, as needed.
            this.birimlerTableAdapter.Fill(this.stockControlDataSet.Birimler);
            // TODO: This line of code loads data into the 'stockControlDataSet.StockCard' table. You can move, or remove it, as needed.
            this.stockCardTableAdapter.Fill(this.stockControlDataSet.StockCard);
            VerileriGoster("SELECT StokKodu, StokCinsi, StokBarkod, StokBirim, StokGrup, StokTarih, StokAciklama, StokResim FROM StockCard ORDER BY StokKodu ASC");
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnClose_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnEkle_Click(object sender, EventArgs e)
        {
            Image img = pictureBoxResim.Image;
            byte[] arr;
            ImageConverter converter = new ImageConverter();
            arr = (byte[])converter.ConvertTo(img, typeof(byte[]));

            try
            {
                SqlDataAdapter da = new SqlDataAdapter("SELECT StokKodu FROM StockCard WHERE StokKodu='" + textBoxKod + "' ", connect);
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count >= 1)
                {
                    MessageBox.Show("Aynı kod");
                }
                else
                {
                    connect.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO StockCard(StokKodu, StokCinsi, StokBarkod, StokBirim, StokGrup, StokTarih, StokAciklama, StokResim) " +
                        "VALUES(@SKod,@SCins, @SBarkod, @SBirim, @SGrup, @STarih, @SAciklama, @SResim) ", connect);
                    cmd.Parameters.AddWithValue("@SKod", textBoxKod.Text);
                    cmd.Parameters.AddWithValue("@SCins", textBoxCins.Text);
                    cmd.Parameters.AddWithValue("@SBarkod", textBoxBarkod.Text);
                    cmd.Parameters.AddWithValue("@SBirim", comboBoxBirim.Text);
                    cmd.Parameters.AddWithValue("@SGrup", comboBoxGrup.Text);
                    cmd.Parameters.AddWithValue("@STarih", dateTimeTarih.Text);
                    cmd.Parameters.AddWithValue("@SAciklama", richTextAciklama.Text);
                    cmd.Parameters.AddWithValue("@SResim", arr);
                    int sonuc = cmd.ExecuteNonQuery();
                    if (sonuc == -1)
                    {
                        MessageBox.Show("Bu ürün daha önce stoklarımıza eklenmiştir. Aynı ürünü birden fazla kez ekleyemezsiniz.", "Hata");
                    }
                    else
                    {
                        MessageBox.Show("Yeni Stok Eklendi.", "Bilgi");
                    }
                    VerileriGoster("SELECT StokKodu, StokCinsi, StokBarkod, StokBirim, StokGrup, StokTarih, StokAciklama, StokResim FROM StockCard ORDER BY StokKodu ASC");
                    connect.Close();
                    MessageBox.Show("Yeni Stok Eklendi.", "Bilgi");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Lütfen Boş Alanları Doldurunuz!", "Hata!");
            }
                textBoxKod.Clear();
                textBoxCins.Clear();
                textBoxBarkod.Clear();
                comboBoxBirim.Text = null;
                comboBoxGrup.Text = null;
                dateTimeTarih.Text = null;
                richTextAciklama.Clear();
                pictureBoxResim.Image = null;
                textBoxKod.Focus();
            
        }

        private void dataGridViewStok_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int secilen = dataGridViewStok.SelectedCells[0].RowIndex;
            textBoxKod.Text = dataGridViewStok.Rows[secilen].Cells[0].Value?.ToString();
            textBoxCins.Text = dataGridViewStok.Rows[secilen].Cells[1].Value.ToString();
            textBoxBarkod.Text = dataGridViewStok.Rows[secilen].Cells[2].Value.ToString();
            comboBoxBirim.Text = dataGridViewStok.Rows[secilen].Cells[3].Value.ToString();
            comboBoxGrup.Text = dataGridViewStok.Rows[secilen].Cells[4].Value.ToString();
            dateTimeTarih.Text = dataGridViewStok.Rows[secilen].Cells[5].Value.ToString();
            richTextAciklama.Text = dataGridViewStok.Rows[secilen].Cells[6].Value.ToString();
            byte[] bytes = (byte[])dataGridViewStok.Rows[secilen].Cells[7].Value;
            MemoryStream ms = new MemoryStream(bytes);
            pictureBoxResim.Image = Image.FromStream(ms);
        }

        private void btnResim_Click(object sender, EventArgs e)
        {
            using(OpenFileDialog ofd = new OpenFileDialog())
            {
                if(ofd.ShowDialog()==DialogResult.OK)
                {
                    imageUrl = ofd.FileName;
                    pictureBoxResim.Image = Image.FromFile(ofd.FileName);
                }
            }
        }

        private void listBoxUrunler_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void btnSil_Click(object sender, EventArgs e)
        {
            try
            {
                if (textBoxKod.Text == string.Empty && textBoxBarkod.Text == string.Empty && textBoxCins.Text == string.Empty)
                {
                    MessageBox.Show("Lütfen ürün seçiniz.", "Uyarı");
                }
                else
                {
                    DialogResult secenek = MessageBox.Show("Silmek İstediğinize Emin Misiniz?", "Uyarı", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (secenek == DialogResult.Yes)
                    {
                        connect.Open();
                        SqlCommand cmd = new SqlCommand("DELETE FROM StockCard WHERE StokKodu=@SKod", connect);
                        cmd.Parameters.AddWithValue("@SKod", textBoxKod.Text);
                        cmd.ExecuteNonQuery();
                        VerileriGoster("SELECT StokKodu, StokCinsi, StokBarkod, StokBirim, StokGrup, StokTarih, StokAciklama, StokResim FROM StockCard ORDER BY StokKodu ASC");
                        connect.Close();
                        MessageBox.Show("Stok Silindi.", "Bilgi", MessageBoxButtons.OK);

                        textBoxKod.Clear();
                        textBoxCins.Clear();
                        textBoxBarkod.Clear();
                        comboBoxBirim.Text = null;
                        comboBoxGrup.Text = null;
                        dateTimeTarih.Text = null;
                        richTextAciklama.Text = null;
                        pictureBoxResim.Image = null;
                        textBoxKod.Focus();
                    }
                    else if (secenek == DialogResult.No)
                    {
                        MessageBox.Show("Silme İşlemi İptal Edildi.", "MESAJ");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDuzen_Click(object sender, EventArgs e)
        {

        }
    }
}

This is the whole error I get:

System.ArgumentOutOfRangeException
  HResult = 0x80131502
  Message = Directory was out of range. It should not be a negative value and should be smaller than the size of the collection.
Parameter name: index
  Source = mscorlib
  StackTrace:
   at System.Collections.ArrayList.get_Item (Int32 index)
   at System.Windows.Forms.DataGridViewColumnCollection.get_Item (Int32 index)
   at SenseTekStokApp.StockCard.changeHeader () in D: \ yNs \ VisualTutorials \ SenseTekStokApp \ SenseTekStokApp \ StockCard.cs: line 27
   at SenseTekStokApp.StockCard.StockCard_Load (Object sender, EventArgs e) in D: \ yNs \ VisualTutorials \ SenseTekStokApp \ SenseTekStokApp \ StockCard.cs: line 45
   at System.Windows.Forms.Form.OnLoad (EventArgs e)
   at System.Windows.Forms.Form.OnCreateControl ()
   at System.Windows.Forms.Control.CreateControl (Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl ()
   at System.Windows.Forms.Control.SetVisibleCore (Boolean value)

  This exception was originally thrown at this call stack:
    [External Code]
    DuyuTekStokApp.StockCard.changeHeader () in StockCard.cs
    SenseTekStokApp.StockCard.StockCard_Load (object, System.EventArgs) in StockCard.cs
    [External Code]

The code is fully working. But when I add "public void changeHeader ()" method, I get this error. I also tried changing the dataGridView properties from the "DataGridView Tasks" section from the "Edit Columns ..." menu. But that didn't work either.

My "headers" are now from my table names in SQL Server. I want to change this. I don't know the cause of the error and how can I do it. I would be glad if you could help.

c#
sql-server
visual-studio

2 Answers

0

When you load your form the datagridview columns are not initialized but you try to change their names. Call this method after loading data from database.

answered on Stack Overflow Nov 11, 2020 by Yaroslav Menshikov
0

When you call changeHeader, the datagridview hasn't been bound to any data source. So there is no columns in datagridview.

Try to set datagridview's data source first, then reset columns' name.

private void StockCard_Load(object sender, EventArgs e)
{
    // code omitted
    // ...
    VerileriGoster("SELECT StokKodu, StokCinsi, StokBarkod, StokBirim, StokGrup, StokTarih, StokAciklama, StokResim FROM StockCard ORDER BY StokKodu ASC");
    changeHeader();
}
answered on Stack Overflow Nov 12, 2020 by Kyle Wang - MSFT

User contributions licensed under CC BY-SA 3.0