I get a null – reference in this Code-line:
**DataRow dr = tableSelectedItems.NewRow();**
I can’t find out why. Can anyone help me please?
My code should fill the books which were Selected by the user in a datalist. This is to learn how Sessionstate works. I used the book “ASP.NET 3.5 Step by Step” in a German version. I have exactly the same code as them, but i’m using .net 4.0 instead of 3.5.
Can please someone help me??
All the code of the DatalistItemdCommand is:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
int nItemIndex = e.Item.ItemIndex;
this.DataList1.SelectedIndex = nItemIndex;
BindToinventory();
//Row's Order: ID, Title, FirstName, LastName, Topic, Publisher
DataTable dt = (DataTable)DataList1.DataSource;
string strID = (dt.Rows[nItemIndex][0]).ToString();
string strTitle = (dt.Rows[nItemIndex][1]).ToString();
string strAuthorLastName = (dt.Rows[nItemIndex][2]).ToString();
string strAuthorFirstName = (dt.Rows[nItemIndex][3]).ToString();
string strTopic = (dt.Rows[nItemIndex][4]).ToString();
string strPublisher = (dt.Rows[nItemIndex][5]).ToString();
DataTable tableSelectedItems;
tableSelectedItems = (DataTable)Session["tableSelectedItems"];
//Null Reference is here
DataRow dr = tableSelectedItems.NewRow();
dr[0] = strID;
dr[1] = strTitle;
dr[2] = strAuthorLastName;
dr[3] = strAuthorFirstName;
dr[4] = strTopic;
dr[5] = strPublisher;
tableSelectedItems.Rows.Add(dr);
Session["tableSelectedItems"] = tableSelectedItems;
this.GridView1.DataSource = tableSelectedItems;
this.GridView1.DataBind();
}
}
You try to use the session with out first set a value to it / or the value to this session is not the same data type. I suggest to change to this code:
how ever you must have in mind that this variable will always be null if the user did not have set cookie enable, or the session have time outs.
Why the session will be always null if the cookie is off ? because the session variables are associate with the cookie. If the user have cookies off, then in every reload a new cookie is created and the application can not know the previous cookie, and can not connect the previous session with this user and creates a new session.