【问题标题】:Save data from two forms into same table in Winforms application将两个表单中的数据保存到 Winforms 应用程序中的同一个表中
【发布时间】:2020-12-12 05:08:48
【问题描述】:

我有两个 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-studio winforms


【解决方案1】:

您可以像这样在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;
                }
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多