一、效果图
二、实现过程
1、model实体类
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace guolei.Model{ public class title { public int id { get; set; } public string tb_title { get; set; } public DateTime add_time { get; set; } }}
2、dal数据访问
/// /// 增加数据,首先要添加引用Model层 /// /// /// public int Add(Model.title model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into title("); strSql.Append("tb_title,add_time)"); strSql.Append(" values ("); strSql.Append("@title,@add_time)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@title", SqlDbType.NVarChar,50), new SqlParameter("@add_time", SqlDbType.DateTime)}; parameters[0].Value = model.tb_title; parameters[1].Value = model.add_time; //添加主表数据 object obj = new SqlHelper().ExecuteScalar(strSql.ToString(), parameters, CommandType.Text); model.id = Convert.ToInt32(obj); return model.id; }
3、web后台代码
#region 增加操作================================= private bool DoAdd() { bool result = false; Model.title model = new Model.title(); model.tb_title = txtTb_title.Text.Trim(); model.add_time = Utils.StrToDateTime(txtAdd_time.Text.Trim(), DateTime.Now); if (new DAL.title().Add(model) > 0) { result = true; } return result; } #endregion //保存 protected void btnSubmit_Click(object sender, EventArgs e) { if (!DoAdd()) { Response.Write(""); return; } else { Response.Write(""); } }
4、sqlhelper数据访问助手类的相关代码
//带参数的获取第1行1列的数据 public object ExecuteScalar(string cmdText, SqlParameter[] paras, CommandType ct) { using (cmd = new SqlCommand(cmdText, Getconn())) { cmd.CommandType = ct; cmd.Parameters.AddRange(paras); object val = cmd.ExecuteScalar(); return val; } }
5、文本转日期格式的代码
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace guolei.Common{ public class Utils { public static DateTime StrToDateTime(string str, DateTime defValue) { if (!string.IsNullOrEmpty(str)) { DateTime dateTime; if (DateTime.TryParse(str, out dateTime)) return dateTime; } return defValue; } }}