Generate Auto ID With Prefix
There are several way to generate auto id. Here is a method for generating auto ID from program. By providing prefix, data table with/without data and column name from program, it will return a new ID with prefix. For example...
First we need to fill a data table by selecting an sql table. Then call this method by passing the parameters ---
getNewIdWithPrefix("CUS-", dataTable, "customerID");
It will return 'CUS-00001'
--------------ID Generating Method---------------
public static string getNewIdWithPrefix(string prefix, DataTable dt, string columnName)
{
string newId = string.Empty;
int maxId = 0;
if (dt.Rows.Count > 0)
{
DataTable idTable = new DataTable();
idTable.Columns.Add("id", typeof(int));
foreach (DataRow dtRow in dt.Rows)
{
DataRow dr = idTable.NewRow();
if (dtRow[columnName].ToString().Contains(prefix))
{
dr["id"] = int.Parse(dtRow[columnName].ToString().Substring(prefix.Length));
idTable.Rows.Add(dr);
}
else
{
dr["id"] = 0;
idTable.Rows.Add(dr);
}
}
maxId = (int)idTable.Compute("MAX(id)", "") + 1;
}
else
{
maxId = 1;
}
newId = prefix + maxId.ToString("#00000");
return newId;
}
First we need to fill a data table by selecting an sql table. Then call this method by passing the parameters ---
getNewIdWithPrefix("CUS-", dataTable, "customerID");
It will return 'CUS-00001'
--------------ID Generating Method---------------
public static string getNewIdWithPrefix(string prefix, DataTable dt, string columnName)
{
string newId = string.Empty;
int maxId = 0;
if (dt.Rows.Count > 0)
{
DataTable idTable = new DataTable();
idTable.Columns.Add("id", typeof(int));
foreach (DataRow dtRow in dt.Rows)
{
DataRow dr = idTable.NewRow();
if (dtRow[columnName].ToString().Contains(prefix))
{
dr["id"] = int.Parse(dtRow[columnName].ToString().Substring(prefix.Length));
idTable.Rows.Add(dr);
}
else
{
dr["id"] = 0;
idTable.Rows.Add(dr);
}
}
maxId = (int)idTable.Compute("MAX(id)", "") + 1;
}
else
{
maxId = 1;
}
newId = prefix + maxId.ToString("#00000");
return newId;
}
Thanks for nice and effective solution...
ReplyDelete