DOTNET开发之窗体间的传值转化操作
好想把自己最近学到的知识写下来和各位朋友分享,也希望得到大神的指点。今天终于知道自己要写点什么,就是关于WPF开发时简单的界面传值与简单操作。
涉及两个界面:一个界面用于显示所有信息;另一个界面在单击第一个界面的某个按钮后自动弹出,可执行相应的操作,如简单的增删改查数据。
可进行数据的插入删除各种操作。此列中好的一点就是有两个字段可以为空(出生日期和爱好)。在插入数据库的时候要进行判断和转换。这是一个亮点。希望对各位有所帮助。
第一个窗体的前段代码如下:
<DockPanel >
<ToolBar DockPanel.Dock="Top" Height="30">
说明:ToolBar为工具栏控件
<Button x:Name="btnAdd" Click="btnAdd_Click" >
<Image Source=" add.ico"></Image>
</Button>
<Button x:Name="btnDel" Click="btnDel_Click" >
<Image Source="delete.ico"></Image>
</Button>
<Button x:Name="btnEdit" Click="btnEdit_Click" >
<Image Source="edit.ico"></Image>
</Button>
</ToolBar>
说明:DataGrid为显示数据的表格,AutoGenerateColumns="False"表示不再自动增加列,IsReadOnly="True"是表示只能读,补课修改。Binding="{Binding S_no}"是对个数据进行b绑定,Header="学号"是设置列名
<DataGrid Name="datagrid" AutoGenerateColumns="False" DockPanel.Dock="Top" IsReadOnly="True" >
<DataGrid.Columns >
<DataGridTextColumn Width="100" Header="学号" Binding="{Binding S_no}"></DataGridTextColumn>
<DataGridTextColumn Width="80" Header="姓名" Binding="{Binding S_name}"></DataGridTextColumn>
<DataGridTextColumn Width="50" Header="性别" Binding="{Binding S_sex}"></DataGridTextColumn>
<DataGridTextColumn Width="150" Header="出生日期" Binding="{Binding S_birthday}"></DataGridTextColumn>
<DataGridTextColumn Width="100" Header="专业" Binding="{Binding S_dept}"></DataGridTextColumn>
<DataGridTextColumn Width="100" Header="爱好" Binding="{Binding S_love}"></DataGridTextColumn>
<DataGridTextColumn Width="80" Header="是否党员" Binding="{Binding S_isCommie}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
后台绑定代码如下:
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
Load();
}
private void Load()
{
说明:窗体加载时对表格赋值,使得打开窗口时,表格中是已经存在的信息
datagrid.ItemsSource = StudentDAO.SelectAll();
}
//添加信息按钮
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
说明:创建一个新的窗体对象
MainWindow mw = new MainWindow();
mw.IsInsert = true;//传递按下的按钮信息
if (mw.ShowDialog() ==true)//判断是按下了打开新窗体的那个按钮(保存还是取消),用来作出不同的响应,若是保存,则重新加载数据,若是取消,则不变。
{
Load();
}
}
//删除信息按钮
private void btnDel_Click(object sender, RoutedEventArgs e)
{
StudentModel st = (StudentModel)datagrid.SelectedItem;
if (st == null)
{
MessageBox.Show("请选择要删除的行");
return;
}
说明:MessageBox.Show ("提醒","确定要删除吗?",MessageBoxButton.YesNo)==MessageBoxResult .Yes的判断是一个亮点,是否真的删除???
if (MessageBox.Show ("提醒","确定要删除吗?",MessageBoxButton.YesNo)==MessageBoxResult .Yes )
{
StudentDAO.DeleteById(st.S_no);
Load();
}
}
//编辑信息按钮
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
说明: 把选定行的信息赋值给学生的实体类对象
StudentModel st = (StudentModel )datagrid.SelectedItem;
if (st==null)
{
MessageBox.Show("请选择要编辑的行");
return;
}
MainWindow mw = new MainWindow();
mw.IsInsert = false;
mw.id =st.S_no;
if (mw.ShowDialog()==true)
{
Load();
}
}
以下是第二个窗体的主界面的后台操作代码:
private bool isInsert;
/// <summary>
/// 传递信息,说明按下了那个按钮,将执行那个事件
/// </summary>
public bool IsInsert
{
get { return isInsert; }
set { isInsert = value; }
}
public int id;
说明:这个类是对学生实体类赋值的一个重构
private StudentModel InsertIntoStudent()
{
//StudentModel st=null;
int s_no;
string s_name;
string s_sex;
DateTime? s_birthday;
string s_love;
string s_dept;
bool s_isCommie;
s_no = Convert.ToInt32(txtSno.Text);
s_name = txtName.Text;
if (m.IsChecked == true)
{
s_sex = "男";
}
else
{
s_sex = "女";
}
if (txtBir.Text.Trim() == "")
{
s_birthday = null;
}
else
{
s_birthday = Convert.ToDateTime(txtBir.Text);
}
if (txtLove.Text == "")
{
s_love = null;
}
else
{
s_love = txtLove.Text;
}
s_dept = txtDept.Text;
if (y.IsChecked == true)
{
s_isCommie = true;
}
else
{
s_isCommie = false;
}
StudentModel st = new StudentModel(s_no, s_name, s_sex, s_birthday, s_love, s_dept, s_isCommie);
return st;
}
保存按钮的行为
private void BtnSave_Click(object sender, RoutedEventArgs e)
{
if (isInsert)
{
说明:对数据的增加
StudentModel st = InsertIntoStudent();
//StudentModel st = (StudentModel)grid.DataContext;
bool b = StudentDAO.InsertIntoStudent(st);
if (b)
{
MessageBox.Show("插入成功");
}
else
{
MessageBox.Show("插入失败");
}
}
else
{
修改数据
StudentModel st = StudentDAO.SelectById(id);
st = InsertIntoStudent();
StudentDAO.UpdateById(st);
}
DialogResult = true;
}
private void BtnCancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
说明:当窗体打开时进行对数据的加载;增强用户体验
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
txtName.Focus();//窗口打开时让第一个获得焦点
if (isInsert)
{
//这是添加,所以什么都不必做
//StudentModel st = new StudentModel();
//st.S_dept = "软件工程";
//grid.DataContext = st;
}
else
{
//这是编辑,要把选择编辑的值显示出来,便于修改
StudentModel st = StudentDAO.SelectById(id);
txtSno.Text = st.S_no.ToString();
txtName.Text = st.S_name;
txtBir.Text = st.S_birthday.ToString();
txtDept.Text = st.S_dept;
txtLove.Text = st.S_love;
if (st.S_sex == "男")
{
m.IsChecked = true;
}
else
{
f.IsChecked = true;
}
if (st.S_isCommie == true)
{
y.IsChecked = true;
}
else
{
n.IsChecked = true;
}
}
}
这就是两个界面的前段和后台代码,其实在学习的过程中有好多问题,总想把他们写下来,与同道中人共同切磋。
下面就说一下DAL层代码和Model层代码。
MODEL层如下:
namespace 三层架构.Model
{
public class StudentModel
{
private int s_no;
/// <summary>
/// 学号(为主键,不可以为空)
/// </summary>
public int S_no
{
set { s_no = value; }
get { return s_no; }
}
private string s_name;
/// <summary>
/// 学生姓名(不可以为null)
/// </summary>
public string S_name
{
set{s_name=value;}
get {return s_name;}
}
private string s_sex;
/// <summary>
/// 学生性别(不可以为null)
/// </summary>
public string S_sex
{
set { s_sex = value; }
get { return s_sex; }
}
private DateTime? s_birthday;
/// <summary>
/// 学生出生日期(可以为null)
/// </summary>
public DateTime? S_birthday
{
set { s_birthday = value; }
get { return s_birthday; }
}
private string s_love;
/// <summary>
/// 学生兴趣爱好(可以为null)
/// </summary>
public string S_love
{
set { s_love = value; }
get { return s_love; }
}
private string s_dept;
/// <summary>
/// 学生的专业(不可以为null)
/// </summary>
public string S_dept
{
set { s_dept = value; }
get { return s_dept; }
}
private bool s_isCommie;
/// <summary>
/// 该生是非为党员(数据库里为bit类型(即0为true 1为false))不能为空
/// </summary>
public bool S_isCommie
{
set { s_isCommie = value; }
get { return s_isCommie; }
}
public StudentModel(){ }
/// <summary>
/// 学生模板类构造函数
/// </summary>
/// <param name="s_no">学号</param>
/// <param name="s_name">姓名</param>
/// <param name="s_sex">性别</param>
/// <param name="s_birthday">生日</param>
/// <param name="s_love">爱好</param>
/// <param name="s_dept">系别</param>
/// <param name="s_isCommie">是否是党员</param>
public StudentModel(int s_no, string s_name, string s_sex, DateTime? s_birthday, string s_love, string s_dept, bool s_isCommie)
{
this.s_no = s_no;
this.s_name = s_name;
this.s_sex = s_sex;
this.s_birthday = s_birthday;
this.s_love = s_love;
this.s_dept = s_dept;
this.s_isCommie =s_isCommie;
}
}
}
SQLHELPER类如下:
class SqlHelper
{
//连接数据库字符串
private static string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
//private static SqlConnection conn = null;
//private static SqlCommand cmd = null;
//private static SqlDataReader reader = null;
////完成对学生表的增删改查(注意可空字段的处理)
//public SqlHelper()
//{
// string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
// conn = new SqlConnection(connStr);
//}
///// <summary>
///// 判断数据链接是否打开,若是关闭状态,则打开后将连接返回
///// </summary>
///// <returns>conn</returns>
//private static SqlConnection Getconn()
//{
// if (conn.State== ConnectionState.Closed)
// {
// conn.Open();
// }
// return conn;
//}
///// <summary>
///// 执行带参数的sql语句的ExecuteNonQuery查找函数
///// </summary>
///// <param name="sql">sql语句</param>
///// <param name="paras">可变参数集合</param>
///// <returns>DataTable表格式结果</returns>
public static DataTable ExecuteQuery(string sql, params SqlParameter[] paras)
{
using (SqlConnection conn=new SqlConnection (connStr))
{
conn.Open();
using (SqlCommand cmd=conn.CreateCommand ())
{
DataTable dt = new DataTable();
//cmd = Getconn().CreateCommand();
cmd.CommandText = sql;
//将参数数组添加进sql
cmd.Parameters.AddRange(paras);
SqlDataAdapter reader = new SqlDataAdapter(cmd);
reader.Fill(dt);
return dt;
}
}
}
/// <summary>
/// 执行带参数的sql语句,ExecuteNonQuery函数科完成五返回值的插入,删除,更新等操作。
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <returns></returns>
public static int ExecuteNonQuery(string sql, params SqlParameter[] paras)
{
using (SqlConnection conn=new SqlConnection (connStr))
{
conn.Open();
using (SqlCommand cmd=conn.CreateCommand ())
{
//cmd = Getconn().CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddRange(paras);
return cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// 判断输入的字符串是否为null
/// </summary>
/// <param name="sender">传入的字段值</param>
/// <returns>返回处理后的值</returns>
public static object ToDBValue(object sender)
{
if (sender == null)
{
return DBNull.Value;
}
else
{
return sender;
}
}
/// <summary>
/// 判断从数据库中取出的数据是否为NULL,若是NULL则应该转化为C#中的null,否则直接传值
/// </summary>
/// <param name="sender">传入的值</param>
/// <returns>返回的判断结果</returns>
public static object FromDBValue(object sender)
{
if (sender == DBNull.Value)
{
return null;
}
else
{
return sender;
}
}
}
DAO层的代码段及功能说明
class StudentDAO
{
#region 获得学生实体类对象(对方法的重构)
/// <summary>
/// 获得学生实体类对象
/// </summary>
/// <param name="item">DataTable类的行</param>
/// <returns>实体类对象</returns>
public static StudentModel ToStudent(DataRow item)
{
StudentModel st = new StudentModel();
st.S_no = (int)item["S_no"];
st.S_name = (string)item["S_name"];
st.S_sex = (string)item["S_sex"];
st.S_birthday = (DateTime?)SqlHelper.FromDBValue(item["S_birthday"]);
st.S_love = (string)SqlHelper.FromDBValue(item["S_love"]);
st.S_dept = (string)item["S_dept"];
st.S_isCommie = (bool)item["S_isCommie"];
return st;
}
#endregion
#region 根据学生的学号查找学生SelectById(int s_no)
/// <summary>
/// 根据学生的学号查找学生
/// </summary>
/// <param name="id">学号(s_no)</param>
/// <returns>学生类的实体</returns>
public static StudentModel SelectById(int s_no)
{
StudentModel st = new StudentModel();
string sql = "select * from T_studentInfo where S_no=@s_no";
SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@s_no", s_no) };
DataTable dt = SqlHelper.ExecuteQuery(sql, paras);
if (dt.Rows.Count <= 0)
{
return null;
}
if (dt.Rows.Count > 1)
{
throw new Exception("该生学号重复了");
}
else
{
DataRow item=dt.Rows[0];
return ToStudent(item);
}
}
#endregion
#region 将学生信息插入数据库InsertIntoStudent(StudentModel st)
/// <summary>
/// 将学生信息插入数据库
/// </summary>
/// <param name="st">学生实体类对象</param>
/// <returns>是否插入成功(true/false)</returns>
public static bool InsertIntoStudent(StudentModel st)
{
bool flag = false;
string sql = @"insert into T_studentInfo(S_no,S_name ,S_sex ,S_birthday ,S_love ,S_dept ,S_isCommie)
values(@S_no,@S_name ,@S_sex ,@S_birthday ,@S_love ,@S_dept ,@S_isCommie)";
SqlParameter[] paras = new SqlParameter[]
{
new SqlParameter ("@S_no",st.S_no ),
new SqlParameter ("@S_name",st.S_name ),
new SqlParameter ("@S_sex",st.S_sex ),
new SqlParameter ("@S_birthday",SqlHelper .ToDBValue ( st.S_birthday) ),
new SqlParameter ("@S_love",SqlHelper .ToDBValue( st.S_love)),
new SqlParameter ("@S_dept",st.S_dept ),
new SqlParameter ("@S_isCommie",Convert.ToInt32 (st.S_isCommie))
};
int res = SqlHelper.ExecuteNonQuery(sql, paras);
if (res > 0)
{
flag = true;
}
return flag;
}
#endregion
#region 根据学号修改学生信息UpdateById(StudentModel st)
/// <summary>
/// 根据学号修改学生信息UpdateById(StudentModel st)
/// </summary>
/// <param name="st">学生实体类对象</param>
/// <returns>是否更新成功(true/false)</returns>
public static bool UpdateById(StudentModel st)
{
bool flag = false;
string sql = @"update T_studentInfo set S_name=@name,S_sex =@sex,S_birthday=@birthday,
S_love=@love,S_dept=@dept,S_isCommie=@isCommie where S_no=@s_no";
SqlParameter[] paras = new SqlParameter[]
{
new SqlParameter ("@s_no",st.S_no ),
new SqlParameter ("@name",st.S_name ),
new SqlParameter ("@sex",st.S_sex ),
new SqlParameter ("@birthday",SqlHelper .ToDBValue ( st.S_birthday) ),
new SqlParameter ("@love",SqlHelper .ToDBValue ( st.S_love) ),
new SqlParameter ("@dept",st.S_dept ),
new SqlParameter ("@isCommie",Convert.ToInt32 (st.S_isCommie))
};
int res = SqlHelper.ExecuteNonQuery(sql,paras);
if (res>0)
{
flag = true;
}
return flag;
}
#endregion
#region 获得所有学生实体类的对象数组 public static StudentModel[] SelectAll()
/// <summary>
/// 获得所有学生实体类的对象数组
/// </summary>
/// <returns>返回学生实体类的对象数组</returns>
public static StudentModel[] SelectAll()
{
string sql = "select * from T_studentInfo";
DataTable dt = SqlHelper.ExecuteQuery(sql);
StudentModel[] st = new StudentModel[dt.Rows.Count];
for(int i=0;i<dt.Rows.Count ;i++ )
{
st[i] = ToStudent(dt.Rows[i]);
}
return st;
}
#endregion
#region 根据学号删除该学生的记录DeleteById(string s_no)
/// <summary>
/// 根据学号删除该学生的记录DeleteById(string s_no)
/// </summary>
/// <param name="s_no">学号</param>
/// <returns>返回是否删除</returns>
public static bool DeleteById(int s_no)
{
bool flag = false;
string sql = "delete T_studentInfo where S_no=@s_no";
SqlParameter []paras=new SqlParameter []{
new SqlParameter ("@s_no",s_no)
};
int i = SqlHelper.ExecuteNonQuery(sql,paras);
if (i>0)
{
flag= true;
}
return flag;
}
#endregion
}