GridView with Dynamic DataTable

Last post 03-27-2008 10:11 PM by domesticmonkey. 3 replies.

Sort Posts:

  • GridView with Dynamic DataTable

    01-12-2008, 3:25 PM
    • Loading...
    • shinsoft
    • Joined on 09-23-2002, 7:25 PM
    • Posts 50

    I'm working with dynamically generated DataTable stored in a session that I bind to GridView. But I seem to have some issues.

    1. When trying to edit the row within GridView. RowEditing event fires and I'm able to get the textboxes to show but in the textbox instead of the value it contains <% Bind("ChargeCode") %> instead. How do I get the the value of the field to show in the textbox?

    2. After doing an EmptyInsert to populate the first row browser refresh seems to add the same row repeatedly.

    3. GridView has 3 columns and first column I would like to have Drop Down List rather than textbox. What's the proper way to do this?

    4. How do I add validation controls for the text box columns?

    Where can I find a good sample of GridView bound to dynamic DataTable that has Insert, Edit, Delete functions?

    My current code and ASPX is below.

     

    <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Temp.aspx.cs" Inherits="Temp" Title="Untitled Page" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
          <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
          <asp:GridView ID="GridView1" ShowFooter="true" runat="server" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"   
             OnRowCommand="GridView1_RowCommand1" AutoGenerateColumns="false" OnRowEditing="GridView1_RowEditing">
          <Columns>
             <asp:TemplateField>
                <ItemTemplate>
                   <asp:Button Text="Edit" CommandName="Edit" CausesValidation="false" runat="server" ID="btEdit" /> 
                   <asp:Button Text="Delete" CommandName="Delete" CausesValidation="false" runat="server" ID="btDelete" />
                </ItemTemplate>
                <EditItemTemplate>
                   <asp:Button Text="Update" CommandName="Update" CausesValidation="true" runat="server" ID="btUpdate" /> 
                   <asp:Button Text="Cancel" CommandName="Cancel" CausesValidation="false" runat="server" ID="btCancel" />
                </EditItemTemplate>
                <FooterTemplate>
                   <asp:Button Text="Insert" CommandName="Insert" CausesValidation="true" runat="server" ID="btInsert" /> 
                   <asp:Button Text="Cancel" CommandName="Cancel" CausesValidation="false" runat="server" ID="btCancel" />
                </FooterTemplate>
             </asp:TemplateField>
             <asp:TemplateField >
                <HeaderTemplate>
                   <asp:Label ID="lblChargeCodeHeader" Text="Charge Code" runat="server"></asp:Label>
                </HeaderTemplate>
                <ItemTemplate>
                   <asp:Label ID="lblChargeCodeItem" Text='<%# Eval("ChargeCode") %>' runat="server"></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                      <asp:TextBox ID="txtChargeCodeEdit" runat="server" Text='<% Bind("ChargeCode") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                      <asp:TextBox ID="txtChargeCodeInsert" runat="server" Text="" ></asp:TextBox>
                </FooterTemplate>
                </asp:TemplateField>
             <asp:TemplateField >
                <HeaderTemplate>
                   <asp:Label ID="lblChargeAmountHeader" Text="Charge Amount" runat="server"></asp:Label>
                </HeaderTemplate>
                <ItemTemplate>
                   <asp:Label ID="lblChargeAmountItem" Text='<%# Eval("ChargeAmount") %>' runat="server"></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                      <asp:TextBox ID="txtChargeAmountEdit" runat="server" Text='<% Bind("ChargeAmount") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                      <asp:TextBox ID="txtChargeAmountInsert" runat="server" Text="" ></asp:TextBox>
                </FooterTemplate>
                </asp:TemplateField>
             <asp:TemplateField >
                <HeaderTemplate>
                   <asp:Label ID="lblStopNumberHeader" Text="Stop #" runat="server"></asp:Label>
                </HeaderTemplate>
                <ItemTemplate>
                   <asp:Label ID="lblStopNumber" Text='<%# Eval("StopNumber") %>' runat="server"></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                      <asp:TextBox ID="txtStopNumberEdit" runat="server" Text='<% Bind("StopNumber") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                      <asp:TextBox ID="txtStopNumberInsert" runat="server" Text="" ></asp:TextBox>
                </FooterTemplate>
                </asp:TemplateField>
             </Columns>
             <EmptyDataTemplate>
                   <asp:Button ID="cmdEmptyInsert" Text="Insert" runat="server" CommandName="EmptyInsert" UseSubmitBehavior="False" />
                   <asp:Button Text="Cancel" CommandName="Cancel" CausesValidation="false" runat="server" ID="btCancel" />
                   <asp:TextBox ID="txtChargeCodeEmptyInsert" runat="server"></asp:TextBox>
                   <asp:TextBox ID="txtChargeAmountEmptyInsert" runat="server"></asp:TextBox>
                   <asp:TextBox ID="txtStopNumberEmptyInsert" runat="server"></asp:TextBox>
                </EmptyDataTemplate>
             </asp:GridView>
    </asp:Content>
    
    
      
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class Temp : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Create dummy data
                DataTable dt = new DataTable();
                dt.Columns.Add("ChargeCode");
                dt.Columns.Add("ChargeAmount");
                dt.Columns.Add("StopNumber");
    
                Session["ChargeDataTable"] = dt;
                
                //Bind the gridview
                BindGrid();
            }
    
            //Recurses through the controls to show the naming of each individual control that is currently in the gridview
            //RecurseControls(GridView1.Controls[0].Controls);
            //Label1.Text += GridView1.Controls[0].Controls[0].GetType().Name + "<br />";  
        }
    
        void RecurseControls(ControlCollection ctls)
        {
            foreach (Control ctl in ctls)
            {
                if (!ctl.HasControls())
                    Label1.Text += ctl.ClientID + " " + ctl.GetType().Name + "&lt;br />";
                else
                    RecurseControls(ctl.Controls);
            }
        }
    
        void BindGrid()
        {
            DataTable dt = new DataTable();
            dt = (DataTable)Session["ChargeDataTable"];
    
            //Bind the gridview
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    
        void AddNewCharge(string ChargeCode, string ChargeAmount, string StopNumber)
        {
            DataTable dt = new DataTable();
    
            dt = (DataTable)Session["ChargeDataTable"];
    
            DataRow dr = dt.NewRow();
            dr["ChargeCode"] = ChargeCode;
            dr["ChargeAmount"] = ChargeAmount;
            dr["StopNumber"] = StopNumber;
            dt.Rows.Add(dr);
    
            Session["ChargeDataTable"] = dt;
    
            BindGrid();
        }
    
        protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EmptyInsert")
            {
                //handle insert here
                TextBox ChargeCode = GridView1.Controls[0].Controls[0].FindControl("txtChargeCodeEmptyInsert") as TextBox;
                TextBox ChargeAmount = GridView1.Controls[0].Controls[0].FindControl("txtChargeAmountEmptyInsert") as TextBox;
                TextBox StopNumber = GridView1.Controls[0].Controls[0].FindControl("txtStopNumberEmptyInsert") as TextBox;
    
                AddNewCharge(ChargeCode.Text, ChargeAmount.Text, StopNumber.Text);
    
                //Label1.Text = string.Format("You would have inserted the name : <b>{0}</b> from the emptydatatemplate",tbEmptyInsert.Text);
            }
    
            if (e.CommandName == "Insert")
            {
                //handle insert here
                TextBox ChargeCode = GridView1.FooterRow.FindControl("txtChargeCodeInsert") as TextBox;
                TextBox ChargeAmount = GridView1.FooterRow.FindControl("txtChargeAmountInsert") as TextBox;
                TextBox StopNumber = GridView1.FooterRow.FindControl("txtStopNumberInsert") as TextBox;
    
                AddNewCharge(ChargeCode.Text, ChargeAmount.Text, StopNumber.Text);
                //Label1.Text = string.Format("You would have inserted the name :  <b>{0}</b> from the footerrow", tbInsert.Text);
            }
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            BindGrid();
        }
    }
    
     
  • Re: GridView with Dynamic DataTable

    01-13-2008, 12:02 AM

    1) Text='<% # Bind("ChargeCode") %>' instead of Text='<% Bind("ChargeCode") %>'

    2) use ViewState instead of session

    dt = (DataTable) ViewState["ChargeDataTable"]; like this

    3)

    <asp:DropDownList ID="txtInwordNoEmptyInsert" runat="server" ValidationGroup="as1">

    <asp:ListItem Selected="True" Text="prod1" Value="prod1">Product1</asp:ListItem>

    <asp:ListItem Text="prod2" Value="prod2">Product2</asp:ListItem>

    </asp:DropDownList>

    DropDownList ChargeCode = GridView1.Controls[0].Controls[0].FindControl("txtChargeCodeEmptyInsert") as DropDownList ; 'like this at both place

    4)

     <EmptyDataTemplate>

    <asp:Button ValidationGroup="as1" ID="cmdEmptyInsert" Text="Insert" runat="server" CommandName="EmptyInsert" UseSubmitBehavior="False" />

    <asp:Button Text="Cancel" CommandName="Cancel" CausesValidation="false" runat="server" ID="btCancel" />

    <asp:DropDownList ID="txtInwordNoEmptyInsert" runat="server" ValidationGroup="as1">

    <asp:ListItem Selected="True" Text="prod1" Value="prod1">Product1</asp:ListItem>

    <asp:ListItem Text="prod2" Value="prod2">Product2</asp:ListItem>

    </asp:DropDownList>

    <asp:TextBox ValidationGroup="as1" ID="txtReceiptQtyEmptyInsert" runat="server" ></asp:TextBox>

    <asp:RequiredFieldValidator ValidationGroup="as1" ID="RequiredFieldValidator1" SetFocusOnError="true"

    ControlToValidate="txtReceiptQtyEmptyInsert" runat="server" ErrorMessage="*"></asp:RequiredFieldValidator>

    <asp:TextBox ID="txtReceiptdateEmptyInsert" ValidationGroup="as1" runat="server"></asp:TextBox>

    </EmptyDataTemplate> like this at both place

    Bhumika
    ..............................
    All things are availabel,you have to just find it out.
  • Re: GridView with Dynamic DataTable

    01-13-2008, 12:02 AM
    Answer

    1) Text='<% # Bind("ChargeCode") %>' instead of Text='<% Bind("ChargeCode") %>'

    2) use ViewState instead of session

    dt = (DataTable) ViewState["ChargeDataTable"]; like this

    3)

    <asp:DropDownList ID="txtInwordNoEmptyInsert" runat="server" ValidationGroup="as1">

    <asp:ListItem Selected="True" Text="prod1" Value="prod1">Product1</asp:ListItem>

    <asp:ListItem Text="prod2" Value="prod2">Product2</asp:ListItem>

    </asp:DropDownList>

    DropDownList ChargeCode = GridView1.Controls[0].Controls[0].FindControl("txtChargeCodeEmptyInsert") as DropDownList ; 'like this at both place

    4)

     <EmptyDataTemplate>

    <asp:Button ValidationGroup="as1" ID="cmdEmptyInsert" Text="Insert" runat="server" CommandName="EmptyInsert" UseSubmitBehavior="False" />

    <asp:Button Text="Cancel" CommandName="Cancel" CausesValidation="false" runat="server" ID="btCancel" />

    <asp:DropDownList ID="txtInwordNoEmptyInsert" runat="server" ValidationGroup="as1">

    <asp:ListItem Selected="True" Text="prod1" Value="prod1">Product1</asp:ListItem>

    <asp:ListItem Text="prod2" Value="prod2">Product2</asp:ListItem>

    </asp:DropDownList>

    <asp:TextBox ValidationGroup="as1" ID="txtReceiptQtyEmptyInsert" runat="server" ></asp:TextBox>

    <asp:RequiredFieldValidator ValidationGroup="as1" ID="RequiredFieldValidator1" SetFocusOnError="true"

    ControlToValidate="txtReceiptQtyEmptyInsert" runat="server" ErrorMessage="*"></asp:RequiredFieldValidator>

    <asp:TextBox ID="txtReceiptdateEmptyInsert" ValidationGroup="as1" runat="server"></asp:TextBox>

    </EmptyDataTemplate> like this at both place

    Bhumika
    ..............................
    All things are availabel,you have to just find it out.
  • Re: GridView with Dynamic DataTable

    03-27-2008, 10:11 PM

    In answer to your last question: Where can I find a good sample of GridView bound to dynamic DataTable that has Insert, Edit, Delete functions?

     

    http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx

    http://aspalliance.com/1125_Dynamically_Templated_GridView_with_Edit_Delete_and_Insert_Options 

Page 1 of 1 (4 items)
Microsoft Communities
Page view counter