【问题标题】:using same form for insert and edit without having unused variables in c#使用相同的表单进行插入和编辑,而在 c# 中没有未使用的变量
【发布时间】:2018-09-11 09:13:44
【问题描述】:

好的男孩/女孩,我是编程新手,有一个问题。我创建了一个用于将数据插入 sql server 的 winform。现在我想使用相同的表单来更新数据。 在主窗体 frmEmployees 上,我有两个按钮,btnAddEmployee 和 btnUpdateEmployee,我也有 employeeID(我从数据网格中获取 id)和一个名为“isEditMode = true”的布尔变量,现在当我单击 btnUpdateEmployee 时,我将 EmployeeID 和 isEditMode 值发送到重载构造函数..和frmAddEmployee打开..我有全局私有变量employeeID和bool isEditmode..然后我通过重载构造函数设置它们的值,这是工作,但是..当我点击btnAddEmployee时我没有发送employeeID和isEditMode值..我在添加员工时想出了未使用的变量..

private int employeeID;
private bool isEditMode;
public frmAddEmployee()
{
  InitializeComponent();

  this.AutoValidate = AutoValidate.Disable;
    }
public frmAddEmployee(int employeeID, bool isEditMode): this()
{
  this.employeeID = employeeID;
  this.isEditMode = isEditMode;
}

【问题讨论】:

  • 嗨,你能分享更多代码吗?这真的不足以理解你的问题。至少是由您的按钮触发的部分,也许是您的应用程序的屏幕截图,以便轻松可视化您正在解释的内容
  • 你用的是什么sql_

标签: c# winforms


【解决方案1】:

你没有向我们展示很多代码,但我会给你一个很好的例子来说明我如何处理程序和 SQL 数据库之间的通信。

首先我为每个对象创建类。在你的例子中,我看到你有Employee,所以我会创建一个关于我的每个员工和我想为他们拥有的功能的信息(变量)很少的类。所以类看起来像这样:

public class Employee
{
    static string databaseString = "";
    public int Id { get { return _Id; } } //This is property
    public string Name { get { return _Name; } set { _Name = value; } } //This is property

    private int _Id; //This is private variable used by property
    private string _Name; //This is private variable used by property

    public Employee()
    {
        //Constructor used to create empty object
    }

    public Employee(int Id)
    {
        try
        {
            using (SqlConnection con = new SqlConnection(databaseString))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT NAME FROM Employee WHERE ID = @ID", con))
                {
                    cmd.Parameters.AddWithValue("@ID", Id);

                    SqlDataReader dr = cmd.ExecuteReader();

                    //I am usin IF(dr.Read()) instead of WHILE(dr.Read()) since i want to read only first row.
                    if (dr.Read())
                    {
                        this._Id = Id;
                        this._Name = dr[0].ToString();
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("There was no Employee with that ID in database!");
                    }
                }
            }
        }
        catch(SqlException ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString());
        }
    }

    public void Save(bool showMessage)
    {
        using (SqlConnection con = new SqlConnection(databaseString))
        {
            con.Open();
            using (SqlCommand cmd = new SqlCommand("UPDATE Employee SET NAME = @N WHERE ID = @ID", con))
            {
                cmd.Parameters.AddWithValue("@N", this._Name);
                cmd.Parameters.AddWithValue("@ID", this._Id);

                cmd.ExecuteNonQuery();

                if (showMessage)
                    System.Windows.Forms.MessageBox.Show("Employee saved!");
            }
        }
    }

    public static void Create(string Name, bool showMessage = true)
    {
        using (SqlConnection con = new SqlConnection(databaseString))
        {
            con.Open();
            using (SqlCommand cmd = new SqlCommand("INSERT INTO Employee (ID, NAME) VALUES (COALESCE(MAX(ID), 1), @NAME)", con))
            {
                cmd.ExecuteNonQuery();

                if (showMessage)
                    System.Windows.Forms.MessageBox.Show("New Employee created!");
            }
        }
    }
}

现在当我上课时,我可以用两种方式称呼它:

Employee emp = new Employee(); //This will create empty employee object
Employee emp1 = new Employee(1); //This will create employee object and will load employees data from database where employees id == 1

我还能做的是:

Employee.Create("SomeName"); //Calling public static method from Employee class. Doesn't require you to create object for static methods

或者如果我加载了员工并想更改其名称然后保存,我会这样做:

Employee emp2 = new Employee(1); //Created and loaded emp from database
emp2.Name = "Changed Name";
emp2.Save(); //Called public method.

所以现在,如果您有显示一名员工的表单,它将如下所示:

public partial class Form1 : Form
{
    private Employee emp;

    public Form(int EmployeeID)
    {
        InitializeComponents();

        //Creating new object of Employee but with constructor that will automatically load variables into it.
        emp = new Employee(EmployeeID);

        //Checking to see if employee is loaded since if there was no employee with given ID it would return null
        if(emp.Id == null || < 1)
        {
            DialogResult dr = MessageBox.Show("Employee doesn't exist. Do you want to create new one?", "Confirm", MessageBoxButtons.YesNo);
            if(dr == DialogResult.No)
            {
                //User doesn't want to create new employee but since there is no employee loaded we close form
                this.Close();
            }
            else
            {
                Employee.Create("New Employee");
                MessageBox.Show("New employee created");
                //Here we need to load this employee with code like emp = new Employee(newEmployeeId);
                //To get new employee id you have 2 options. First is to create function inside Employee class that will Select MAX(ID) from Employee and return it. (bad solution)
                //Second solution is to return value upon creating new employee so instead function `public static void Create()` you need to have `public static int Create()` so it returns newly created ID of new row in SQL database. I won't explain it since you are new and it will be too much information for now. You will easily improve code later. For now you can use Select Max(id) method
            }
        }

        textBox1.Text = emp.Id;
        textBox2.Text = emp.Name;
    }

    private void OnButton_Save_Click(object sender, EventArgs e)
    {
        DialogResult dr = MessageBox.Show("Do you really want to save changes?", "Save", MessageBoxButtons.YesNo);
        if(dr == DialogResult.Yes)
        {
             emp.Save();
        }
        else
        {
            //Here create private Reload function inside form that will do emp = Employee(emp.Id) and then set UI again.
        }
    }

    private void OnButton_CreateNewEmployee_Click(object sender, EventArgs e)
    {
        Employee.Create("New Employee");

        int newEmpID = something; //As i said up create method to select MAX ID or update SQL inside Create function to return newly created ID

        //I am using using since after form closes it automatically disposes it
        using(Form1 f = new Form1(newEmpID))
        {
            f.showDialog()
        }
        this.Close();
    }
}

【讨论】:

    猜你喜欢
    • 2016-06-17
    • 1970-01-01
    • 2014-05-15
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多