我想使用 MVC 模式 winforms 将记录添加到数据库中。将记录添加到数据库中的功能正在工作,但我想通过使用对象方法来完成。
有人请我在这里用 MVC 模式做的错误是什么?
看法:
using System;
using System.Data.SqlClient;
using System.Globalization;
using System.Windows.Forms;
using MVCwithDBFormReg.Controller;
using MVCwithDBFormReg.Model;
namespace MVCwithDBFormReg.View
{
public partial class Form1 : Form, IUserView
{
private readonly User _model;
public Form1(User model)
{
_model = model;
InitializeComponent();
}
public event CreateUserHandler Create;
private void button3_Click(object sender, System.EventArgs e)
{
_model.FirstName = FirstName;
_model.LastName = LastName;
_model.Language = Language;
_model.Country = Country;
_model.State = State;
_model.Zipcode = Zipcode;
_model.TimeZone = TimeZone;
_model.Sex = Sex;
_model.Month = Month;
_model.Day = Day;
_model.Year = Year;
_model.Occupation = Occupation;
Create(_model);
}
}
}
模型:
namespace MVCwithDBFormReg.Model
{
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Language{ get; set; }
public string Country{ get; set; }
public string State{ get; set; }
public int Zipcode { get; set; }
public string TimeZone{ get; set; }
public Gender Sex { get; set; }
public enum Gender
{
Male = 1,
Female = 2
}
public string Month { get; set; }
public string Day { get; set; }
public int Year { get; set; }
public string Occupation { get; set; }
}
控制器:
namespace MVCwithDBFormReg.Controller
{
public class UserController
{
private SqlConnection sqlConnection1;
private void ViewOnSave(User model)
{
if (model.FirstName == "" || model.LastName == "")
MessageBox.Show("Please enter your name");
else
{
sqlConnection1.Open();
string insert = "INSERT INTO REGISTER(FNAME, LNAME, LANG, COUNTRY, STATE, ZIPCODE, TIMEZONE, GENDER, BDAY, BMONTH, BYEAR, OCCUPATION) " +
"VALUES ('" + model.FirstName + "','" + model.LastName + "','"
+ model.Language + "','" + model.Country + "','"
+ model.State + "','" + model.Zipcode
+ "','" + model.TimeZone + "','"
+ model.Sex + "','" + model.Day + "','"
+ model.Month + "','" + model.Year + "','"
+ model.Occupation + "')";
SqlCommand cmd = new SqlCommand(insert, this.sqlConnection1);
cmd.ExecuteNonQuery();
sqlConnection1.Close();
MessageBox.Show("You have been successfully registered to our database.");
}
}
}
}