以第二种形式获取数据datagridview

时间:2015-06-12 07:20:11

标签: c# winforms

我有两个forms。在form1中,我有两个comboboxes,它从store procedurebutton中获取两个参数来触发结果。结果应显示在form2中,单击按钮时会显示datagridview

我在form1中的代码(btn事件)。不知道它是否正确

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string C = ConfigurationManager.ConnectionStrings["D"].ConnectionString;
        using (var con = new SqlConnection(C))
        using (var cmd = new SqlCommand())

        {
            SqlDataReader myReader;
            cmd.CommandText = ("[dbo].[spInfo]");
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Periode2", cbPeriode2.SelectedValue.ToString());
            cmd.Parameters.AddWithValue("@Periode1", cbPeriode1.SelectedValue.ToString());
            con.Open();
            myReader = cmd.ExecuteReader();

           if(myReader.HasRows)
            {
                DataTable datatable = new DataTable();
                datatable.Load(myReader);
                //datagridview1.DataSource = datatable;
            }
            con.Close();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    new Form2().ShowDialog();
} 

Form2(formload事件) 我不知道如何在这里获取记录

private void Form2_Load(object sender, EventArgs e)
{           
}

1 个答案:

答案 0 :(得分:0)

将数据从form1传递给form2
来自Form1

private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            string C = ConfigurationManager.ConnectionStrings["D"].ConnectionString;
            using (var con = new SqlConnection(C))
            using (var cmd = new SqlCommand())

            {
                SqlDataReader myReader;
                cmd.CommandText = ("[dbo].[spInfo]");
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Periode2", cbPeriode2.SelectedValue.ToString());
                cmd.Parameters.AddWithValue("@Periode1", cbPeriode1.SelectedValue.ToString());
                con.Open();
                myReader = cmd.ExecuteReader();
                DataTable datatable = new DataTable();    
               if(myReader.HasRows)
                {

                    datatable.Load(myReader);
                    //datagridview1.DataSource = datatable;
                }
                con.Close();
                ShowForm2(datatable);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
}
public void ShowForm2(DataTable yourData)
{
    DataTable Data = yourData;
    Form2 frm = new Form2(Data);
    frm.Show();
}   

在Form2上

public class Form2
{
     public Form2()
     {
        InitializeComponent();
        //Default Consturctor
     }
     private DataTable LocalData;
     public Form2(DataTable Data)
     {
        InitializeComponent();
        LocalData = Data;
     }
     public void Form2_Load(object sender, EventArgs e)
     {
              //Consume LocalData Here
     }
}