简体   繁体   English

带字符串的自动增量ID

[英]Auto increment ID with string

I'm using Access 2000-2003 database for C#. 我将Access 2000-2003数据库用于C#。 I like to have my TypeID to have a unique id as CHHTP001 , CHHTP002 and etc, and display the id in TextBox before inserting new value in the database. 我希望我的TypeID具有唯一的ID,例如CHHTP001CHHTP002等,并在将新值插入数据库之前在TextBox显示该ID。

public void generateRateID()
{
     string id;
     con.Open();
     string rate = "SELECT MAX(TypeID) FROM tblRoomTypeRate";
     cmd = new OleDbCommand(rate, con);
     OleDbDataReader dr = cmd.ExecuteReader();
     if (dr.Read())
     {
          id = dr[0].ToString();
          id = id + 1;
          txtRateID.Text = "CHHRT" + id.PadLeft(3, '0');
     }
     con.Close();
}

The display in TextBox is CHHTP001 at first, then CHHTPCHHTP0011 . TextBox的显示首先是CHHTP001 ,然后是CHHTPCHHTP0011 How can I make the CHHTPCHHTP0011 to CHHTP002 and so on? 如何使CHHTPCHHTP0011变为CHHTP002等?

Use Regex . 使用Regex This should works as you want: 这应该可以根据需要工作:

id = dr[0].ToString();//CHHTP001 Or CHHTP111
id = Regex.Replace(id, "\\d+", m => (int.Parse(m.Value) + 1).ToString(new string('0', m.Value.Length)));
txtRateID.Text = id;//CHHTP002 Or CHHTP112

Here is some general guidelines. 这是一些一般准则。

You should create an int variable that records what should be the number. 您应该创建一个int变量来记录应该是什么数字。 That way you can manage your id easily. 这样,您可以轻松管理自己的ID。 When you want to increment your id, just increment the variable. 当您想增加ID时,只需增加变量即可。

When you want to convert the id to a string, first call ToString and PadLeft . 如果要将id转换为字符串,请首先调用ToStringPadLeft Next you just concatenate the string to "CHHTP"! 接下来,您只需将字符串连接到“ CHHTP”! Isn't that easy? 那不容易吗?

Try this: 尝试这个:

{ {

 string id;

 string literal; // "CHHRT" or whatever;

 int sequence;

 con.Open();
 string rate = "SELECT MAX(TypeID) FROM tblRoomTypeRate";
 cmd = new OleDbCommand(rate, con);
 OleDbDataReader dr = cmd.ExecuteReader();
 if (dr.Read())
 {
     id = dr[0].ToString();
     sequence = int.Parse( new string( id.Where( char.IsDigit ).ToArray() ) );
     literal = new string( id.Where( char.IsLetter ).ToArray() );
     id = literal + ( sequence + 1 ).ToString( "000" );                
     txtRateID.Text = id;
 }
 con.Close();

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM