0

i am applying the multiple search option on a single table .. for that i have made a sp which is accepting 3 value . my problem is if i apply the multiple search on the table it is taking only one search value at a time so i used view state

  if (ViewState["gen"] != null || ViewState["cen"]!=null)
    {
        var a = db.sp_StudentSelect1(ViewState["gen"].ToString(), ViewState["cen"].ToString());

        GridView1.DataSource = a;
        DataBind();
    }

but it is giving me an error

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

please help...

Saba Aslam
  • 43
  • 3
  • 11

2 Answers2

2

You want and not or in your if statement:

 if (ViewState["gen"] != null && ViewState["cen"]!=null)

Right now just one of them can be non-null and the if statement will pass, but if one of them is null then the statement inside the if won't work because you can't call ToString() on a null value. Use && as above. Or you can edit your code to not fail if one of the values is null (by passing an empty string or some other default value.)


HERE IS AN EXAMPLE HOW TO "FIX" the code:

string gen, cen;

gen = "Default";
cen = "Default";

if (ViewState["gen"] != null)
  gen = ViewState["gen"];

if (ViewState["cen"] != null)
  cen = ViewState["cen"];

var a = db.sp_StudentSelect1(gen,cen);

GridView1.DataSource = a;
DataBind();
Hogan
  • 69,564
  • 10
  • 76
  • 117
  • this code is working only when you select gender and center both.. – Saba Aslam Dec 23 '14 at 15:02
  • Yes, as I said your code in the if statement will only work if you select both. I've written an example of one way to fix your code -- as described in my original answer. – Hogan Dec 23 '14 at 15:16
0

As per Hogan's answer if all parameters are mandatory then use && plus use this check before binding in case your stored procedure returns no rows or null

This indicates var a has null value. before assigning the datasource do this check

if(a!=DBNull.Value)
{

GridView1.DataSource = a;
DataBind();
}

Does it work when you pass one parameter from ViewState?

Also where you do you store values in ViewState? (i.e. what method page_load?)

Mir
  • 86
  • 6