Object reference not set to an instance of an object.

0

Panowie, już nie wiem co robię źle. Proszę o pomoc :/

Podczas ładowania formy wczytuję do ComboBox'a listę z bazy :
private MySqlConnection mysqlConnection = null;
public MySqlTransaction transaction = null;

w form_load :

          this.mysqlConnection = new MySqlConnection(
                "server="+help.getConfigValue("DBHost")+
                ";database=" + help.getConfigValue("DBNazwa") +
                ";uid=" + help.getConfigValue("DBUser") +
                ";password=" + help.getConfigValue("DBHaslo") +
                ";Persist Security Info=false; charset=utf8;");
            
            try
            {
                this.mysqlConnection.Open();
                MySqlCommand cmd = new MySqlCommand("SELECT * FROM kth_grupa", this.mysqlConnection);
                MySqlDataReader record = cmd.ExecuteReader();
                while (record.Read())
                {
                    cmbGrupa.Items.Add(record.GetValue(1).ToString());
                }
                record.Close();
                //this.mysqlConnection.Close();
            }
            catch (MySqlException error)
            {
                MessageBox.Show(error.Message.ToString());
            }

później, po wprowadzeniu danych przez użytkownika, chcę je zapisać do bazy :

            MySqlCommand cmd = null;
            string id_kth_grupa = string.Empty;
            string id_kth = string.Empty;

            

            try
            {
                this.mysqlConnection.Open();
                cmd = new MySqlCommand("SELECT id_kth_grupa FROM kth_grupa WHERE nazwa='" + cmbGrupa.SelectedItem.ToString() + "'", this.mysqlConnection);
                MySqlDataReader record = cmd.ExecuteReader();
                while (record.Read())
                {
                    id_kth_grupa = record["id_kth_grupa"].ToString();
                }
                record.Close();
            }
            catch (MySqlException error)
            {
                MessageBox.Show("Nie udało sie pobrac numeru grupy " + error.Message.ToString());
            }

            transaction = this.mysqlConnection.BeginTransaction();

            cmd = new MySqlCommand("INSERT INTO kth VALUES(NULL,'" +
                    txtNazwaFirmy.Text + "','" +
                    txtNip.Text + "','" +
                    txtRegon.Text + "','" +
                    id_kth_grupa + "','1','" +
                    txtUwagi.Text + "')", this.mysqlConnection);
            cmd.ExecuteNonQuery();
            id_kth = cmd.LastInsertedId.ToString();

            for (int i = 0; i < arraySqlCmd.Length - 1; i++)
            {
                if (!string.IsNullOrWhiteSpace(arraySqlCmd[i]))
                {
                    cmd = new MySqlCommand(arraySqlCmd[i], mysqlConnection);
                    cmd.Parameters.AddWithValue("@idKth", id_kth);
                    cmd.ExecuteNonQuery();
                    cmd.Dispose();
                }
            }

            try
            {
                transaction.Commit();
            }
            catch (MySql.Data.MySqlClient.MySqlException error)
            {
                try
                {
                    transaction.Rollback();
                }
                catch (MySql.Data.MySqlClient.MySqlException err)
                {
                    MessageBox.Show(err.Message.ToString());
                    MessageBox.Show(error.Message.ToString());
                }
            }

i po wciśnięciu buttona, w

this.mysqlConnection.Open();

dostaję
Object reference not set to an instance of an object.

Już szczerze nie wiem co robię nie tak ;/

0

wrzuć cały kod, najlepiej plik *.cs

0

Ale to jest 90% kodu w tej formie o_O, wczytanie po załadowaniu formy + 1 button 'Zapisz' i wsio.

0

Ale plik *.cs moge wrzucic do VS a tego nie chce mi się kopiować :)

Poza tym, włączasz Debugger i jedziesz linijka po linijce i zobaczysz kiedy się nulluje :)

0

Poza tym w wyjatku masz StackTrace, ktory pokazuje, w ktorej dokladnie linijce (jesli to Twoj kod wylecial) nastapil blad. Wystarczy przeczytac caly wyjatek, a nie tylko czesc.

0

this.mysqlConnection - to sugeruje że zmienna mysqlConnection jest polem w klasie formularza, a nie zmienną lokalną w metodzie. Zakładam że this nie jest nullem, więc nullem jest obiekt połączenia. Czy na pewno w momencie zamknięcia połączenia, obiekt nie jest ustawiany na null?

0

czy taka deklaracja :

  private MySqlConnection mysqlConnection = null;

mogła powodować, że mysqlConnection był null'owane po wyjściu z lokalnej funkcji ?
Sprawdziłem wszystkie sql'e, break pointy w newralgicznych miejscach i w sumie nic mi nie wyszło. Dla testów zadeklarowałem

private MySqlConnection mysqlConnection;

i działa o_O

//

wrzuciłem też najnowszy connector do mysql - może to pomogło o_O

//
massther, mysqlConnection jest deklarowane zaraz po :

  public partial class Form1 : Form, IWindows
    {
0

Nie no kurde jednak nadał mam problem :/

        private void Form1_Load(object sender, EventArgs e)
        {
            this.help = new myHelpers();
            this.arraySqlCmd = new string[50];
            this.mysqlConnection = new MySqlConnection("server="+
                this.help.getConfigValue("DBHost")+";database="+
                this.help.getConfigValue("DBNazwa")+";uid="+
                this.help.getConfigValue("DBUser")+";password="+
                this.help.getConfigValue("DBHaslo")+";Persist Security Info=false; charset=utf8;");
            try
            {
                this.mysqlConnection.Open();
                MySqlCommand cmd = new MySqlCommand("SELECT * FROM kth_grupa", this.mysqlConnection);
                MySqlDataReader record = cmd.ExecuteReader();
                while (record.Read())
                {
                    cmbGrupa.Items.Add(record.GetValue(1).ToString());
                }
                record.Close();
            }
            catch (MySqlException error)
            {
                MessageBox.Show(error.Message.ToString());
            }
        }

W Form_Load otwieram połączenie, między czasie odczytuję parę rzeczy w bazy i teraz użytkownik wypełnia formularz i klika ZAPISZ

        private void saveAllBtn_Click(object sender, EventArgs e)
        {
            MySqlCommand cmd = null;
            string id_kth_grupa = string.Empty;
            string id_kth = string.Empty;
            //------------ sprawdzanie czy wypełniono pola
            
            if (string.IsNullOrWhiteSpace(txtNazwaFirmy.Text))
            {
                MessageBox.Show("Nie podano nazwy kontrahenta !", "Błąd !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrWhiteSpace(txtNip.Text))
            {
                MessageBox.Show("Nie podano NIP'u kontrahenta !", "Błąd !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show(listKthAdres.Items.Count.ToString());
            if (listKthAdres.Items.Count == 0)
            {
                MessageBox.Show("Kontrahent powinien posiadać przynajmniej jeden adres firmowy !", "Błąd !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //--------------------------------------------
            try
            {

                if (cmbGrupa.SelectedItem != null)
                {
                    if (string.IsNullOrWhiteSpace(cmbGrupa.SelectedItem.ToString()))
                    {
                        id_kth_grupa = "0";
                    }
                    else
                    {
                        string grupaTekst = cmbGrupa.SelectedItem.ToString();
                        cmd = new MySqlCommand("SELECT id_kth_grupa FROM kth_grupa WHERE nazwa='"+grupaTekst+"';", this.mysqlConnection);
                        MySqlDataReader record = cmd.ExecuteReader();
                        while (record.Read())
                        {
                            id_kth_grupa = record["id_kth_grupa"].ToString();
                        }
                        record.Close();
                    }
                }
                else
                {
                    id_kth_grupa = "0";
                }
                   
                
            }
            catch (MySqlException error)
            {
                MessageBox.Show("Nie udało sie pobrac numeru grupy " + error.Message.ToString());
            }

            MessageBox.Show(this.mysqlConnection.State.ToString());  <----- tutaj wywala błąd  Object reference not set to an instance of an object

            cmd = new MySqlCommand("INSERT INTO kth VALUES(NULL,'" +
                       txtNazwaFirmy.Text + "','" +
                       txtNip.Text + "','" +
                       txtRegon.Text + "','" +
                       id_kth_grupa + "','1','" +
                       txtUwagi.Text + "')", this.mysqlConnection);
            cmd.ExecuteNonQuery();
            if (getArrayItem() > 0)
            {
                transaction = this.mysqlConnection.BeginTransaction();

               
                id_kth = cmd.LastInsertedId.ToString();
               
                for (int i = 0; i < arraySqlCmd.Length - 1; i++)
                {
                    if (!string.IsNullOrWhiteSpace(arraySqlCmd[i]))
                    {
                        cmd = new MySqlCommand(arraySqlCmd[i], mysqlConnection);
                        cmd.Parameters.AddWithValue("@idKth", id_kth);
                        cmd.ExecuteNonQuery();
                        cmd.Dispose();
                        //txtUwagi.AppendText(arraySqlCmd[i] + "\n");
                    }
                }

                try
                {
                    transaction.Commit();
                }
                catch (MySql.Data.MySqlClient.MySqlException error)
                {
                    try
                    {
                        transaction.Rollback();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException err)
                    {
                        MessageBox.Show(err.Message.ToString());
                        MessageBox.Show(error.Message.ToString());
                    }
                }
            }
            this.Close();
        }

jak widać nigdzie nie korzystam z :

this.mysqlConnection.Close()
  • więc dlaczego obiekt this.mysqlConnection jest pusty ??

cały plik *.cs

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel.Composition;
using System.Configuration;
using pInterface;
using System.IO;

using MySql.Data.MySqlClient;
using Helpers;

namespace addKth
{
    [Export(typeof(IWindows))]
    [WindowsMetaData("addKth", "1.0.0.0", "Forma")]

    public partial class Form1 : Form, IWindows
    {
        public Form1 dziecko_addKth;
        private MySqlConnection mysqlConnection;
        public MySqlTransaction transaction;

        public string[] arraySqlCmd;

        private myHelpers help;
        public string DBUser;
        public string DBHaslo;
        public string DBHost;
        public string DBNazwa;
        public Form1()
        {
            InitializeComponent();
        }

        public bool OpenWindow(Form pParenForm)
        {

            if (dziecko_addKth == null)
            {
                dziecko_addKth = new Form1();
                dziecko_addKth.Disposed += new EventHandler(dziecko_Disposed);
                dziecko_addKth.MdiParent = pParenForm;

                dziecko_addKth.Show();
                // dziecko.loaddane();
            };
            return true;
        }

        public void dziecko_Disposed(object sender, EventArgs e)
        {
            dziecko_addKth = null;
            //dziecko_addKth.Disposed -= new EventHandler(dziecko_Disposed);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            addKth_frm2 Form2 = new addKth_frm2(this);
            Form2.Show();
        }

  
        private void button7_Click(object sender, EventArgs e)
        {
            addKth_frm4 Form4 = new addKth_frm4(this);
            Form4.Show();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            this.help = new myHelpers();
            this.arraySqlCmd = new string[50];
            this.mysqlConnection = new MySqlConnection("server="+
                this.help.getConfigValue("DBHost")+";database="+
                this.help.getConfigValue("DBNazwa")+";uid="+
                this.help.getConfigValue("DBUser")+";password="+
                this.help.getConfigValue("DBHaslo")+";Persist Security Info=false; charset=utf8;");
            try
            {
                this.mysqlConnection.Open();
                MySqlCommand cmd = new MySqlCommand("SELECT * FROM kth_grupa", this.mysqlConnection);
                MySqlDataReader record = cmd.ExecuteReader();
                while (record.Read())
                {
                    cmbGrupa.Items.Add(record.GetValue(1).ToString());
                }
                record.Close();
            }
            catch (MySqlException error)
            {
                MessageBox.Show(error.Message.ToString());
            }
        }


       

        private void button8_Click(object sender, EventArgs e)
        {
            MySqlCommand cmd = null;
            string id_kth_grupa = string.Empty;
            string id_kth = string.Empty;
            //------------ sprawdzanie czy wypełniono pola
            
            if (string.IsNullOrWhiteSpace(txtNazwaFirmy.Text))
            {
                MessageBox.Show("Nie podano nazwy kontrahenta !", "Błąd !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrWhiteSpace(txtNip.Text))
            {
                MessageBox.Show("Nie podano NIP'u kontrahenta !", "Błąd !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show(listView2.Items.Count.ToString());
            if (listView2.Items.Count == 0)
            {
                MessageBox.Show("Kontrahent powinien posiadać przynajmniej jeden adres firmowy !", "Błąd !", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //--------------------------------------------
            try
            {

                if (cmbGrupa.SelectedItem != null)
                {
                    if (string.IsNullOrWhiteSpace(cmbGrupa.SelectedItem.ToString()))
                    {
                        id_kth_grupa = "0";
                    }
                    else
                    {
                        string grupaTekst = cmbGrupa.SelectedItem.ToString();
                        cmd = new MySqlCommand("SELECT id_kth_grupa FROM kth_grupa WHERE nazwa='"+grupaTekst+"';", this.mysqlConnection);
                        MySqlDataReader record = cmd.ExecuteReader();
                        while (record.Read())
                        {
                            id_kth_grupa = record["id_kth_grupa"].ToString();
                        }
                        record.Close();
                    }
                }
                else
                {
                    id_kth_grupa = "0";
                }
                   
                
            }
            catch (MySqlException error)
            {
                MessageBox.Show("Nie udało sie pobrac numeru grupy " + error.Message.ToString());
            }

            MessageBox.Show(this.mysqlConnection.State.ToString());

            cmd = new MySqlCommand("INSERT INTO kth VALUES(NULL,'" +
                       txtNazwaFirmy.Text + "','" +
                       txtNip.Text + "','" +
                       txtRegon.Text + "','" +
                       id_kth_grupa + "','1','" +
                       txtUwagi.Text + "')", this.mysqlConnection);
            cmd.ExecuteNonQuery();
            if (getArrayItem() > 0)
            {
                transaction = this.mysqlConnection.BeginTransaction();

               
                id_kth = cmd.LastInsertedId.ToString();
               
                for (int i = 0; i < arraySqlCmd.Length - 1; i++)
                {
                    if (!string.IsNullOrWhiteSpace(arraySqlCmd[i]))
                    {
                        cmd = new MySqlCommand(arraySqlCmd[i], mysqlConnection);
                        cmd.Parameters.AddWithValue("@idKth", id_kth);
                        cmd.ExecuteNonQuery();
                        cmd.Dispose();
                        //txtUwagi.AppendText(arraySqlCmd[i] + "\n");
                    }
                }

                try
                {
                    transaction.Commit();
                }
                catch (MySql.Data.MySqlClient.MySqlException error)
                {
                    try
                    {
                        transaction.Rollback();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException err)
                    {
                        MessageBox.Show(err.Message.ToString());
                        MessageBox.Show(error.Message.ToString());
                    }
                }
            }
            this.Close();
        }



        public int getArrayItem()
        {
            int i = 0;
            while (i <= this.arraySqlCmd.Length - 1)
            {
                if (string.IsNullOrWhiteSpace(arraySqlCmd[i]))
                {
                    break;
                }
                i++;
            }
            return i;
        }



        private void button5_Click_1(object sender, EventArgs e)
        {
            addKth_frm5 Form5 = new addKth_frm5(this);
            Form5.Show();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (listView2.SelectedItems.Count > 0)
            {
                listView2.Items.RemoveAt(listView2.SelectedIndices[0]);
            }
        }


        private void button3_Click(object sender, EventArgs e)
        {
            if (listView3.SelectedItems.Count > 0)
            {
                listView3.Items.RemoveAt(listView3.SelectedIndices[0]);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                listView1.Items.RemoveAt(listView1.SelectedIndices[0]);
            }
        }

        private void listView4_DoubleClick(object sender, EventArgs e)
        {
            if (listView4.SelectedItems.Count > 0)
            {
                frmHistoryDetails Form6 = new frmHistoryDetails(listView4.SelectedIndices[0]);
                Form6.Show();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.mysqlConnection.Close();
        }

    


    }
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1