-3

Possible Duplicate:
System.NullReferenceException: Object reference not set to an instance of an object

look at my code

if (ViewState["Edit"].ToString() == "new") { 
}
else {
      row = _section.GetBannerEntry(ViewState["Edit"].ToString()); 
}

I was getting the error on this line if (ViewState["Edit"].ToString() == "new") I replaced with if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") it works.

Now I am getting the same error here in else row = _section.GetBannerEntry(ViewState["Edit"].ToString());

please help

Community
  • 1
  • 1
shafiq
  • 45
  • 1
  • 2
  • 3
  • 2
    asking what is effectively the same question over and over again is not good Stack Overflow etiquette and attracts unwanted flag attention. You've been told quite a few times that `_section` has not been initialised by other user's answers. That should be a good enough pointer to why your code is failing? You also fail to provide any code that explains how `_section` is being initialised (if at all) which isn't helping either. Thanks. – Kev Jun 02 '11 at 12:34

5 Answers5

3

Your View state is null Check for

if(ViewState["Edit"]!= null)
{
 if (ViewState["Edit"].ToString() == "new")
}
Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
Bindas
  • 980
  • 2
  • 8
  • 22
1

If ViewState["Edit"] hasn't been set, .ToString() will throw an exception.

Try one of these:

  • if (ViewState["Edit"]!= null && ViewState["Edit"].ToString() == "new") //best one
  • if (ViewState["Edit"] + "" == "new")
Alex R.
  • 4,664
  • 4
  • 30
  • 40
Sergio
  • 8,125
  • 10
  • 46
  • 77
0

Well, either ViewState is null or ViewState["Edit"] is returning null...

Sean
  • 60,939
  • 11
  • 97
  • 136
0
if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") {

or if whats supposed to be in the viewstate is a string, this should work:

if ((string)ViewState["Edit"] == "new") {
Magnus
  • 45,362
  • 8
  • 80
  • 118
0

Try

protected void btnSaveDetails_Click(object sender, EventArgs e) 
{         
DataRow row = null;          
 if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") 
 {
 }
}
FIre Panda
  • 6,537
  • 2
  • 25
  • 38