全局变量在计时器tick事件C#上变为null [英] Global variables are getting null on timer tick event C#
问题描述
亲爱的所有人,
我在ASP.NET C#中有一个Web应用程序。
目前,我正在努力将QuestionList中的问题显示给候选人。
我创建了一个存储过程来获取一个全局可变的问题列表。< br $>
Dear All,
I have one web application in ASP.NET C#.
Currently, I'm working to display Question from the QuestionList to the candidate.
I have created a stored procedure to get a list of Questions, which is global varaible.
Private List<QuestionInfo> _questionList;
public List<QuestionInfo> QuestionList
{
get
{
if(_questionList != null)
return _questionList;
else
_questionList =
QuestionDetailsController.Instance.ExamQuestionsGetRandomly(Module.TotalQuestions, QuestionLanguageID, PracticeModuleID).Select(item => item.Question).ToList();
return _questionList;
}
}
我的尝试:
What I have tried:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindQuestion(_questionNumber);
Timer1.Enabled = true;
}
}
protected void BindQuestion(int nthQuestion)
{
if (nthQuestion <= QuestionList.Count())
{
QuestionInfo CurrentQuestion = QuestionList.ElementAt(nthQuestion);
if (CurrentQuestion != null)
{
lblNoOfQuestions.Text = string.Format("Question {0} of {1}", nthQuestion + 1, ExamQuestion.QuestionList.Count());
lblQuestionText.Text = CurrentQuestion.QuestionDetails.First().Details.Text.QuestionText;
}
}
}
我正在使用Ajax UpdatePanel&计时器(显示剩余时间)。
我有三个按钮,如上一个,暂停,下一个。
每当我单击Previous或Next按钮时,全局变量将变为null&在timer_tick事件上也是如此。
如何在单击Next,previous(按钮)或TimerEvent时停止全局变量不得为null。
任何人都可以帮助我。
提前致谢
I'm using Ajax UpdatePanel & Timer(to display time remaining).
I have three buttons, like Previous, Pause, Next.
Whenever I click Previous or Next button, the global variable is getting null & on timer_tick event, as well.
How can I stop global variables not to get null, on clicking the Next, previous(buttons) or TimerEvent.
Can anyone please help me.
Thanks in advance
推荐答案
只有你的控制数据或ViewState中的东西在回发中保持不变,你的本地变量不是每个回发_questionlist都是null,因为你没有在回发时调用BindQuestion。您只需要删除if检查。
Only your control data or things in the ViewState are persisted across postbacks, your local variables are not so on every postback _questionlist will be null as you don't call BindQuestion on postback. You just need to remove the "if" check.
protected void Page_Load(object sender, EventArgs e)
{
BindQuestion(_questionNumber);
if (!IsPostBack)
{
Timer1.Enabled = true;
}
}
你没有显示_questionNumber来自哪里,但是因为我上面说过,如果你想要记住这个值,你需要将它存储在ViewState中,比如
You don't show where _questionNumber comes from, but as I said above if you want that value to be remembered you'll need to store it in the ViewState, something like
<pre>protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Timer1.Enabled = true;
}
else
{
_questionNumber = (int)ViewState["questionNumber"];
}
BindQuestion(_questionNumber);
ViewState["questionNumber"] = _questionNumber;
}
这篇关于全局变量在计时器tick事件C#上变为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!