Question

I am looking for assistance in using an object as a datasource for GridView in an ASP.NET page. The scenario is: I am creating a vacation planner for employees in my company. I have created a class to hold the information that pertains to each day (Req1 when I reference in the future), as well as a class to hold a List<> of the request class (Req2). My goal is to allow a user to enter information into a data entry form, when they submit, the data from the entry form is stored in object Req1, which is then stored in the list of requests, which is then used as a datasource for a GridView. Once the user has entered all the dates that they would like to take off, they would submit all and the system would loop through each request and insert a record into the database. (I imagine the submit would be handled within the class.)

My issue is in my understanding of ASP.NET. I think I am storing the data in a ViewState, but the gridview is not displaying the info on the screen when the user enters a specific record. The ToDataTable() method returns a datatable of the values in each Req1 object. I am pointing the DataSource of the gridview to the ToDataTable() method to return the request as a table.

I would prefer to work with a tutorial on using an object data source, but I could not find something that suited my needs online. I hope someone can point me in the right direction.

Here is the code for the Req1 and Req2 classes. Some values are populated with dummy data.

[Serializable]
public class RTORequestOrder
{
    private int _RTORequestId = 123;
    private int _RTOOrderId = 123;
    private DateTime _RTOOrderDate = DateTime.Now;
    private string _RTOOrderRecipientEmpId = "123456";
    private int _RTOOrderTimeOffCd = 123;
    private string _RTOOrderStartTime = "4 O'Clock";
    private int _RTOOrderDuration = 123;
    private LunchBreak _RTOOrderLunchOffset = LunchBreak.Mins00;
    private int _RTOOrderStatus = 1;
    private int _RTOOrderState = 1;
    private byte[] _RTOOrderVersion;
    private string _RTOInsertUserId = "Donald";
    private string _RTOInsertUserWorkstation = "MyComputer";

    public int RTORequestId
    {
        // Set by calling object when this object is created.
        get { return _RTORequestId; }
    }
    public int RTOOrderId
    {
        // Set by calling object when this object is created.
        get { return _RTOOrderId; }
    }
    public DateTime RTOOrderDate
    {
        // Set by drop down.
        get { return _RTOOrderDate; }
        set { _RTOOrderDate = value; }
    }
    public string RTOOrderRecipientEmpId
    {
        get { return _RTOOrderRecipientEmpId; }
    }
    public int RTOOrderTimeOffCd
    {
        get { return _RTOOrderTimeOffCd; }
        set { _RTOOrderTimeOffCd = value; }
    }
    public string RTOOrderStartTime
    {
        get { return _RTOOrderStartTime; }
        set { _RTOOrderStartTime = value; }
    }
    public int RTOOrderDuration
    {
        get { return _RTOOrderDuration; }
        set { _RTOOrderDuration = value; }
    }
    public LunchBreak RTOOrderLunchOffset
    {
        get { return _RTOOrderLunchOffset; }
        set { _RTOOrderLunchOffset = value; }
    }
    public int RTOOrderStatus
    {
        get { return _RTOOrderStatus; }
    }
    public int RTOOrderState
    {
        get { return _RTOOrderState; }
    }
    public byte[] RTOOrderVersion
    {
        get { return _RTOOrderVersion; }
    }
    public string RTOInsertUserId
    {
        get { return _RTOInsertUserId; }
    }
    public string RTOInsertUserWorkstation
    {
        get { return _RTOInsertUserWorkstation; }
    }

    public RTORequestOrder(int RTORequestId, string RTOOrderRecipientEmpId, string RTOInsertUserId, string RTOInsertUserWorkstation)
    {
        // Set properties
        _RTORequestId = RTORequestId;
        _RTOOrderRecipientEmpId = RTOOrderRecipientEmpId;
        _RTOInsertUserId = RTOInsertUserId;
        _RTOInsertUserWorkstation = RTOInsertUserWorkstation;
    }

    public void InsertRTORequstOrder()
    {
        DALRTORequest.InsertRTORequestOrder(this);
    }
}

[Serializable]
public class UserRequestOrders
{
    private List<RTORequestOrder> m_thisUsersOrders = new List<RTORequestOrder>();

    public List<RTORequestOrder> RequestOrders
    {
        get { return m_thisUsersOrders; }
    }

    public DataTable SelectRequestOrders()
    {

            DataTable dt = ToDataTable(m_thisUsersOrders);
            dt.Columns.Remove("RTORequestId");
            dt.Columns.Remove("RTOOrderLunchOffset");
            dt.Columns.Remove("RTOOrderStatus");
            dt.Columns.Remove("RTOOrderState");
            dt.Columns.Remove("RTOOrderVersion");
            dt.Columns.Remove("RTOInsertUserId");
            dt.Columns.Remove("RTOInsertUserWorkstation");

            dt.Columns["RTOOrderId"].ColumnName = "Order ID";
            dt.Columns["RTOOrderDate"].ColumnName = "Date";
            dt.Columns["RTOOrderRecipientEmpId"].ColumnName = "Name";
            dt.Columns["RTOOrderTimeOffCd"].ColumnName = "Time Off Code";
            dt.Columns["RTOOrderStartTime"].ColumnName = "Start Time";
            dt.Columns["RTOOrderDuration"].ColumnName = "Duration";

                return dt;

    }

    public void AddNew(RTORequestOrder newOrder)
    {
        m_thisUsersOrders.Add(newOrder);
    }

    private DataTable ToDataTable<T>(List<T> items)
    {

        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties

        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo prop in Props)
        {

            //Setting column names as Property names

            dataTable.Columns.Add(prop.Name);

        }

        foreach (T item in items)
        {

            var values = new object[Props.Length];

            for (int i = 0; i < Props.Length; i++)
            {

                //inserting property values to datatable rows

                values[i] = Props[i].GetValue(item, null);

            }

            dataTable.Rows.Add(values);

        }

        //put a breakpoint here and check datatable

        return dataTable;

    }


}

And here is the code behind for the page that I am using:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


public partial class Default3 : System.Web.UI.Page
{
    RTODataEntryObjects.UserRequestOrders MyOrders = new RTODataEntryObjects.UserRequestOrders();

    void Page_PreRender(object sender, EventArgs e)
    {
        ViewState.Add("vsMyOrders", MyOrders);
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        NewDataGrid.EnableViewState = true;
        if (ViewState["vsMyOrders"] != null)
        {
            MyOrders = (RTODataEntryObjects.UserRequestOrders)ViewState["vsMyOrders"];
        }

        //MyName.InnerText = User.Identity.Name;
        //MyWorkstation.InnerText = System.Environment.MachineName;


    }

    public void btnSubmit(object sender, EventArgs e)
    {
        RTODataEntryObjects.RTORequestOrder thisOrder = new RTODataEntryObjects.RTORequestOrder(1, "Donald", User.Identity.Name, System.Environment.MachineName);
        //Response.Write(thisOrder.RTOOrderId);
        //MyOrders.AddNew(thisOrder);

        ViewState["vsMyOrders"] = MyOrders;
    }

}

And finally, here is the page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" Debug="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <label id="MyName" runat="server"></label>
        <label id="MyWorkstation" runat="server"></label>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="btnSubmit" />
        <fieldset id="RTORequestForm" runat="server">
            <legend>Time Off Request</legend>
            <asp:DataGrid ID="NewDataGrid" runat="server" BackColor="White" 
                BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" 
                DataSourceID="ObjectDataSource1" GridLines="Horizontal">
                <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
                <SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
                <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" 
                    Mode="NumericPages" />
                <AlternatingItemStyle BackColor="#F7F7F7" />
                <ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
                <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
            </asp:DataGrid>
<%--            <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
                DataObjectTypeName="RTODataEntryObjects.RTORequestOrder" InsertMethod="AddNew" 
                SelectMethod="SelectRequestOrders" 
                TypeName="RTODataEntryObjects.UserRequestOrders"></asp:ObjectDataSource>--%>
            <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"></asp:ObjectDataSource>
        </fieldset>
    </form>
</body>
</html>
Was it helpful?

Solution

I have found a good keyword to search on when adding custom code is "Dynamic". Also try adding "Bind" and "List". Have you looked at the page http://msdn.microsoft.com/en-us/library/cc488549(VS.100).aspx yet? There is code that steps you through in detail as well as several other links that may be closer to what you are looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top