如何在c#窗口窗体中检索按钮单击后已分配的当前值
本文关键字:分配 单击 按钮 窗口 窗体 检索 | 更新日期: 2023-09-27 18:17:13
. NET我可以使用会话,但对于windows窗体,我如何获得当前值,我可以添加+ 1?
在btnPrintToken点击后,它将重写,重新运行代码,我希望它保持最后输入的值(LastTokenNumberIssued),并为它添加+ 1等,以便它将更新队列。
private void btnPrintToken_Click(object sender, EventArgs e)
{
Queue<int> queueTokens = new Queue<int>();
lblStatus.Text = "There are " + queueTokens.Count.ToString() +
" customers before you in the queue";
int LastTokenNumberIssued = // Not sure how to retrieve current value what it was after nextTokenNumberTobeIssued.
int nextTokenNumberTobeIssued = LastTokenNumberIssued + 1;
LastTokenNumberIssued = nextTokenNumberTobeIssued;
queueTokens.Enqueue(nextTokenNumberTobeIssued);
AddTokensToListBox(queueTokens);
}
private void AddTokensToListBox(Queue<int> queueTokens)
{
listTokens.Items.Clear();
foreach (int token in queueTokens)
{
listTokens.Items.Add(token.ToString());
}
}
在方法之外创建您的LastTokenNumberIssued:
public YourWindow
{
int LastTokenNumberIssued;
private void btnPrintToken_Click(object sender, EventArgs e)
{
int nextTokenNumberIssued;
LastTokenNumberIssued = LastTokenNumberIssued++;
nextTokenNumberTobeIssued = LastTokenNumberIssued;
}
}
如果你在方法中创建lasttokennumberissue,它会在每次点击按钮时被重写,因为当方法返回时它的值会丢失。
查看方法作用域的更多信息
一种方法是在btnPrintToken_Click
方法之前定义这些变量nextTokenNumberTobeIssued
, LastTokenNumberIssued
,如下所示:
int LastTokenNumberIssued = 0; //give it a default value here.
int nextTokenNumberTobeIssued = 0; //give it a default value here.
private void btnPrintToken_Click(object sender, EventArgs e)
{
....
nextTokenNumberTobeIssued = LastTokenNumberIssued + 1;
LastTokenNumberIssued = nextTokenNumberTobeIssued;
...
}
这样,每次用户点击按钮PrintToken
,你将有LastTokenNumberIssued
保持之前的点击。
int LastTokenNumberIssued = 0; //here will be the start value
private void btnPrintToken_Click(object sender, EventArgs e)
{
Queue<int> queueTokens = new Queue<int>();
lblStatus.Text = "There are " + queueTokens.Count.ToString() +
" customers before you in the queue";
int nextTokenNumberTobeIssued = LastTokenNumberIssued + 1;
LastTokenNumberIssued = nextTokenNumberTobeIssued;
queueTokens.Enqueue(nextTokenNumberTobeIssued);
AddTokensToListBox(queueTokens);
}
private void AddTokensToListBox(Queue<int> queueTokens)
{
listTokens.Items.Clear();
foreach (int token in queueTokens)
{
listTokens.Items.Add(token.ToString());
}
}