Search code examples
c#stringwinformsrandomtextbox

String disappears after clicking on another textbox


I'm trying to generate random integer value (Barcode) when I click on a button. Then, I 'm checking two tables (stocks, units) if the new barcode already exist or not. If it's unique, the new barcode will be written in the textbox.

It's all working but when I click on another texbox of form the barcode disappears.

PS: I defined newBarcode in global area as Integer..

private void btnBarkodOlustur_Click(object sender, EventArgs e)
{
    BarcodeGenerator();
    string _newBarcode = newBarcode.ToString();
    if (context.Stocks.Any(c => c.Barcode == _newBarcode) || context.Units.Any(c => c.Unit == _newBarcode))
    {
        BarcodeGenerator();
        return;
    }
    else
    {
        txtBarcode.Text = _newBarcode;
    }
}

private void BarcodeGenerator()
{
    Random rnd = new Random();
    newBarcode = rnd.Next(10000000, 99999999);
}

Solution

  • I have made some modifications to your code. When the button is clicked it will generate a barcode. While the barcode is not unique it will continue to generate a barcode until it is unique. Then it will assign the barcode value to the Text property of txtBarcode.

    private Random rnd = new Random();
    
    private void btnBarkodOlustur_Click(object sender, EventArgs e)
    {   
        string _newBarcode = BarcodeGenerator();
        while (context.Stocks.Any(c => c.Barcode == _newBarcode) || context.Units.Any(c => c.Unit == _newBarcode))
        {
            _newBarcode = BarcodeGenerator();
        }
    
        txtBarcode.Text = _newBarcode;
    }
    
    private string BarcodeGenerator()
    {
        return rnd.Next(10000000, 99999999);
    }