如何在 C# 中将数据从一种形式传输到另一种形式?

How to transmit data from 1 form to another in c#?

我想通过其他形式从我的 dbconnect class 访问 openConnection,但它不能正常工作。我必须将整个 Oopenconnection 复制粘贴到其他页面,以便他们访问它。

class 数据库连接

class DB_Connect
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string uid;
    private string password;

    //Constructor
    public DB_Connect()
    {
        Initialize();
    }

    //Initialize values
    private void Initialize()
    {
        server = "localhost";
        database = "xyz";
        uid = "root";
        password = "";

        string connectionString = $"datasource=127.0.0.1;port = 3306; SERVER={server}; DATABASE={database}; USERNAME={uid}; PASSWORD={password};sslmode=none";
        connection = new MySqlConnection(connectionString);
    }

    //open connection to database
    public bool OpenConnection()
    {

        try
        {
            connection.Open();
            return true;
        }
        catch (MySqlException ex)
        {

            switch (ex.Number)
            {
                case 0:
                    MessageBox.Show("Cannot connect to server. Contact administrator");
                    break;

                case 1045:
                    MessageBox.Show("Invalid username/password, please try again");
                    break;
            }
            return false;
        }

    }

    //Close connection
    public bool CloseConnection()
    {
         try
            {
                connection.Close();
                return true;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
         }

    }

}

我的表格 2 点击数据显示在 dataGridView

 private void display_record_Click(object sender, EventArgs e)
    {
        DB_Connect connect = new DB_Connect(); // I believe this part does not work

        string show_query = "SELECT * FROM testing_tb"; 

        if (connect.OpenConnection() == true)
        {

            using (MySqlCommand cmd_DB = new MySqlCommand(show_query, connection))
            {

                try
                {

                    using (MySqlDataReader reader = cmd_DB.ExecuteReader())

                        if (reader.HasRows)

                        {

                            dt = new DataTable();
                            dt.Load(reader);
                            dataGridView1.DataSource = dt;

                        }
                        else
                        {
                            MessageBox.Show("No data record detected");
                        }

                    connect.CloseConnection();

                }
                catch (Exception ex)

                {
                    MessageBox.Show("Could not connect to database!\n" + ex, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }// end of catch

            } // end of MySQLCommand

        } // end of connection check
    }

我想从我的 dtconnect class 访问数据,这样我就不必在每个要打开连接的新表单中粘贴 public bool OpenConnection(){}

错误:无法连接到数据库,连接必须有效且打开等。

如果您真的希望连接随处可用,您可以使用这个:

public static class Connection
{
    private const string ConnectionString = "YOUR CONNECTION";
    public static System.Data.SqlClient.SqlConnection Conn { get; private set; } = null;

    public static void Open()
    {
        try
        {
            Conn = new System.Data.SqlClient.SqlConnection(ConnectionString);
            Conn.Open();
        }
        catch { System.Windows.MessageBox.Show("Can't connect to the server, please check if you have an internet connection."); }
    }

    public static void Close() { Conn.Close(); }
}

不推荐,因为您的连接将一直打开,因此您应该这样做:

    public static class Connection
{
    private const string ConnectionString = "YOUR CONNECTION";
    public static System.Data.SqlClient.SqlConnection Conn { get; private set; } = null;

    public static void Create() { Conn = new System.Data.SqlClient.SqlConnection(ConnectionString); }
    public static void Open()
    {
        try { Conn.Open(); }
        catch { System.Windows.MessageBox.Show("Can't connect to the server, please check if you have an internet connection."); }
    }

    public static void Close() { Conn.Close(); }
}

并且在需要时打开和关闭连接。 所以基本上,当您在使用查询时打开连接时,您使用 Connection.Open()Connection.Close()。如果 class 正在使用您的表单,现在可以从任何地方访问它。

这里有一个关于连接状态的link:https://softwareengineering.stackexchange.com/questions/142065/creating-database-connections-do-it-once-or-for-each-query