通过代码手动生成唯一ID. [英] Generating Unique ID manually through code.

查看:93
本文介绍了通过代码手动生成唯一ID.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



您能给我发送用于通过代码手动生成唯一ID的代码吗,该代码是前缀字符串的组合,该字符串是常量,后缀数字,每次注册都在增加.
例如,
我想通过代码生成ID.谁的输出应该如下,

org001
org002
org003等...

在此先感谢.

Hi,

Can you please send me the code for generating the Unique ID manually through code which is combination of prefixed string which is constant and postfixed by number which is increasing at each time of registration.

For Example,
I want to generate the Id through code. Whose output should be as follows,

org001
org002
org003 etc...

Thanks in advance.

推荐答案

的代码很简单:只需增加一个计数器,并使用固定的前缀和计数器的当前值正确格式化字符串,例如
The code for that is trivial: just increment a counter and properly format a string with the fixed prefix and the current value of the counter, e.g.
string newID(string prefix)
{
  counter++;
  return prefix + counter.ToString("D3");
}



但是counter必须是永久,也就是说,如果需要在应用程序重新启动时保持唯一性,则必须将其保存到文件中.



However counter needs to be persistent, that is you have to save it to a file if you need to maintain uniqueness on application restarts.


SqlConnection cnn = new SqlConnection(your connection String);
    SqlCommand cmd;
    static string path;

    protected void Page_Load(object sender, EventArgs e)
    {

     
        cnn.Open();
       
        string str = "Select count(*) from  tablename";
        cmd = new SqlCommand(str, cnn);
        object necd;
        int newecd;
        cmd = new SqlCommand(str, cnn);
        necd = cmd.ExecuteScalar();
        newecd = Convert.ToInt16(necd) + 1;
        string necode;
        necode = "org00"  + newecd.ToString();
        txtccode.Text = necode.ToString();
        cnn.Close();
    }



这段代码可以帮助您.....



may this code help you.....


尝试这样的

try like this

con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
     da = new SqlDataAdapter("select id from sample order by id desc", con);
      ds = new DataSet ();
      da.Fill(ds);


      string orgname = "AAA";
      if (ds.Tables[0].Rows.Count > 0)
      {
          i = Convert.ToInt32(ds.Tables[0].Rows[0][0].ToString());
          i = i + 1;
      }
      else { i = 1; }
      string empname = orgname + Convert.ToString(i);

     if(con.State ==ConnectionState.Closed )
         con.Open ();
     cmd = new SqlCommand("insert into sample(id,name,address) values('" + empname + "','" + txtname.Text + "','" + txtaddr.Text + "')", con);
     int j = cmd.ExecuteNonQuery();
     con.Close();


这篇关于通过代码手动生成唯一ID.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆