【问题标题】:String disappears after clicking on another textbox单击另一个文本框后字符串消失
【发布时间】:2020-02-25 16:10:53
【问题描述】:

单击按钮时,我正在尝试生成随机整数值(条形码)。然后,如果新条形码已经存在,我将检查两个表(库存、单位)。如果它是唯一的,则新的条形码将写入文本框中。

一切正常,但是当我点击另一个 texbox 表单时,条形码消失了。

PS:我将全局区域的 newBarcode 定义为 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);
}

【问题讨论】:

  • 第一个代码 sn-p - 它是什么情况?函数 BarkodOlustur() 有什么作用?请注意,您的“随机”生成器将始终生成相同的数字...
  • 点击另一个文本框会导致任何事件吗?
  • @JakubSzułakiewicz:如果连续快速调用随机数生成器只会返回相同的数字 - 使用无参数 Random 构造函数使用基于系统时间的种子,因此只要系统时间有改变这不会发生。但是每次调用都不需要一个新的 Random 实例是正确的。
  • @JakubSzułakiewicz 哦,对不起,它实际上也是 BarcodeGenerator()。在发布问题之前,我已尝试将所有关键字翻译成英文。那是我的错,对不起。
  • 这里的逻辑有缺陷。 BarcodeGenerator(); 被调用一次,如果它失败,你只会再调用一次。在这种情况下,未设置 TextBox 文本。反正。您必须全力以赴,才能找到 good 的价值。我不确定 disappear 是什么意思。您可能还有其他设置 TextBox.Text 或清除它的东西。

标签: c# string winforms random textbox


【解决方案1】:

我对您的代码做了一些修改。单击按钮时,它将生成一个条形码。虽然条形码不是唯一的,但它将继续生成条形码,直到它是唯一的。然后它将条形码值分配给txtBarcodeText属性。

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    相关资源
    最近更新 更多