Regardless of the Page_Load if statement, you have to understand scope of the variables you create.
When you create or instantiate the variable inside a block, like an if( ) { } then the variables only exist there. If you declare the variables in a function then that is where they exist.
Now the key is in this case that you have them declared outside of any function or block, so the variable itself is OK, but in this case you have instantiated them by using new () inside a block that is executed only the first (as indicated above) therefore on the second iteration or postback, the variables are declared but not instantiated and therefore you get the error of null reference exception.
The first example that you indicate is Wrong, I am interested in why you think it is wrong. It is actually right, and in your example, it is the way you should do this because you use the variables when you need them and then they go out of scope. In your second example you are trying to be generic and have a GLOBAL object, and that is not the best practice in .NET.
Ben.
Main Topics
Browse All Topics





by: Chirag1211Posted on 2007-08-16 at 21:59:54ID: 19714667
The 2nd example of the code throws an error because in the Page_Load() event you have written code as : ", sqlConnectC); e;
if(!Page.IsPostaback)
{
sqlConnectC = new SqlConnection(conString);
sqlCommandC = new SqlCommand("countContracty
sqlCommandC.CommandType = CommandType.StoredProcedur
.........}
Now sqlCommandC object will only get instantiated when your page will get loaded for the first time. But when you click on the button the code inside the if() statement will not work. So the sqlCommandC object will be null which when accessed inside Button_Click() event will throw null reference exception
So the change for this could you remove the if() condition in the Page_load()
Regards,
Chirag Patel.