The object reference error in asp.net - asp.net

i am using the following code on page_load event in asp.net
protected void Page_Load(object sender, EventArgs e)
{
lblDate.Text = System.DateTime.Now.ToLongDateString();
if(!IsPostBack)
{
setImageUrl();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
setImageUrl();
}
private void setImageUrl()
{
Random rnd = new Random();
int i = rnd.Next(1, 7);
Image1.ImageUrl ="~/SlideImages/"+ i.ToString() + ".gif";
}
code is working well at page-load event but when i click any other menu item it gives me the following error message
Object reference not set to an instance of an object.

Well I am 95% sure that i is null because when you ToString() and object if it is null it will throw a fatal exception. What I would do is set a break point on the line throwing the error and run this project in debug mode and see what I is returning. If it is null then there is your problem. So you would have to find out why your Random Method isn't instantiating properly.
Also a recommendation would be to do a String.Format on that line as well
Image1.ImageUrl = String.Format("~/SlideImages/{0}.gif", i);
This will give you the same result set as long as i is valid and String.Format will format null as an empty string. So you will have a graceful fail and your image just won't show up which means you know your problem.

Related

.net using and reaching public value

I wrote this code in .NET. When I want to change ‘s’ by clicking button2, it doesn’t change. I mean after clicking button2 and then I click Button1 to see the changes but nothing changes. How can I change and access the value of ‘s’ properly. What am I doing wrong?
public string s;
public void Button1_Click(object sender, EventArgs e)
{
Label1.Text = s;
}
public void Button2_Click(object sender, EventArgs e)
{
s = TextBox1.Text;
}
You need to understand how web applications work.
In each post back an instance of the class that handles the page is loaded, so when you click on button 1, the page does a post back and loads again, so this way the variable s isn't loaded with your content.
To make this code work, you need to save the S values on the page viewstate.
try replacing "public string s;" with this:
public string s
{
get { return (string)ViewState["myValue"]; }
set [ ViewState["myValue"] = value };
}
More Information about Page Life Cycle at: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

asp.net textbox not updated from another task

I have a GridView and on its SelectedIndexChanged the code is fired:
protected void grdEntry_SelectedIndexChanged(object sender, EventArgs e)
{
lblAssignId.Text = grdEntry.SelectedRow.Cells[1].Text == " "
? ""
: grdEntry.SelectedRow.Cells[1].Text;
Ob.BranchId = Globals.BranchID;
Ob.AssignId = lblAssignId.Text;
DataSet dsMain = GetAssignDetails(Ob);
if (dsMain.Tables[0].Rows.Count != 0)
{
// some other code
Task.Factory.StartNew(() => FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId));
}
}
and the code for filling membership id is
private void FillMemberShipAndBarCode(string customerCode, string branchId)
{
var sqlCommand = new SqlCommand
{
CommandText = "sp_customermaster",
CommandType = CommandType.StoredProcedure
};
sqlCommand.Parameters.AddWithValue("#CustomerCode", customerCode);
sqlCommand.Parameters.AddWithValue("#BranchId", branchId);
sqlCommand.Parameters.AddWithValue("#Flag", 18);
var data = PrjClass.GetData(sqlCommand);
txtMemberShip.Text = data.Tables[0].Rows[0]["MembershipId"].ToString();
txtBarCode.Text = data.Tables[0].Rows[0]["Barcode"].ToString();
}
It's working fine, but is is not updating any of the textboxes. Also, I checked in watch window, the values are returned as expected (M-1213 and 634-98-4 ) and the code does reaches the point txtMemberShip.Text = data.Tables[0].Rows[0]["MembershipId"].ToString();
but the txtMemberShip just remains empty??? Can anyone tell me why is not updating the textboxes?
UPDATE
As per comments, here is the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDown();
BindGrid();
SetDefaultsInTextBoxes();
}
}
And I don't have any code that waits on this task.
Don't do this:
Task.Factory.StartNew(() => FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId));
What are you trying to achieve by doing so?
What is probably happening is your method FillMemberShipAndBarCode is probably running after ASP.NET has already sent the page back to the browser. Thus, essentially, no visible effect on the rendered HTML.
ASP.NET isn't a good place to do multi-threaded stuff.
Try just replacing the above with this:
FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId);

Collection was modified enumeration operation may not execute in datalist

I am getting error when i try to fire event after clicking button which is outside datalist.
Error shows in for each statement :
Collection was modified enumeration operation may not execute.
protected void btnSaveGrid_Click(object sender, EventArgs e)
{
foreach (DataListItem item in dlPl.Items)
{
CommandEventArgs commandArgs = new CommandEventArgs("SaveGrid", btnSaveGrid);
DataListCommandEventArgs repeaterArgs = new DataListCommandEventArgs(item,btnSaveGrid, commandArgs);
dlPl_ItemCommand(btnSaveGrid, repeaterArgs);
}
protected void dlPl_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "SaveGrid")
{
//Some work
}
}
can anyone help me?
You may not modify the collection while you are enumerating it. dlPl_ItemCommand modifies dlPl.Items, which is not allowed.If you move DataBind outside the loop, it should work.

ASP.NET Session bool variable is set to null in page load

I am receiving this error message when I debug my program.
Object reference not set to an instance of an object.
That error happens on this line:
protected void Page_Load(object sender, EventArgs e)
{
bool x = (bool)Session["IsConnectionInfoSet"];--> error here
if (IsPostBack && x)
//do something with the bool x variable
}
Postback is invoked by:
protected void btnDo_Click(object sender, EventArgs e)
{
//do something
Session["IsConnectionInfoSet"] = true;
//do something
}
This error happened in Visual Studio 2008, .NET Framework 3.5.
Can someone give me advice on how this?
The Page_Load method is always run before any event handlers. As a result, the page_load will run, find null and throw an error, all before you click handler has a chance to set this session value.
Here's a safer way to access this session value
bool x = Session["IsConnectionInfoSet"] == null ? false :
(bool)Session["IsConnectionInfoSet"];
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//this is the first time page load.
}
else
{
if (Session["IsConnectionInfoSet"] != null)
{
bool x = (bool)Session["IsConnectionInfoSet"];
if (x)
{
//do something with the bool x variable
}
}
}
}
Hope this helps

Send data through the QueryString with ASP.NET

I want to send a string to another page named Reply.aspx using the QueryString.
I wrote this code on first page that must send the text to Reply.aspx:
protected void FReplybtn_Click(object sender, EventArgs e)
{
String s = "Reply.aspx?";
s += "Subject=" + FSubjectlbl.Text.ToString();
Response.Redirect(s);
}
I wrote this code on the Reply.aspx page:
RSubjectlbl.Text += Request.QueryString["Subject"];
But this approach isn't working correctly and doesn't show the text.
What should I do to solve this?
Thanks
Though your code should work fine, even if the source string has spaces etc. it should return something when you access query string, please try this also:
protected void FReplybtn_Click(object sender, EventArgs e)
{
String s = Page.ResolveClientUrl("~/ADMIN/Reply.aspx");
s += "?Subject=" + Server.UrlEncode(FSubjectlbl.Text.ToString());
Response.Redirect(s);
}
EDIT:-
void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString.HasKeys())
{
if(!string.IsNullOrEmpty(Request.QueryString["Subject"]))
{
RSubjectlbl.Text += Server.UrlDecode(Request.QueryString["Subject"]);
}
}
}
PS:- Server.UrlEncode is also sugested in comment to this question.
this is easy :
First page :
string s = "~/ADMIN/Reply.aspx?";
s += "Subject=" + FSubjectlbl.Text;
Response.Redirect(s);
Second page :
RSubjectlbl.Text = Request.QueryString["Subject"];

Resources