Search code examples
c#.netstack-overflow

System.StackOverflowException on retrieve one row from DB and fill in datatable


I'm try to get 1 row from database and fill it to datatable but this get error on fill data into datatable. yesterday it's work fine but suddenly this happen.

the function used to return the last row on order to use that las order in add more orders rows. this function call once time in the code width no loop in call. the user click button to generate group of barcode which call the generate function which then call the function (retrieve the row from database).

here the part of code error (retrieve the row from database):

 public String  getLastBarcodeByFirstChar(char c)
    {
        DataTable dataTable = new DataTable();
        using (SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand($"SELECT TOP 1 barcode FROM Barcodes WHERE barcode LIKE '{c}%' ORDER BY Id DESC", Con))
            {
                SqlDataAdapter ad = new SqlDataAdapter(cmd);
                //ad.ReturnProviderSpecificTypes = true;
                ad.Fill(dataTable);
            }
        }
        
        foreach(DataRow r in dataTable.Rows)
        {
            return r["barcode"].ToString();
        }

        return string.Empty;
    }

function call in this bard on generate barcode function

public string GenerateRandomEan13Barcode(char x)
{
    ...
    String lastBarcode = func.getLastBarcodeByFirstChar(x);
    ...
}

called there

public string getBarcode(char c)
    {
        EncryptFuc encryptFuc = new EncryptFuc();
        string barcode = encryptFuc.GenerateRandomEan13Barcode(c);

        if (IsContainBarcode(barcode))
        {
            getBarcode(c);
        }

        return barcode;

which called when user click the button, call straight forward with no loop.

protected void BtnGenerateBarcodesRange_Click(object sender, EventArgs e)
        {
            ...

            //generate the barcode 
            string Barcode = assetDo.getBarcode(x[0]);
            ...
        }

can you tell me what I'm missing ?


Solution

  • I found the issue by Hans Kesting comment

    , getBarcode function loop recursion go for infinity,, because mistake on IsContainBarcode(barcode) function.