c# 将数据从 Data table 传递到另一种形式

c# Pass data from Data table into another form

我对 c# 非常陌生,如果这是一个新手问题,我很抱歉。

我有一个带有连接到 MySQL 数据库的数据网格的表单。

我做到了,所以它会选择整行,当您双击该行时,它会打开一个新表单。

我现在想要做的是在第二个表单中的一些文本框中填充用户在前一个表单中选择的数据。

到目前为止,这是我的代码。

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string connectionString = "datasource=*****;database=****;username=****;password=****;";
            string query = "select firstname, surname, email from users;";
            MySqlConnection connection = new MySqlConnection(connectionString);
            MySqlCommand command = new MySqlCommand(query, connection);
            connection.Open();
            MySqlDataAdapter adapter = new MySqlDataAdapter();
            adapter.SelectCommand = command;
            DataTable dTable = new DataTable();
            adapter.Fill(dTable);
            dataGridView1.DataSource = dTable;
            connection.Close();
        }

        private void viewData(object sender, DataGridViewCellEventArgs e)
        {
            Form2 secondForm = new Form2();
            secondForm.Show();
        }
    }

您可以将字符串数据传递给Form2的构造函数。示例:

表格 2:

public partial class Form2 : Form
    {
        public Form2()
        {
          ....
        }

        public Form2(string data)
        {
          textBox1.Text=data;
        }

    }

在 Form1 上:

.......
 private void viewData(object sender, DataGridViewCellEventArgs e)
        {
            string mydata=///...
            Form2 secondForm = new Form2(mydata);
            secondForm.Show();
        }

创建全局 Public Class 其中包含 DataTable

喜欢

public static class Globals
{
DataTable Globaldt=new DataTable();
}     

像在 Form2 上一样访问它

DataTable dt=Globals.Globaldt;

您需要在第二个 class 的构造函数中将数据表作为变量发送 class :

例如..在你的情况下:

public partial class Form1 : Form
    {
        public Form1()
        {
          //code that you have already wrote 
          Form2 f2 = new Form2(dTable);
          f2.ShowDialog();
        }
     }
public partial class Form2 : Form
    {
        public Form2(Datatable table)
        {
            //Do whatever you want with this table
            //Example 
            label1.Text = table.Rows[0][0].ToString();
        }
    }

干杯!