0

I'm having a problem storing and displaying values from a datatable. My goal is to add a value to a datatable, reload the page, and then display the datatable with the added value and give the ability to enter more. Currently, I can't even get the data table to show up. I am sure that it is an issue with saving the data in a session, but I simply cannot get the saving/loading from session to work.

I appericate any help you guys can give me, and I apologize if it's something really blindingly simple. Seems I just need a second opinion on it.

This is my current webpage,

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <p><asp:TextBox ID="txtName" runat="server"></asp:TextBox><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><asp:TextBox ID="txtAddress" runat="server"></asp:TextBox><asp:TextBox ID="txtInfo" runat="server"></asp:TextBox></p>
    <p>
        <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click"/></p>
    </div>
    <div>
        <table border="1">
            <asp:Repeater ID="rptrData" runat="server">
                <HeaderTemplate>
                    <tr>
                        <td>Name</td>
                        <td>Email</td>
                        <td>Address</td>
                        <td>Info</td>
                    </tr>
                </HeaderTemplate>
                <ItemTemplate>
                    <tr>
                        <td><%#Eval("Name") %></td>
                        <td><%#Eval("Email") %></td>
                        <td><%#Eval("Address") %></td>
                        <td><%#Eval("Info") %></td>
                    </tr>
                </ItemTemplate>
                <AlternatingItemTemplate>
                    <tr>
                        <td><%#Eval("Name") %></td>
                        <td><%#Eval("Email") %></td>
                        <td><%#Eval("Address") %></td>
                        <td><%#Eval("Info") %></td>
                    </tr>
                </AlternatingItemTemplate>
            </asp:Repeater>
        </table>
    </div>
    </form>
</body>
</html>

And my current code behind,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
using System.Data;
using System.Collections;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        public DataTable MyDT = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                DataTable MyDT = (DataTable)Session["MyDT"];
                rptrData.DataSource = MyDT;
                rptrData.DataBind();
            }
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            //DataTable MyDT = new DataTable();
            MyDT.Columns.Add("Name");
            MyDT.Columns.Add("Address");
            MyDT.Columns.Add("Email");
            MyDT.Columns.Add("Info");
            string Name = txtName.Text;
            string Address = txtAddress.Text;
            string Email = txtEmail.Text;
            string Info = txtInfo.Text;

            DataRow dtRow = MyDT.NewRow();
            dtRow["Name"] = Name;
            dtRow["Address"] = Address;
            dtRow["Email"] = Email;
            dtRow["Info"] = Info;

            Session.Add("MyDT", MyDT);
        }  
    }
}
1
  • You only want to add the columns to the datatable once, i recommend in page load, not everytime you click the add button. Commented Mar 21, 2016 at 20:18

2 Answers 2

1

Your code has a few basic issues. If you see what I changed and compare it to what you had you should be able to figure out some of the problems.

public DataTable MyDT;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        MyDT = new DataTable();
        MyDT.Columns.Add("Name");
        MyDT.Columns.Add("Address");
        MyDT.Columns.Add("Email");
        MyDT.Columns.Add("Info");
        Session["MyDT"] = MyDT;
    }
    else
    {
        // Here we load the session datatable to the variable you declared at the top.
        // It will be ready for us in the button click event.  We know this because
        // of asp.net page lifecycle which will run the page_load before the button
        // click event.

        MyDT = (DataTable)Session["MyDT"];
    }

    // You can bind the repeater here also if you want.  Doesn't really make a huge difference
}



protected void btnAdd_Click(object sender, EventArgs e)
{
    string Name = txtName.Text;
    string Address = txtAddress.Text;
    string Email = txtEmail.Text;
    string Info = txtInfo.Text;

    DataRow dtRow = MyDT.NewRow();
    dtRow["Name"] = Name;
    dtRow["Address"] = Address;
    dtRow["Email"] = Email;
    dtRow["Info"] = Info;
    MyDT.Rows.Add(dtRow);

    rptrData.DataSource = MyDT;
    rptrData.DataBind();
}

You'll notice I don't even have to save the datatable back to the session variable. The DataTable is a reference type so any changes I make to the variable MyDT are being saved to the same spot the Session variable is pointing to.

I also removed the new declaration at the top if your class for MyDT. You don't need that.

Finally you'll see that the columns are created a single time when the page first loads. As someone commented in your question recreating the columns is not a good idea or needed.

Sign up to request clarification or add additional context in comments.

3 Comments

Hey, thanks a lot for your help. The code looks a lot cleaner, I've learned a lot from it. I am having one problem, it's throwing "System.NullReferenceException: Object reference not set to an instance of an object." because when it attempts to load the new datarow"dtRow" both dtRow and MyDT are null.
Hey! Seemed to have fixed it, sorry about that. Thank you a lot, I really appreciate it.
Are you sure you have the else statement in Page_Load which assigns the Session["MyDT"] to the table? If you do have that then my next question is what browser are you using? Also, set a break point and test your Session class to make sure it is saving data. Your security settings may be blocking that.
0

I have a solution for this in VB, don't have time to convert to C# myself, but hopefully this will help.

The idea is to create the table first when loading the page and store it in the session var. Then to add to it, create a new DataRow and insert them into the table, update the session var, and rebind to the grid.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then

        CreateDetailTable()

    End If

End Sub


''' <summary>
''' create the detail table and store in a session var
''' </summary>
''' <remarks></remarks>

Private Sub CreateDetailTable()

    Dim dt As New DataTable

    dt.Columns.Add("McsStatusId")
    dt.Columns.Add("McsHeaderId")
    dt.Columns.Add("SeqNo")
    dt.Columns.Add("Status")
    dt.Columns.Add("DateTime")
    dt.Columns.Add("Timezone")
    dt.Columns.Add("Location")
    dt.Columns.Add("State")
    dt.Columns.Add("Country")
    dt.Columns.Add("Comments")
    dt.Columns.Add("TransmittedFlag")
    dt.Columns.Add("TransmissionNo")
    dt.Columns.Add("AddUserId")
    dt.Columns.Add("AddTime")
    dt.Columns.Add("LastUserId")
    dt.Columns.Add("LastTime")
    dt.Columns.Add("DeleteFlag")

    Session(hdnSessionVar.Value) = dt

End Sub


''' <summary>
''' add detail record to the table stored in the session, then use this table to refresh the grid
''' </summary>
''' <remarks></remarks>

Private Function AddDetailToGrid() As Boolean

    Dim rtn As Boolean = False

    Try

        Dim u As New ClassUserProfile
        u.GetUserFromSession()

        Dim dt As DataTable = TryCast(Session(hdnSessionVar.Value), DataTable)
        Dim dr As DataRow

        dr = dt.NewRow

        dr("McsStatusId") = 0 'filler
        dr("McsHeaderId") = hdnMcsHeaderId.Value 'filler
        dr("SeqNo") = 0 'filler
        dr("Status") = ddlStatus.SelectedItem.Text.Trim
        dr("DateTime") = txtStatusDate.Text.Trim & " " & txtStatusTime.Text.Trim
        dr("Timezone") = ddlTimezones.SelectedItem.Text.Trim
        dr("Location") = txtStatusLocation.Text.Trim
        dr("State") = txtStatusState.Text.Trim
        dr("Country") = txtStatusCountry.Text.Trim
        dr("Comments") = txtStatusComments.Text.Trim
        dr("TransmittedFlag") = 0 'these two fields should not be able to be added by user, they will be updated in a DB job that runs, and
        dr("TransmissionNo") = 0 'once they are set this status detail record will no longer be editable
        dr("AddUserId") = 0 'filler
        dr("AddTime") = DateTime.Now 'filler
        dr("LastUserId") = 0 'filler
        dr("LastTime") = DateTime.Now  'filler
        dr("DeleteFlag") = 0 'filler

        If hdnSeqNo.Value = "" Then
            dt.Rows.Add(dr)
        Else
            dt.Rows.InsertAt(dr, hdnSeqNo.Value)
        End If

        Session(hdnSessionVar.Value) = dt 'update the session var

        'bind the grid
        gridMcsStatus.DataSource = dt
        gridMcsStatus.DataBind()

        rtn = True

    Catch ex As Exception

        mbStatus.ShowErrorMsg("There was an error adding to the grid: " & ex.ToString)

    End Try

    Return rtn

End Function

''' <summary>
''' bind the session var containing the table data to the grid
''' </summary>
''' <remarks></remarks>

Private Sub BindStatusDetailGrid()

    Using dt As DataTable = TryCast(Session(hdnSessionVar.Value), DataTable)

        gridMcsStatus.DataSource = dt
        gridMcsStatus.DataBind()

    End Using

End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.