前台HTML代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> </div> <h1>添加商品</h1> <asp:Button ID="Button1" runat="server" Text="姓名" /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /> <br /> <br /> <asp:Button ID="Button2" runat="server" Text="价格" /> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <br /> <br /> <br /> <asp:Button ID="Button3" runat="server" Text="添加" OnClick="Button3_Click" /> <asp:Button ID="Button4" runat="server" OnClick="Button4_Click" Text="随机" /> <br /> </form> </body> </html>
后台C#代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button3_Click(object sender, EventArgs e) { //取值 string name = TextBox1.Text; decimal price = Convert.ToDecimal(TextBox2.Text); TestDataContext context = new TestDataContext(); string code = ""; //流水号的格式 取当前的日期时间 取出他的年月日 //查商品表有没有Code if (context.ShangPin.Count() == 0) { code = DateTime.Now.ToString("yyyyMMdd") + "001"; } else { //找到数据库Code列最大的数据 截取后三位+1 string max = context.ShangPin.Max(p=>p.Code); //截取字符串 string max1 = max.Substring(8,3); //截取字符串 string rq = max.Substring(8); if (rq == DateTime.Now.ToString("yyyyMMdd")) //如果想等 就是同一天 { //转成整型 int max2 = Convert.ToInt32(max1);// 若果是同一天 执行 max2 = max2 + 1; if (max2 < 10) { code = DateTime.Now.ToString("yyyyMMdd") + "00" + max2; } else if (max2 < 100) { code = DateTime.Now.ToString("yyyyMMdd") + "0" + max2; } else { code = DateTime.Now.ToString("yyyyMMdd") + max2; } } //执行到这 else //不是同一天 重新开始 { code = DateTime.Now.ToString("yyyyMMdd") + "001"; } } //添加数据 先造一个ShangPin对象 ShangPin data = new ShangPin(); //赋值 data.Code = code; data.Name = name; data.Price = price; context.ShangPin.InsertOnSubmit(data); context.SubmitChanges(); } protected void Button4_Click(object sender, EventArgs e) { TestDataContext context = new TestDataContext(); string name = TextBox1.Text; decimal price = Convert.ToDecimal(TextBox2.Text); //定义一个随机数 Random rd = new Random(); //生成1000以内的以为随机数 string code = DateTime.Now.ToString("yyyyMMddHHmmss")+rd.Next(1000); //添加数据 先造一个ShangPin对象 ShangPin data = new ShangPin(); //赋值 data.Code = code; data.Name = name; data.Price = price; context.ShangPin.InsertOnSubmit(data); context.SubmitChanges(); } }
SQL显示:
时间: 2024-11-05 14:52:30