Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My current task are to create Timesheet system. The problem is when user input value in GridView will be missing after the page been refresh. I have been search through other forum and there is no solution that can fit with my problem.

I would like to explain the flow of my system.

1. There is drop down list that user will select to add new project in the GridView.

<asp:DropDownList ID="dd_project_no" runat="server" CssClass="tb_pro_no btn-info"
OnSelectedIndexChanged="dd_project_no_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
2. Then user will put some value inside textbox of GridView which is the working hour for the project.

<asp:TemplateField ItemStyle-Width="600px" HeaderText="Saturday">
<HeaderTemplate>
<div class="form-inline">
<asp:Label ID="Label12" runat="server" Text="Sat" CssClass="col-xs-12"></asp:Label>
<%--<asp:Label ID="dSat" runat="server" Text="Date" CssClass="col-xs-12"></asp:Label>--%>
<asp:Label ID="Label16" runat="server" Text="ST" CssClass="col-xs-5"></asp:Label>
<asp:Label ID="Label17" runat="server" Text="OT" CssClass="col-xs-5"></asp:Label>
</div>
</HeaderTemplate>
<ItemTemplate>
<div class="form-inline">
<asp:TextBox ID="sat_st" runat="server" CssClass="tb_day col-xs-5"></asp:TextBox>
<asp:TextBox ID="sat_ot" runat="server" CssClass="tb_day col-xs-5" ReadOnly="true"></asp:TextBox>
</div>
</ItemTemplate>
<FooterTemplate>
<div class="form-inline">
<asp:TextBox ID="tb_nt_sat_tot" runat="server" CssClass="tb_day col-xs-5"></asp:TextBox>
<asp:TextBox ID="tb_ot_sat_tot" runat="server" CssClass="tb_day col-xs-5"></asp:TextBox>
</div>
<asp:Label ID="checkTotalSat" runat="server" ForeColor="Red" Font-Size="7.5"></asp:Label>
</FooterTemplate>
</asp:TemplateField>

3. If user want to add new project after select the drop down list, the value inside the textbox will be missing.
The code behind for drop down list of project:

dt.Rows.Add(dr);
ViewState["Files"] = dt;

GridView1.DataSource = dt;
GridView1.DataBind();


My assumption is due to the value for user key in are not saved in DataSource (which is ViewState["Files"] ), hence it become reset to null.

Appreciate for advise. Thank You.

What I have tried:

I have tried using UpdatePanel and add bind data in

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataBind();
}
}
Posted
Updated 29-Dec-16 15:35pm
v2

1 solution

From your code i recon that you are working with web forms (i.e. you have a page object)

A possibility here is to use viewstate
Understanding ASP.NET View State[^]

That beign said a gridview doesn't as such have controls, so what very likely happens is that you have a gridview which is wired up with some edit functionality in that case you need to catch those data as they get posted and well ... what? make a new row or save and updated? I guess you need this tutorial too:
Tutorial 12: Using TemplateFields in the GridView Control[^]

So well the short of the long is that when you post something on a asp.net web.page you'll have access to the values in the Request.Form[] array and depending on if it is a client side or a server side control, after page load you could have access to it on the server side instance of a control.

UPDATE: OK, here's a solution to a similar problem using ViewState to persist the data and not using an ObjectDatasource which is propably what you want to do ultimately but sticking to the case at hand and keeping things as simple as possible with a grid :D This one will make a new grid on the initial GET and allow you to play with that as long as you keep posting by clicking the action linkbuttons on the grid.

The form:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AnittyGriddy.aspx.cs" Inherits="WebFormsProj.AnittyGriddy" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Content/bootstrap.min.css" type="text/css" rel="stylesheet"  />
    <script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>

</head>
<body>
    <form id="form1" runat="server">
        <div class="row">
            <div class="col-xs-6"><label>Project scope</label></div>
            <div class="col-xs-6">
                <asp:DropDownList ID="ProjectDD" runat="server" Width="100%" OnSelectedIndexChanged="ProjectDD_SelectedIndexChanged" AutoPostBack="true">
                    <asp:ListItem Text="All" Value="all" Selected="True" />
                    <asp:ListItem Text="Add" Value="add" />
                </asp:DropDownList>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12">
                <asp:GridView ID="TheGrid" runat="server" Width="100%" Height="100%" AutoGenerateColumns="false" DataKeyNames="ProjectName" OnRowEditing="TheGrid_RowEditing" OnRowUpdating="TheGrid_RowUpdating" AutoGenerateEditButton="true" OnRowCancelingEdit="TheGrid_RowCancelingEdit">
                    <Columns>
                        <asp:TemplateField HeaderText="Project" SortExpression="ProjectName">
                            <EditItemTemplate>
                                <asp:TextBox ID="ProjectNameText" runat="server" Text='<%#Bind("ProjectName") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="ProjectNameLabel" runat="server" Text='<%#Bind("ProjectName") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Estimate" SortExpression="ProjectEstiamte">
                            <EditItemTemplate>
                                <asp:TextBox ID="ProjectEstimateText" runat="server" Text='<%#Bind("ProjectEstimate") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="ProjectEstimateLabel" runat="server" Text='<%#Bind("ProjectEstimate") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
        </div>
    </form>
</body>
    
</html>


And the code behind:
using System;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;

namespace WebFormsProj
{
    public partial class AnittyGriddy : System.Web.UI.Page
    {      
        protected DataTable GridSource {
            get { return (DataTable)ViewState["gridsource"]; }
            set { ViewState["gridsource"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ConstructInitialGridSource();
            }
            BindGrid();
        }

        private void ConstructInitialGridSource()
        {
            var table = new DataTable();
            table.Columns.Add(new DataColumn("ProjectName", typeof(string)));
            table.Columns.Add(new DataColumn("ProjectEstimate", typeof(int)));
            table.PrimaryKey = new DataColumn[] { table.Columns[0] };
            var row = table.NewRow();
            row[0] = "Alfa";
            row[1] = 100;
            table.Rows.Add(row);
            GridSource = table;
        }

        private void BindGrid()
        {
            TheGrid.DataSource = GridSource;
            TheGrid.DataBind();
        }

        protected void ProjectDD_SelectedIndexChanged(object sender, EventArgs e)
        {
            var dropdown = (DropDownList)sender;
            var todisplayordo = dropdown.SelectedValue;
            switch (todisplayordo)
            {
                case "add":
                    {
                        var mytable = GridSource;
                        var thenew = mytable.NewRow();
                        thenew[0] = DateTime.Now.Ticks.ToString();
                        thenew[1] = 666;
                        mytable.Rows.Add(thenew);
                        GridSource = mytable;                        
                        TheGrid.EditIndex = mytable.Rows.Count - 1;
                        BindGrid();
                        break;
                    }
                default:
                    {
                        //already databound to all
                        break;
                    }
            }
        }

        protected void TheGrid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            TheGrid.EditIndex = e.NewEditIndex;
            TheGrid.DataBind();
        }

        protected void TheGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string keyField = e.Keys[0].ToString();
            var mytable = GridSource;
            var editRow = mytable.Rows.Find(e.Keys[0]);
            var keys = Request.Form.AllKeys;
            foreach (DataColumn clmn in mytable.Columns)
            {
                var idofclmn = keys.First(k => k.EndsWith(clmn.ColumnName + "Text"));
                editRow[clmn.ColumnName] = Request.Form[idofclmn];
            }
            GridSource = mytable;
            TheGrid.EditIndex = -1;
            BindGrid();
        }

        protected void TheGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            TheGrid.EditIndex = -1;
            TheGrid.DataBind();
        }
    }
}
 
Share this answer
 
v2
Comments
Member 11666220 29-Dec-16 21:17pm    
Thanks for your advise. I will read the note from link that you suggest. You are right about I'm working with web forms. Actually I want to put the image of my form in this forum. But I don't know how to post it. I would like to explain it using the image.
Member 11666220 29-Dec-16 21:37pm    
I have improved my question above. I hope that you will understand the problem in my system. Thanks a lot for reply to my question. :)
Member 11666220 30-Dec-16 20:39pm    
Thanks for your advise. I will try the code that you give and give feedback later. :)
Member 11666220 5-Jan-17 1:52am    
The solution that you provided very useful but there some problem with my update button. The value that user insert in edit mode can't be updated. Appreciate for advise.
Thomas Nielsen - getCore 5-Jan-17 3:06am    
Is the problem with the update button in my example or in the code you supplied in the question? Notice the RowEditing is actually a postback that makes your GridView change controls by setting an edit index and that the grid has passed page load before the event method executes, is it also like that for you? Observe the Request.Form.Keys collection and see how the actual edit template controls 'behind the scene' has some different names than you might expect

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900