Search code examples
c#mysqlado.net

WinForms: Connection must be valid and open


There is a DataGridView element on the form, in which there is a connected SQL table. Also on the form there are several elements for entering data and a button, when clicked, the process of adding data should be performed directly.Thanks in advance. Here is the code:

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;
using System.Configuration;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace Курсовая.Приложение
{
    public partial class ProfileForm : Form
    {
        public ProfileForm()
        {
            InitializeComponent();
        }
        private void ProfileForm_Load(object sender, EventArgs e)
        {
            TouristGridView.DataSource = GetTouristList();
        }
        private DataTable dtTourist = new DataTable();
        private DataTable GetTouristList()
        {
            string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(connString))
            {
                using (MySqlCommand cmd = new MySqlCommand("SELECT FIO, dob, phone FROM tourist", con))
                {
                    con.Open();
                    MySqlDataReader reader = cmd.ExecuteReader();
                    dtTourist.Load(reader);
                }
            }
            return dtTourist;
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(connString))
            {
                con.Open();
                MySqlCommand Command = new MySqlCommand("INSERT INTO [tourist] ([FIO], [dob], [phone]) VALUES ('" + NametextBox.Text + "','" + dobDate.Value + "','" + PhonetextBox.Text + "')");
                Command.ExecuteNonQuery();
            }
        }
    }
}

Solution

  • When you instance your MySqlConnection, you have to pass the open connection Object, like that :

    private void button1_Click_1(object sender, EventArgs e)
            {
                string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
                using (MySqlConnection con = new MySqlConnection(connString))
                {
                    con.Open();
                    MySqlCommand Command = new MySqlCommand("INSERT INTO [tourist] ([FIO], [dob], [phone]) VALUES ('" + NametextBox.Text + "','" + dobDate.Value + "','" + PhonetextBox.Text + "')", con);
                    Command.ExecuteNonQuery();
                }
            }