Что мне делать, если я хочу, чтобы значение dgv1 (datagridview) отображалось в другой форме? - PullRequest
0 голосов
/ 03 августа 2020

Форма1

namespace erpmam
{
    public partial class Form1 : Form
    {
        MySqlDB mySqlDB;
        SqlDataAdapter adpt;
        DataTable dt;
        SqlConnection con;
        public void showdata()
        {
            adpt = new SqlDataAdapter("select deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms from sys_department;",con);
            dt = new DataTable();
            adpt.Fill(dt);
            dgv1.DataSource = dt;
        }

        public Form1()
        {
            InitializeComponent();
        }

        public void Form1_Load(object sender, EventArgs e)
        {
            mySqlDB = new MySqlDB("server=······");
        }

        private SqlDataAdapter MySqlDataAdapter(string v, MySqlConnection con)
        {
            throw new NotImplementedException();
        }

        public void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void BTN_INSERT_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.ShowDialog();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string sql = "";
            sql += " select";
            sql += " deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms";
            sql += " from sys_department";
            sql += " where deptmt_id like '%" + textBox1.Text.Trim() + "%'";

            DataTable dt = mySqlDB.ExecuteReader(sql, mySqlDB.DBConnection());

            dgv1.SuspendLayout();
            dgv1.Rows.Clear();
            for (int idx = 0; idx < dt.Rows.Count; idx++)
            {
                DataRow r = dt.Rows[idx];
                dgv1.Rows.Add(1);
                dgv1[0, idx].Value = r["deptmt_id"].ToString().Trim();
                dgv1[1, idx].Value = r["deptmt_name"].ToString().Trim();
                dgv1[2, idx].Value = r["deptmt_seq"].ToString().Trim();
                dgv1[3, idx].Value = r["reg_ymdtms"].ToString().Trim();
                dgv1[4, idx].Value = r["mod_ymdtms"].ToString().Trim();
            }
            dgv1.ResumeLayout();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            string sql = "";
            sql += " select";
            sql += "    deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms";
            sql += " from sys_department";
            sql += "   where deptmt_name like '%" + textBox2.Text.Trim() + "%'";

            DataTable dt = mySqlDB.ExecuteReader(sql, mySqlDB.DBConnection());

            dgv1.SuspendLayout();
            dgv1.Rows.Clear();
            for (int idx = 0; idx < dt.Rows.Count; idx++)
            {
                DataRow r = dt.Rows[idx];
                dgv1.Rows.Add(1);
                dgv1[0, idx].Value = r["deptmt_id"].ToString().Trim();
                dgv1[1, idx].Value = r["deptmt_name"].ToString().Trim();
                dgv1[2, idx].Value = r["deptmt_seq"].ToString().Trim();
                dgv1[3, idx].Value = r["reg_ymdtms"].ToString().Trim();
                dgv1[4, idx].Value = r["mod_ymdtms"].ToString().Trim();
            }
            dgv1.ResumeLayout();
        }

        private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Form3 Form3 = new Form3();
            Form3.ShowDialog();
        }
    }
}

Форма2

namespace erpmam
{
    public partial class Form2 : Form
    {
        MySqlConnection connection = new MySqlConnection("datasource =······");
        MySqlCommand command;
        public Form2()
        {
            InitializeComponent();
        }
        public void executeMyQuery(string query)
        {
            try
            {
                openConnection();
                command = new MySqlCommand(query, connection);
                if (command.ExecuteNonQuery() == 1)
                {
                    MessageBox.Show("Query Executed");
                }

                else
                {
                    MessageBox.Show("Query Not Executed");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                closeConnection();
            }
        }
        public void openConnection()
        {
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
        }

        public void closeConnection()
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string insertQuery = "INSERT INTO sys_department(DEPTMT_ID, DEPTMT_NAME, DEPTMT_SEQ, REG_YMDTMS) VALUES(" + textBox1.Text + ',' + textBox2.Text + ','+ textBox3.Text + ','+ "NOW()" +")";
            connection.Open();
            MySqlCommand command = new MySqlCommand(insertQuery, connection);
            try
            {
                if (command.ExecuteNonQuery() == 1)
                {
                    MessageBox.Show("adding normally");
                }
                else
                {
                    MessageBox.Show("error");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            connection.Close();
            this.Close();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

Форма3

namespace erpmam
{
    public partial class Form3 : Form
    {
        MySqlConnection connection = new MySqlConnection("datasource = localhost; port = 3306; Initial Catalog = 'erp'; username = root; password=610822");
        MySqlCommand command;
        public Form3()
        {
            InitializeComponent();
        }
        public void executeMyQuery(string query)
        {
            try
            {
                openConnection();
                command = new MySqlCommand(query, connection);

                if (command.ExecuteNonQuery() == 1)
                {
                    MessageBox.Show("Query Executed");
                }

                else
                {
                    MessageBox.Show("Query Not Executed");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                closeConnection();
            }
        }        public void openConnection()
        {
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
        }
        public void closeConnection()
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }
        private void btn_update_Click(object sender, EventArgs e)
        {
            string updateQuery = " UPDATE sys_department"; 
            updateQuery +=       " SET DEPTMT_NAME = '" + textBox2.Text + "', DEPTMT_SEQ = '" + textBox3.Text + "', mod_ymdtms = NOW()";
            updateQuery +=       " where DEPTMT_ID = '" + textBox1.Text + "'";
            connection.Open();
            MySqlCommand command = new MySqlCommand(updateQuery, connection);
            try
            {
                if (command.ExecuteNonQuery() == 1)
                {
                    MessageBox.Show("changed normally");
                }
                else
                {
                    MessageBox.Show("error");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            connection.Close();
            this.Close();
        }
        private void btn_delete_Click(object sender, EventArgs e)
        {
            string deleteQuery = " DELETE from sys_department"; 
            deleteQuery +=       " where DEPTMT_ID = '" + textBox1.Text + "' or DEPTMT_NAME = '" + textBox2.Text + "' or DEPTMT_SEQ = '" + textBox3.Text + "'" ;
            connection.Open();
            MySqlCommand command = new MySqlCommand(deleteQuery, connection);
            try
            {
                if (command.ExecuteNonQuery() == 1)
                {
                    MessageBox.Show("adding normally");
                }
                else
                {
                    MessageBox.Show("error");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            connection.Close();
            this.Close();
        }
        private void btn_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    } 
}

Ответы [ 2 ]

0 голосов
/ 03 августа 2020

Просто вы можете создать метод stati c в классе form3 и принять один аргумент от типа DataGridView, вызвать этот метод из form1 и передать dg1 после заполнения его строками, тогда вы можете получить к нему доступ сейчас из этого stati c метод ...

private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e) {
      Form3 Form3 = new Form3();
      Form3.staticMethodToPassDGVBetweenTwoForms(dgv1);
      Form3.ShowDialog();
}

namespace erpmam {

     public partial class Form3 : Form {
     public Form3() {
        initializeComponent();
     }

     public static void staticMethodToPassDGVBetweenTwoForms(DataGridView dgv1){
       //do anything with dg1 now
     }
}
0 голосов
/ 03 августа 2020

Просто вы можете создать глобальную переменную Datatabl e, чтобы использовать ее в качестве источника данных, и вы можете использовать ее где угодно в вашем Forms

Это глобальный класс

//make sure to import this System.Data
using System.Data;

class Global
 {
    private static DataTable source;
    public static DataTable Source
    {
        get
        {
            // Reads are usually simple
            return source;
        }
        set
        {
            // You can add logic here for race conditions,
            // or other measurements
            source = value;
        }
    }
}

В вашей первой форме

string connectString = "datasource=xxxx;port=3306;username=xxxx;password=;database=xxxxx;";
    MySqlConnection conn;
    MySqlCommand comm;
    MySqlDataReader read;
    MySqlDataAdapter adapter;
    Global mySource;

void getData() {
        string query = "Select * from tableName";
        conn = new MySqlConnection(connectString);
        conn.Open();
        comm = new MySqlCommand(query, conn);
        adapter = new MySqlDataAdapter(query, conn);
        DataSet ds = new DataSet();
        adapter.Fill(ds);
        
        //setting up
        Global.Source = ds.Tables[0];

        dataGridView1.DataSource = ds.Tables[0];
        conn.Close();

    }

Во второй форме

 public Form2()
    {
        InitializeComponent();
        dataGridView1.DataSource = Global.Source;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...