-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,295
  • 4
  • 43
  • 64
Bindas
  • 960
  • 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,564
  • 4
  • 29
  • 40
Sergio
  • 7,971
  • 10
  • 45
  • 77
0

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

Sean
  • 58,802
  • 11
  • 90
  • 132
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
  • 43,221
  • 7
  • 76
  • 112
0

Try

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