c#将数据表中的数据传递到另一种形式 [英] c# Pass data from Data table into another form

查看:62
本文介绍了c#将数据表中的数据传递到另一种形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#极为陌生,如果这是一个新手问题,对不起.

I am extremely new to c# so sorry if this is a newbie question.

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

I have a form with a data grid connecting to a MySQL database.

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

I have made it so it selects the whole row and when you double click on that row it opens a new form.

我现在想做的是在第二个表单中有一些文本框,其中填充了用户在上一个表单中选择的内容.

What I want to do now is have some text boxes in the 2nd form filled with data from what the user selected on the previous form.

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

This is my code so far.

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();
        }
    }

推荐答案

您需要在seconde类的构造函数中将数据表作为变量发送:

You need to send the datatable as a variable in the constructor of the seconde 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();
        }
    }

干杯!

这篇关于c#将数据表中的数据传递到另一种形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆