c# Pass data from Data table into another form

橙三吉。 提交于 2020-05-09 15:07:47

问题


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

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

回答1:


You need to send the datatable as a variable in the constructor of the seconde class :

For example .. in your case :

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

Cheers !




回答2:


you can pass the string data to the constructor of Form2. Example:

Form2:

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

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

    }

on Form1:

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



回答3:


Create Global Public Class with DataTable in it

like

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

access it like on Form2

DataTable dt=Globals.Globaldt;


来源:https://stackoverflow.com/questions/28453871/c-sharp-pass-data-from-data-table-into-another-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!