Reputation: 53
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();
}
}
Upvotes: 2
Views: 814
Reputation: 66641
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:
DataTable tableSelectedItems;
object otabSelItems = Session["tableSelectedItems"];
if(otabSelItems is DataTable)
tableSelectedItems = (DataTable)otabSelItems;
else
tableSelectedItems = new DataTable();
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.
Upvotes: 3
Reputation: 586
@Aristos is right.. also other guyz too..its a simple check.. my opinion is to add this line too
tableSelectedItems.AcceptChanges();
after you add the row in table..i.e tableSelectedItems.Rows.Add(dr);
Upvotes: 0
Reputation: 17194
tableSelectedItems = (DataTable)Session["tableSelectedItems"];
This line may be the problem because if session["tableSelectedItems"] is null then tableSelectedItems will also be null.
Upvotes: 0