从新表单

时间:2017-12-19 09:26:37

标签: c# winforms datagridview

我有一个程序在Form1上使用dataGridView来显示SQL Server数据库中的数据。

用户还可以从Form1 dataGridView编辑数据并将数据保存回DB。

但是,我还有一个搜索功能,它会弹出一个新表格并显示搜索结果。

我希望用户能够直接从新窗口保存,但目前它只是更新Form1 dataGridView中的数据。

这是我用来显示搜索结果的内容。

private void ResultsFunc()
    {
        var ColumnToSearch = comboBox1.Text;

        if (textBox1.Text.Length == 0)
        {
            var toSearchBy = listBox1.SelectedItem.ToString();
            aSH_ORDER_DBDataSet1.ASH_PROD_ORDERS.DefaultView.RowFilter = ColumnToSearch + " = " + "'" + toSearchBy + "'";
        }
        else if (textBox1.Text.Length > 0)
        {
            var toSearchBy = textBox1.Text;
            aSH_ORDER_DBDataSet1.ASH_PROD_ORDERS.DefaultView.RowFilter = ColumnToSearch + " = " + "'" + toSearchBy + "'";
        }

        Form2 resultsForm = new Form2();
        resultsForm.dataGridView2.DataSource = aSH_ORDER_DBDataSet1.ASH_PROD_ORDERS.DefaultView;
        resultsForm.Show();
    }

这是我用来尝试从Form2保存数据的原因:

private void button1_Click(object sender, EventArgs e)
    {
        aSH_PROD_ORDERSTableAdapter.Update(aSH_ORDER_DBDataSet1);
    }

如何将在Form2中输入的信息直接保存到数据库而不是仅仅更新Form1中的dataGridView?

1 个答案:

答案 0 :(得分:0)

您是否尝试过SqlBulkCopy,它可以将数据更新到SQLServer 但请确保您在数据表中有必要的列和架构

protected void Button1_Click(object sender, EventArgs e)  
{  
    try  
    {  
        string cs = ConfigurationManager.ConnectionStrings["SchoolConnectionString"].ConnectionString;  
        using (SqlConnection sqlConn = new SqlConnection(cs))  
        {  
            DataSet ds = aSH_ORDER_DBDataSet1;  
            DataTable dtStudentMaster = ds.Tables["Student"]; 
            //  ds.Tables["Student"], if aSH_ORDER_DBDataSet1 has multiple tables in it specify the table name else ds.Tables[0] is fine
            sqlConn.Open();  
            using (SqlBulkCopy sqlbc = new SqlBulkCopy(sqlConn))  
            {  
                sqlbc.DestinationTableName = "StudentMaster"; 
                // StudentMaster - Table need to be updated in SQLServer
                // Make sure you have the similar column names and datatype in both datatable and sql server table
                sqlbc.ColumnMappings.Add("Name", "Name");  
                sqlbc.ColumnMappings.Add("Phone", "Phone");  
                sqlbc.ColumnMappings.Add("Address", "Address");  
                sqlbc.ColumnMappings.Add("Class", "Class");  
                sqlbc.WriteToServer(dtStudentMaster);  
                Response.Write("Bulk data stored successfully");  
            }  
        }  
    }  
    catch (Exception ex)  
    {  
        throw ex;  
    }  
}