首页 > 解决方案 > 将两个表单中的数据保存到 Winforms 应用程序中的同一个表中

问题描述

我有两个 Winform,其中表单 1 用于输入前七个字段的数据,其他表单用于输入后三个字段,我将表存储在 SQL Server 中,但问题是每当我尝试在第二个字段中保存数据时表单它被存储在第一行本身而不是第一个表单正在更新的行中。谁能帮助如何链接这两个表格并将它们保存在同一行中?

这是以第二种形式保存数据的代码,并附上截图:

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using System.Windows.Forms;  
using System.Data.SqlClient;  

namespace Windows  
{  
    public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
        }  
          
        private void btnInsert_Click(object sender, EventArgs e)  
        {  
            SqlConnection con = new SqlConnection(cs);  
            SqlCommand cmd;  
            con.Open();  
            string s="insert into Student values(@p1,@p2,@p3)";  

            cmd = new SqlCommand(s,con);  
            cmd.Parameters.AddWithValue("@p1",rejectReason1ComboBox.Text);  
            cmd.Parameters.AddWithValue("@p2",rejectReason2ComboBox.Text);  
            cmd.Parameters.AddWithValue("@p3",rejectReason3ComboBox.Text);  
            cmd.CommandType = CommandType.Text;  

            int i = cmd.ExecuteNonQuery();  
            con.Close();  

            MessageBox.Show(i+ " Row(s) Inserted ");  
        }  
    }  
}  

在此处输入图像描述

标签: c#visual-studiowinforms

解决方案


您可以ChildForm像这样添加公共属性:

public string Reason1 {get; set;}
public string Reason2 {get; set;}

private void Combobox1_SelectedIndexChanged(object sender, EventArgs e)
{
     Reason1 = (sender as ComboBox).SelectedItem.ToString();
}

private void ButtonOK_Click(object sender, EventArgs e)
{
     (sender as Button).DialogResult = DialogResult.OK;
     // Or you can set this DialogResult property from Button's property window
}

然后在ParentForm,使用ChildForm这样的

private void ButtonOpenChildForm_Click(object sender, EventArgs e)
        {
            using (ChildForm form = new ChildForm())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    // Receive the Reasons here in any variable
                    string reason1 = form.Reason1;
                    string reason2 = form.Reason2;
                }
            }
        }

推荐阅读