Trouble with ViewState on Postback

J

JP2006

I'm having a major pain with retrieving ViewState info after a postback
event. I am trying to persist a string contained in a label
(label_AntiBot.Text) that is generated randomly on page load but needs
to be retained after a postback.
Key snipppet of code in question:

/////////////////////////////////////////////////////
1 protected void Page_Load(object sender, EventArgs e)
2 {
3 if (!Page.IsPostBack)
4 {
5 createAntiBot();
6 }
7 else
8 {
9 // Page is a postback so retrieve the label text from
ViewState
10 label_AntiBot.Text = ViewState["antiBotVS"].ToString();
11 }
12 }
13
14 protected void createAntiBot()
15 {
16 Random r1 = new Random();
17 for (int i = 0; i < 3; i++)
18 {
19 int antiBotInt = r1.Next(0, 9);
20 string antiBotText = antiBotGen(antiBotInt);
21 arAntiBot = antiBotInt;
22 label_AntiBot.Text += "<img src='/images/nums/" +
antiBotText + "'>";
23 }
24 // Place the label text into ViewState
25 ViewState["antiBotVS"] = label_AntiBot.Text;
26 }
/////////////////////////////////////////////////////

When the code runs and the page posts back I get a 'Object reference
not set to an instance of an object.' error on line 10 as ViewState is
null!

I dont get it! I can only assume I am doing something fundamentally
wrong but have read various ViewState primers and really can't see what
it is.
Help gratefully recieved :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top