Hi Everyone,

Can I ask your favor, I have a code that I customize.

DBConnect.CS //here ismy db connection

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data;


namespace PAIRDevelopment.Classes
{
    public class DBConnect
    {
        public static string csConnect = "uid=root; database=membership; pooling = false; convert zero datetime=True";
        public static MySqlConnection csCon= new MySqlConnection(Classes.DBConnect.csConnect);

        public MySqlCommand cmdCon = new MySqlCommand();
        public MySqlDataReader reader;

        public void nonQuery(string cmdText)
        {
            cmdCon.Connection = csCon;
            csCon.Open();
            cmdCon.CommandText = cmdText;
            cmdCon.ExecuteNonQuery();
            cmdCon.Dispose();
            csCon.Close();
        }

        public void OPEN(string cmdtext)
        {
            cmdCon.Connection = Classes.DBConnect.csCon;
            Classes.DBConnect.csCon.Open();
            cmdCon.CommandText = cmdtext;
            reader = cmdCon.ExecuteReader();


        }

        public void CLOSE()
        {
            reader.Close();
            cmdCon.Dispose();
            Classes.DBConnect.csCon.Close();
        }


    }

}

Original Code that I Customize:

            string sql = "SELECT MAX(certnumber) FROM Membership.tblpair_institutional_membership";
            MySqlConnection cond = new MySqlConnection("datasource=localhost;port=3306;username=root;password=");
            MySqlCommand cmdDatabase = new MySqlCommand(sql, cond);

            try
            {

                //cond.Open();
                string pcount = Convert.ToString(cmdDatabase.ExecuteScalar());

                if (pcount.Length == 0)
                {
                    cnumber_isnm.Text = "100000000";

                }
                else
                {
                    int pcount1 = Convert.ToInt32(pcount);
                    int pcountAdd = pcount1 + 1;
                    cnumber_isnm.Text = pcountAdd.ToString();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                //cond.Close();

            }

My Customization:

 OpenConCls.OPEN("SELECT MAX(certnumber) FROM Membership.tblpair_institutional_membership");

            while (OpenConCls.reader.Read())
            {
                string pcount = Convert.ToString(OpenConCls.ToString());// here is the problem

                if (pcount.Length == 0)
                {
                    cnumber_isnm.Text = "10000000";
                }
                else 
                {
                    int pcount1 = Convert.ToInt32(pcount);//// here is the problem
                    int pcountAdd = pcount1 + 1;
                    cnumber_isnm.Text = pcountAdd.ToString();
                }

                OpenConCls.CLOSE();

Purpose: auto number;

I want to minimize the DB calling on my form declaration, that's why I created the seperated class for DB connection.

Please give me the suggestion or Idea what is the code for the auto number?

regards,

Darryl

Recommended Answers

All 27 Replies

OpenConCls.ToString() will give you a default object representation because you didn't override ToString. This won't be a string that represents a valid integer, so Convert.ToInt32 fails.

By auto number I assume you mean the result of the query, which would be done like this, if I recall correctly:

 string pcount = OpenConCls.reader[0].ToString();

what is the ciode for

OpenConCls.ToString() will give you a default object representation because you didn't override ToString. This won't be a string that represents a valid integer, so Convert.ToInt32 fails.

By auto number I assume you mean the result of the query, which would be done like this, if I recall correctly:

I tried the code suggestion, I get this error.

MySqlException was unhandled:

  while (OpenConCls.reader.Read()) - "Invalid attempt to Read when reader is closed."

regards,
Darryl

@deceptikon: I got it.

Now, I have a question to create a auto number like this "AN-0000-0000", it is possible to query this on C#?.

Darryl,

Now, I have a question to create a auto number like this "AN-0000-0000", it is possible to query this on C#?.

That looks fairly custom. What does each part represent and how does it change as new values are generated?

it is possible to query on that idea?

purpose of this for Membership Id Numbering System. When the client apply for membership they get a ID Number, start with the Chracter String and the Integer.

I tried to change the Type in the database of the ID, from int to Varchar

 OpenConCls.OPEN("SELECT MAX(piId) FROM tblpair_individual_membership");

            while (OpenConCls.reader.Read())
            {
                string pcount = OpenConCls.reader[0].ToString();

                if (pcount.Length == 0)
                {
                    textBox1.Text = "00000000";
                }
                else
                {

                    int pcount1 = Convert.ToInt32(pcount);
                    int pcountAdd = pcount1 + 1;
                    textBox1.Text = pcountAdd.ToString();
                }

            }

          OpenConCls.CLOSE();

When I click my Button to add the new ID for new Client, the ID will generated like this AN-000000+1 = AN-0000001;

but the code above is working already but sad to say the code implement like this AN-00000000+1 || AN-000000001 next ID will be added a value. AN-0000000011 instead of generated the number, the value will be add another value not to plus the digit "pcount1+1";

Hope you Understand my purpose,

regards,
Darryl

Yup. You need to split the string to extract the number part, convert it to int, add to it, then paste the string back together:

private static string AutoIncrement(string id)
{
    var parts = id.Split('-');

    if (parts != 2)
    {
        // Expected format "XX-dddddddd"
        throw new ArgumentException("Invalid id format");
    }

    int seq;

    if (!int.TryParse(parts[1], out seq))
    {
        throw new ArgumentException("Sequence number must be numeric");
    }

    // Validate the first part if you want

    // Put it all back together into a new ID
    parts[1] = (seq + 1).ToString("00000000");

    return string.Join("-", parts);
}

The conversion to int is the important part because the + operator for string performs concatenation rather than integer addition.

@deceptikon: nice code, but i don't know where can I put this code on my form. sorry im newbie on this.

and what is Type on my db? int or varchar?

I tried the code to code, i put this to my auto number query,

I get this error:

Error 1 Operator '!=' cannot be applied to operands of type 'string[]' and 'int'

if (parts != 2)
{
}

and then I don't whats next to do..

regards.

Darryl

My bad, it should have been if (parts.Length != 2). If code you find online is broken, don't be afraid to troubleshoot it yourself. We're all fallible, after all. ;)

i don't know where can I put this code on my form. sorry im newbie on this.

You'd pull the ID directly from the database, then call AutoIncrement to get a new ID for new records is what I was thinking. Or maintain the most recent ID in your code and update it as necessary for new records For example:

private string _connectionString = "<your connection string>";
private string _lastId = "AN-00000000"; // Default first ID if there are no records

/// <summary>
/// Retrieves the most recent ID from the database.
/// </summary>
private void Form1_Load(object sender, EventArgs e)
{
    using (var connection = new SqlConnection(_connectionString))
    {
        connection.Open();

        using (var cmd = new SqlCommand(connection))
        {
            cmd.SelectCommand = 
                "select top 1 piId" + 
                "from tblpair_individual_membership" +
                "order by piId desc";

            var id = cmd.ExecuteScalar();

            if (id != null)
            {
                _lastId = Convert.ToString(id);
            }
        }
    }
}

/// <summary>
/// Adds a new client to the database
/// <summary>
private void buttonNewClient_Click(object sender, EventArgs e)
{
    var newId = AutoIncrement(_lastId);

    using (var connection = new SqlConnection(_connectionString))
    {
        connection.Open();

        using (var cmd = new SqlCommand(connection))
        {
            cmd.InsertCommand = "insert into tblpair_individual_membership (piId) values (@piId)";
            cmd.Parameters.Add("@piId", SqlDbType.VarChar).Value = newId;

            if (cmd.ExecuteNonQuery() == 1)
            {
                // Only update the last ID on a successful insert
                _lastId = newId;
            }
        }
    }
}

Note that this is very much incomplete and only serves as an idea of what I think you were asking for, which is incrementing the primary key of new records from C# as opposed to letting SQL Server do it with an auto-inrementing primary key.

My preference for PKs is a uniqueidentifier and then a default of getid(), which totally saves you the effort of managing it, and you can retrieve the key for a new record easily by adding an output clause to your insert command.

and what is Type on my db? int or varchar?

Since it's a custom format, the type would be varchar, and I'm assuming this is your primary key.

@deceptikon: Wow I'm amaze your code, actually I'm using a MySql not Sql Server.

I will try to convert your code to my MySql declaration, then connection string will on my dbconnect like "OpenConCls". Because I don't want to view the connection string each form on my C#.

I will update you about the result of my convertion.

Regards,
Darryl

@Deceptikon: I tried your code to change to MySql but I encounter the problem.

private void Form1_Load(object sender, EventArgs e)
{
using (var connection = new SqlConnection(_connectionString))// like this I want to call OpenConCls
{
connection.Open();//and this is delete cause my connection is open already of this OpenConCls
using (var cmd = new SqlCommand(connection))// change to MySql 
{
cmd.SelectCommand = // OpenConCls.OPEN("");
"select top 1 piId" +
"from tblpair_individual_membership" +
"order by piId desc";
var id = cmd.ExecuteScalar();
if (id != null)
{
_lastId = Convert.ToString(id);
}
}
}
}

In this code, I want to change the SQL to MySQL query with call of this connection "OpenConCls" in dbconnect.cs.

for the buttonNewClick, it the same also in the formload.

Regards,

Darryl

No offense intended, but I don't like your OpenConCls. Here's a data access manager that I use for simplified database connections. Warning, it's a utility class, so there's a bunch of code. But first, an example of how to use it in the code you have:

Example Usage
private const string _provider = "MySql.Data.MySqlClient";
private const string _connectionString = "uid=root; database=membership; pooling = false; convert zero datetime=True";

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        using (var db = new DataAccessManager(_provider, _connectionString))
        {
            var query =
                "select top 1 piId" +
                "from tblpair_individual_membership" +
                "order by piId desc";
            var result = db.Select(query);

            if (result.Rows > 0)
            {
                _lastId = result[0]["piId"].ToString();
            }
        }
    }
    catch (DataAccessException ex)
    {
        // Handle the error
    }
}

DataAccessManager is generalized to any supported provider, which in your case is MySql.Data.MySqlClient. Note that I haven't added scalar query support because I tend to need full DataTables, but it would be trivial to add. It's also optimized for SQL Server in terms of the connection string features, but the actual data access should work for any provider (including MySql).

DataAccessManager
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;

namespace JRD.Utilities.Data
{
    /// <summary>
    /// Provides data provider agnostic queries and commands.
    /// </summary>
    public class DataAccessManager : IDisposable
    {
        private DbProviderFactory ProviderFactory { get; set; }

        /// <summary>
        /// Gets or sets the external data store provider name (ex. System.Data.SqlClient).
        /// </summary>
        public string ProviderName { get; set; }

        /// <summary>
        /// Gets or sets the external data store connection string.
        /// </summary>
        public string ConnectionString { get; set; }

        #region IDisposable Implementation
        public void Dispose()
        {
            // Does nothing; included for future using statement support.
        }
        #endregion

        /// <summary>
        /// Creates and initializes a new DataAccessManager object.
        /// </summary>
        /// <param name="providerName">The data provider name (ex. System.Data.SqlClient).</param>
        /// <param name="connectionString">An appropriate connection string for the data provider.</param>
        public DataAccessManager(string providerName, string connectionString)
        {
            ProviderName = providerName;
            ConnectionString = connectionString;
            ProviderFactory = DbProviderFactories.GetFactory(ProviderName);
        }

        #region Commands
        /// <summary>
        /// Selects a DataTable from the DbProvider.
        /// </summary>
        /// <param name="commandText">The select command text to execute.</param>
        /// <param name="args">Parameter definitions for the command.</param>
        /// <returns>A DataTable containing records selected from the DbProvider.</returns>
        public DataTable Select(string commandText, params DatabaseParameter[] args)
        {
            var result = new DataTable();

            try
            {
                using (var connection = GetConnection())
                {
                    using (var command = ProviderFactory.CreateCommand())
                    {
                        command.Connection = connection;
                        command.CommandType = CommandType.Text;
                        command.CommandText = commandText;

                        foreach (var arg in args)
                        {
                            AddParameter(command, arg);
                        }

                        using (var adapter = ProviderFactory.CreateDataAdapter())
                        {
                            adapter.SelectCommand = command;
                            adapter.Fill(result);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new DataAccessException("Provider: " + ProviderName + Environment.NewLine + "CommandText: " + commandText, ex);
            }

            return result;
        }

        /// <summary>
        /// Executes a non-query command on the DbProvider.
        /// </summary>
        /// <param name="commandText">The non-query command text to execute.</param>
        /// <param name="args">Parameter definitions for the command.</param>
        public void ExecuteCommand(string commandText, params DatabaseParameter[] args)
        {
            try
            {
                using (var connection = GetConnection())
                {
                    using (var command = ProviderFactory.CreateCommand())
                    {
                        command.Connection = connection;
                        command.CommandType = CommandType.Text;
                        command.CommandText = commandText;

                        foreach (var arg in args)
                        {
                            AddParameter(command, arg);
                        }

                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new DataAccessException("Provider: " + ProviderName + Environment.NewLine + "CommandText: " + commandText, ex);
            }
        }
        #endregion

        #region Validation
        /// <summary>
        /// Sanitizes an identifier for the provider by quoting it.
        /// </summary>
        /// <param name="identifier">The identifier to sanitize.</param>
        /// <returns>The sanitized identifier.</returns>
        public string QuotedIdentifier(string identifier)
        {
            using (var builder = ProviderFactory.CreateCommandBuilder())
            {
                return builder.QuoteIdentifier(identifier);
            }
        }

        /// <summary>
        /// Checks a table name to verify that it exists in the DbProvider.
        /// </summary>
        /// <param name="tableName">Name of the table to verify.</param>
        /// <param name="isQuoted">True if the table name is already quoted.</param>
        /// <returns>True if the table exists, false otherwise.</returns>
        public bool VerifyTable(string tableName, bool isQuoted)
        {
            using (var connection = GetConnection())
            {
                using (var tables = connection.GetSchema("Tables"))
                {
                    string newTable = isQuoted ? tableName : QuotedIdentifier(tableName);

                    foreach (DataRow row in tables.Rows)
                    {
                        string existingTable = QuotedIdentifier(row["TABLE_NAME"].ToString());

                        if (existingTable == newTable)
                        {
                            return true;
                        }
                    }

                    return false;
                }
            }
        }
        #endregion

        #region Miscellaneous Helpers
        /// <summary>
        /// Constructs a connection string from individual parts.
        /// </summary>
        public static string GetConnectionString(string server, string database, string user, string pass)
        {
            var builder = new SqlConnectionStringBuilder();

            builder.DataSource = server;
            builder.InitialCatalog = database;

            if (string.IsNullOrWhiteSpace(user))
            {
                builder.IntegratedSecurity = true;
            }
            else
            {
                builder.UserID = user;
                builder.Password = pass;
            }

            return builder.ConnectionString;
        }

        /// <summary>
        /// Gets the server name value of the provided connection string.
        /// </summary>
        /// <param name="connectionString">The connection string being parsed.</param>
        /// <returns>The server name or an empty string if not found.</returns>
        public static string GetServerName(string connectionString)
        {
            return GetValue(
                connectionString, 
                new string[] { "server", "host", "data source", "datasource", "address", "addr", "network address" });
        }

        /// <summary>
        /// Gets the database name value of the provided connection string.
        /// </summary>
        /// <param name="connectionString">The connection string being parsed.</param>
        /// <returns>The database name or an empty string if not found.</returns>
        public static string GetDatabaseName(string connectionString)
        {
            return GetValue(
                connectionString, 
                new string[] { "database", "initial catalog" });
        }

        /// <summary>
        /// Gets the login user name value of the provided connection string.
        /// </summary>
        /// <param name="connectionString">The connection string being parsed.</param>
        /// <returns>The user name or an empty string if not found.</returns>
        public static string GetUserName(string connectionString)
        {
            return GetValue(
                connectionString, 
                new string[] { "user id", "uid", "username", "user name", "user" });
        }

        /// <summary>
        /// Gets the login password value of the provided connection string.
        /// </summary>
        /// <param name="connectionString">The connection string being parsed.</param>
        /// <returns>The password or an empty string if not found.</returns>
        public static string GetPassword(string connectionString)
        {
            return GetValue(
                connectionString, 
                new string[] { "password", "pwd" });
        }

        /// <summary>
        /// Parses the connection string for a value matching one of a list of key aliases.
        /// </summary>
        /// <param name="connectionString">The connection string being parsed.</param>
        /// <param name="keyAliases">Supported key aliases.</param>
        /// <returns>The matched value or an empty string if not found.</returns>
        private static string GetValue(string connectionString, string[] keyAliases)
        {
            var csData = from x in connectionString.Split(';')
                         where x.Contains('=')
                         select x.Split(new char[] { '=' }, 2);
            var dataDict = csData.ToDictionary(
                x => x[0].Trim(),
                x => x[1].Trim(),
                StringComparer.InvariantCultureIgnoreCase);
            var value = string.Empty;

            foreach (var alias in keyAliases)
            {
                if (dataDict.TryGetValue(alias, out value))
                {
                    break;
                }
            }

            return value;
        }

        /// <summary>
        /// Retrieves an open connection from the provider factory.
        /// </summary>
        /// <returns>An open DbConnection.</returns>
        private DbConnection GetConnection()
        {
            var connection = ProviderFactory.CreateConnection();

            connection.ConnectionString = ConnectionString;
            connection.Open();

            return connection;
        }

        /// <summary>
        /// Adds the provided database parameter to the provided command.
        /// </summary>
        /// <param name="command">The command the parameter will be added to.</param>
        /// <param name="parameter">The parameter settings.</param>
        private void AddParameter(DbCommand command, DatabaseParameter parameter)
        {
            var p = command.CreateParameter();

            p.ParameterName = parameter.Name;
            p.Value = parameter.Value;
            p.DbType = parameter.Type;

            command.Parameters.Add(p);
        }
        #endregion
    }
}
DatabaseParameter
using System.Data;

namespace JRD.Utilities.Data
{
    /// <summary>
    /// Represents parameter information for a command into the DataAccessManager.
    /// </summary>
    public class DatabaseParameter
    {
        /// <summary>
        /// Gets or sets the SQL command parameter name of the parameter.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the value of the parameter.
        /// </summary>
        public object Value { get; set; }

        /// <summary>
        /// Gets or sets the expected type of the parameter value.
        /// </summary>
        public DbType Type { get; set; }

        /// <summary>
        /// Creates and initializes a new DatabaseParameter object.
        /// </summary>
        /// <param name="name">The name of the database parameter.</param>
        /// <param name="value">The value of the parameter.</param>
        /// <remarks>
        /// The expected type is defaulted, which may create performance problems with implict typing in the database.
        /// </remarks>
        public DatabaseParameter(string name, object value)
        {
            Name = name;
            Value = value;
        }

        /// <summary>
        /// Creates and initializes a new DatabaseParameter object.
        /// </summary>
        /// <param name="name">The name of the database parameter (eg. @MyParameter or :MyParameter)</param>
        /// <param name="value">The value of the parameter.</param>
        /// <param name="type">The expected type of the parameter.</param>
        public DatabaseParameter(string name, object value, DbType type)
        {
            Name = name;
            Value = value;
            Type = type;
        }
    }
}
DataAccessException
using System;
using System.Runtime.Serialization;

namespace JRD.Utilities.Data
{
    /// <summary>
    /// Thrown when a data access request fails for the DataAccessManager.
    /// </summary>
    [Serializable]
    public class DataAccessException : Exception
    {
        /// <summary>
        /// Creates a new DataAccessException object.
        /// </summary>
        public DataAccessException() { }

        /// <summary>
        /// Creates a new DataAccessException object 
        /// initialized with the specified message string.
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        public DataAccessException(string message) : base(message) { }

        /// <summary>
        /// Creates a new DataAccessException object initialized 
        /// with the specified message string and inner exception.
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="inner">The exception that is the cause of the current exception.</param>
        public DataAccessException(string message, Exception inner) : base(message, inner) { }

        /// <summary>
        /// Creates a new DataAccessException object initialized with serialization data.
        /// </summary>
        /// <param name="info">The object that holds the serialized object data.</param>
        /// <param name="context">The contextual information about the source or destination.</param>
        protected DataAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
    }
}
commented: Wow. +15

@deceptikon: DataAccessManager, DatabaseParameter and DataAccessException for Class?

need time to study and understand the codes...

regards,

Darryl

@deceptikon: I got this error,.

if (result.Rows > 0)// cannot be applied to operands of type 'System.Data.DataRowCollection' and 'int'  

                    {
                        _lastId = result[0]["piId"].ToString(); // Cannot apply indexing with [] to an expression of type 'System.Data.DataTable'   
                    }

regards,

Darryl

@deceptikon: I got this error,.

Did you even try to turn on your brain concerning these errors? Especially since I made a similar typo in an earlier post; the first error should be result.Rows.Count. The second should be result.Rows[0]["piId"].ToString().

Of course, this would be immediately obvious upon seeing the errors and consulting the documentation for DataRowCollection and DataTable. Don't expect my code to be perfect, and if I'm not able to help you quickly, you'd be on your own anyway.

@deceptikon: Actually, My intention here is to declare a query to create a auto number like this "AN-00000000" with the type of varchar in my db. You told that the my OpenConcls to calling a db connection it's not perfect for, Yes. We have a the same concept of codings, you give me your example type of calling a Database connection with the long codes,. I tried this but I got an error that I posted above, you told me that need to turn on my brain? I have you question for if my brain is Off to think , I came in this forum and ask a help?. I'm here to ask a help because I am not a Expert like you I'm a newbie on C# program.

I want a simple query to catering my needs.

Thank you,
Darryl

I'm here to ask a help because I am not a Expert like you I'm a newbie on C# program.

I'm happy to help, as evidenced by my posts in this thread. However, the purpose of helping is for you to learn. Eventually you should learn enough to not need to ask for help. As an example, I rarely ask others for help because I'm able to do research and think through my problems on my own.

When it seems like I'm being asked to do all of the work and thinking for you (such as fixing simple syntactic and semantic errors), I get the strong impression that you're not learning anything, and thus my help is pointless. If you can't do that much, you'll be right back here in no time asking for more "help".

I want a simple query to catering my needs.

At this point I'd question why you haven't managed to come up with something workable, or even something different from what you had originally. I've given you a lot of code, and plenty of ideas for moving forward. Barring doing it all for you including a sample database schema and complete working code, what more can I do for you?

commented: You can lead a horse to water... +10

I turn on my mind and search the other way,

when I saved to the db, the query save like this MEPS-00000000, but when I add again the query select like this MEP1 instead of MEPS-00000001, so '-''0000000' zero it's not include in MEP1. but my type in is varchar, and the in query int, what is the difference on this two type? do you have an idea if the query select to db, the '-''0000000' are include when i add another?

while (OpenConCls.reader.Read())
            {
                string pcount = OpenConCls.reader[0].ToString();

                if (pcount.Length == 0)
                {
                    textBox1.Text = "MEPS-00000000";
                }
                else
                {

                    int pcount1 = Convert.ToInt32(pcount.Substring(4));
                    int pcountAdd = pcount1 + 1;
                    textBox1.Text = pcount.Substring(0, 4) + pcountAdd;
                }

            }

You're not assigning the text with correct formatting. Try this instead:

textBox1.Text = string.Format("{0}-{1:00000000}", pcount.Substring(0, 4), pcountAdd);

@deceptikon: Thanks for your reply :)

It's work.

I got this,

Kindly Check the Code Below, If anyone or newbie wants this code,.

while (OpenConCls.reader.Read())
            {
                string pcount = OpenConCls.reader[0].ToString();

                if (pcount.Length == 0)
                {
                    textBox1.Text = "MEPS-00000000";
                }
                else
                {

         int pcount1 = Convert.ToInt32(pcount.Substring(4));
         int pcountAdd = pcount1 + 1;
         textBox1.Text = String.Format("{0}-{1:D8}", pcount.Substring(0, 4), pcountAdd);
                }

            }

Regards

@deceptikon: Oooops.. I got a problem the formula,. "textBox1.Text = String.Format("{0}-{1:D8}", pcount.Substring(0, 4), pcountAdd);" this formula can store "MEPS-00000000 and MEPS-00000001" in my db but when I add again the Increment structure not implemented. because when i add from MEPS-00000000 and MEPS-00000001, and another ID number which is MEPS-00000003 and soon and so fort or infinity. How to declare and query on this?

@deceptikon: Hi

I tried the code below, but it same result in the 1:D8.

    textBox1.Text = string.Format("{0}-{1:00000000}", pcount.Substring(0, 4), pcountAdd);

Please Help,

regards,
Darryl

I don't understand the question. What are you trying to do now?

@deceptikon: Hi I got My problem for the mean time, I do as simple code.

My question is the substring of declaration is counted? like this if my string is countable for 5, I will declare 5 on my substring instead of 4 declaration. In my case in my autonumber with a substring, I had a registration that has a 3,4 and 5 string. (ex. "MEPS-" is equivalent to 5 character string, so I did to declare in 5), .

Example:

 int pcount1 = Convert.ToInt32(pcount.Substring(5));


int pcountAdd = pcount1 + 1;

textBox1.Text = String.Format("{0}-{1:D8}", pcount.Substring(0, 5), pcountAdd++);

the code above is an example that I used.

In my anohter question is int pcountAdd = pcount1 + 1;this line is supposedly a increment way of plus a number if the ID is Excess and not to used. but the problem I encountered on this, when I run the program, the result of this is like a binary way, when I try to add a new ID first(MEPS-00000001) and second(MEPS-00000002) try will be okay, but when I tried to third attempts, the auto number get back to the beginning(MEPS-00000001).

So, to solved my problem I tried to apply a simple code to increment+
+ and it's work( textBox1.Text = String.Format("{0}-{1:D8}", pcount.Substring(0, 5), pcountAdd++);).

and now, here is the question in my mind, what is the purpose of this code int pcountAdd = pcount1 + 1; if this function it's not continuing a Incremental way, Why I need to put up this code pcountAdd++, if you have a formula on this int pcountAdd = pcount1 + 1.? but when I deleted the ++ the code process like a binary way, after second it's going back to the beginning.

regards,

If it's going back to the start of the sequence, either you're not querying the newest ID or you're overriding what the database returns. It's hard to say without seeing both your database schema and all of the code.

Would it be possible to pare down the code into a very small console mode program that exhibits the problem?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.