开发者

How to auto generate an alpha numeric id in C# using MS Access database?

I have table called emp. The table contains three columns empid, ename and salary. I have to store the empid as autogenerated ids, for example: E001, E002, E003. How can I 开发者_如何学Pythondo that using C#?


If this is not homework:

  • Think about the limitations that this ID naming scheme puts on your data.

  • If those limitations are unacceptable, look for a better mechanism to generate unique IDs. For one thing, is it really necessary to store the letter E along with the number, or could you just make empid a column of type INT and add the E programmatically? If you never actually display the IDs anywhere, consider using e.g. GUIDs (see the documentation of the .NET type System.Guid), as they are guaranteed to be unique (for most practical purposes). Or simply use the auto-increment feature of your DB on the empid column.

If this is homework:

  • Can IDs of deleted records be recycled (reused) with records added later on?

  • Try to locate a method in the .NET framework that formats an integer number with any number of leading zeroes; e.g. 1"001".
    Try also to locate a method in the .NET framework that does the opposite, e.g. "001"1.
    Use these two functions to convert between your Ennn IDs and their numerical parts.

  • Retrieve all existing IDs from the DB table:
    If you cannot recycle IDs, get them in descending order, tell the DB to only return the first entry from that sorted result set, and determine the next larger ID from that returned ID value.
    If you can recycle IDs, get them preferable in ascending order and find the first gap (i.e. when the difference between the numerical parts of two adjacent IDs is greater than 1). Build a new ID so that it falls into this gap.


Some example code snippets:

Format an integer number as an E... string:

int numericPart = 123;   // <-- example input

string empid = numericPart.ToString("'E'000");

Extract the numeric part from an E... string
(using regular expressions, which is actually overkill in your case):

using System.Text.RegularExpressions;
...

string empid = "E123";   // <-- example input

var empidPattern = new Regex(@"^E(?<NumericPart>\d{3})$");

if (empidPattern.IsMatch(empid))
{
    // extract numeric part from key and convert it to int:
    int numericPart = Int32.Parse(
                          empidPattern.Match(empid).Groups["NumericPart"].Value);
}
else
{
    // 'empid' does not represent a valid key (wrong format)
}

Load existing keys from database table into a collection:

using System.Data;

// create a new collection that will hold all empid keys in emp
var empidList = new List<string>();

// open a database connection -- you need to add appropriate code here:
using (IDbConnection db = ...)
{
    // define the query for retrieving all empid keys:
    IDbCommand getEmpidList = db.CreateCommand();
    getEmpidList.CommandType = CommandType.Text;
    getEmpidList.CommandText = "SELECT empid FROM emp ORDER BY empid ASC";

    // execute the query and transfer its result set to the collection:
    using (IDataReader reader = getEmpidList.ExecuteReader())
    {
        while (reader.Read())
        {
            empidList.Add(reader.GetString(0));
        }
    }
}

I'll leave it to yourself to put these pieces together, add the actual logic I described above, and further improve the code.


You could use an autoincremented int column and add the "E" prefix for display purposes only.


public string GetLatestOrderId()
{
    string ReceivedId = string.Empty;
    string displayString = string.Empty;
    String query = "SELECT MAX(OrderReceivedNo) FROM [Order_Received]";
    String data = DataManager.RunExecuteScalar(ConnectionString.Constr, query);
    ReceivedId = data;
    if (string.IsNullOrEmpty(ReceivedId))
    {
        ReceivedId = "OR0000";//It is the start index of alpha numeric value
    }
    int len = ReceivedId.Length;
    string splitNo = ReceivedId.Substring(2, len - 2);//This line will ignore the string values and read only the numeric values
    int num = Convert.ToInt32(splitNo);
    num++;// Increment the numeric value
    displayString = ReceivedId.Substring(0, 2) + num.ToString("0000");//Concatenate the string value and the numeric value after the increment
    return displayString;
}


This my answer,

public string GetLatestOrderId()
        {
            string ReceivedId = string.Empty;
            string displayString = string.Empty;
            String query = "SELECT MAX(OrderReceivedNo) FROM [Order_Received]";
            String data = DataManager.RunExecuteScalar(ConnectionString.Constr, query);
            ReceivedId = data;
            if (string.IsNullOrEmpty(ReceivedId))
            {
                ReceivedId = "OR0000";//It is the start index of alpha numeric value
            }
            int len = ReceivedId.Length;
            string splitNo = ReceivedId.Substring(2, len - 2);//This line will ignore the string values and read only the numeric values
            int num = Convert.ToInt32(splitNo);
            num++;// Increment the numeric value
            displayString = ReceivedId.Substring(0, 2) + num.ToString("0000");//Concatenate the string value and the numeric value after the increment
            return displayString;
        }


        Sql DataAdapter sda = new SqlDataAdapter("select * from emp", con);
        Dataset ds = new DataSet();
        sda.Fill(ds, "emp_id");
        string EmpId;

        //this condition checks that table is empty
        // or not if table is empty that bill id is E0001 other wise else par is run
        if (ds.Tables[0].Rows.Count == 0)
        {
            EmpId = "E0001";
        }
        else
        {
            string s = ds.Tables[0].Rows[ds.Tables[0].Rows.Count - 1]["emp_id"].ToString();
            //retriving empid column last cell data.
            int len = s.Length;
            string splitno = s.Substring(3, len - 3); //spliting string
            int num = Convert.ToInt32(splitno); //converting splited string in integer
            num++; //increasing splited string by 1
            EmpId = s.Substring(0, 3) + num.ToString("0000"); //adding String and store in empid string
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜