txtjinghuo_id.Text = ReceiptNumber.AutoCreatID("CG", "CaiGouInfo", "jinhuo_id"); 下面是AutoCreatID()方法: public static string AutoCreatID(string flag, string TableName, string FieldName) { string dbDateTime = GetServerSysDate("yyyyMMdd"); string Str = "select max(" + FieldName + ") id from " + TableName;//查询表中的字段 object obj = StockManageSystemDAL.DbHelperSQL.GetSingle(Str);//把查询字符串Str放到GetSingle()中执行查询(Command)并返回查询结果(对象) string maxID = ""; if (obj != null)//返回(查询字符串)对象 maxID = StockManageSystemDAL.DbHelperSQL.GetSingle(Str).ToString(); string Result = ""; if (maxID == "")//没有最大编号 { Result = flag + dbDateTime + "0001";//CG200902250001 } else { //截取字符 string strFirstEight = maxID.Substring(2, 8); string strLastFour = maxID.Substring(10, 4); if (dbDateTime == strFirstEight)//截取的最大编号(20090225)是否和数据库服务器系统时间相等 { string strNewFour = (Convert.ToInt32(strLastFour) + 1).ToString("0000");//0000+1 Result = flag + dbDateTime + strNewFour;//CG200902250001 } else { Result = flag + dbDateTime + "0001"; } } return Result; } 现在这个是连接数据库的方法: protected readyonly static string connectionString = @"Data Source=;Initial Catalog=;Userid=;Password="; public static object GetSingle(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw new Exception(e.Message); } } } }