• Show Calendar Control in ASP.NET GridView Control using Javascript

    Posted on June 5, 2012 by in ASP.NET, C#, Dotnet

    GridView displays the values of a data source in a table where each column represents a field and each row represents a record.  In this article, I am going to explain how use a Calendar Server Control in grid view control.

    If you are new to using GridView, you could refer to following articles.
    Using GridView in ASP.NET & C# — PART 1
    Using GridView in ASP.NET & C# — PART 2
    How to Insert, Update & Delete rows in ASP.NET GridView Control

    Database Connection
    I am using Adventure Works provided by Microsoft as datasource. Open web.config and add following entry to connection strings element.

    <add name="Sql" connectionString="Data Source=(local);
         Initial Catalog= TEST;User=testuser;Password=testuser;"
         providerName="System.Data.SqlClient"/>
    

    DataSource
    I am using SQLDataSource to load & update the products from/to database. The ConnectionString property of the SqlDataSource control specifies how to connect to the database. This property can be a hard-coded connection string or can point to a connection string in a Web.config file as shown in the code given above. The SelectCommand property specifies the SQL statement to execute to retrieve the data. The UpdateCommand persists changes to the database. I have created some UpdateParameters which would be applied (set) in the Update event handler of the GridView.

    <asp:SqlDataSource ID="sqlDSProducts" runat="server"
        ConnectionString="<%$ ConnectionStrings:Sql %>"
        SelectCommand="Select top 10 ProductID, Name, ProductNumber, ListPrice, DiscontinuedDate from Production.Product"
        UpdateCommand="UPDATE Production.Product SET Name=@NewProductName,
                            ProductNumber=@ProductNumber, ListPrice=@Price,
                            DiscontinuedDate=@DiscontinuedDate
                             WHERE ProductID=@ProductID">
            <UpdateParameters>
                <asp:Parameter Name="ProductName" Type="String" />
                <asp:Parameter Name="ProductNumber"   Type="String" />
                <asp:Parameter Name="Price"  Type="Decimal" />
                <asp:Parameter Name="DiscontinuedDate"  Type="DateTime" />
                <asp:Parameter Name="ProductID"  Type="Int32" />
            </UpdateParameters>
        </asp:SqlDataSource>
    

    Page Design
    Create a new aspx page and name it as GridViewCalendar.aspx. Open the aspx file in design mode and add the following code in div tag.  “ProductID” attribute is rendered in a bound field. For rendering other attributes (ProductName , ProductNumber, ListPrice & Discontinued Date), I am using TemplateField.   In order to bind the SQLDataSource created above to the grid, set the “DataSourceID” property of the GridView to “sqlDSProducts” (ID property value of SQLDataSource).

    <asp:gridview id="gvProducts"
              autogeneratecolumns="False"
              emptydatatext="No data available."
              DataSourceID = "sqlDSProducts"
              runat="server" DataKeyNames="ProductID"
              OnRowEditing="gvProducts_RowEditing"
              OnRowCancelingEdit="gvProducts_RowCancelingEdit"
              onrowupdating="gvProducts_RowUpdating"
              CssClass="tableClass">
                <Columns>
                    <asp:BoundField DataField="ProductID" HeaderText="Product ID" ReadOnly="true"/>
                    <asp:TemplateField headertext="Product Number">
                            <ItemTemplate> <%#Eval("ProductNumber")%></ItemTemplate>
                            <EditItemTemplate>
                                    <asp:TextBox Width="80px" id="txtProductNumber" text='<%#Eval("ProductNumber")%>'
                                   runat="server"/>
                        </EditItemTemplate>
                    </asp:TemplateField>
                     <asp:TemplateField headertext="Product Name">
                            <ItemTemplate> <%#Eval("Name")%></ItemTemplate>
                         <EditItemTemplate>
                          <asp:TextBox id="txtProductName" text='<%#Eval("Name")%>'
                             runat="server"/>
                        </EditItemTemplate>
                    </asp:TemplateField>
                     <asp:TemplateField headertext="Price">
                         <ItemTemplate><%#Eval("ListPrice","{0:c}")%></ItemTemplate>
                         <ItemStyle Width="80px" />
                         <EditItemTemplate>
                          <asp:TextBox id="txtListPrice" text='<%#Eval("ListPrice")%>'
                                   Width="80px" runat="server"/>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField headertext="Discontinued Date">
                         <ItemTemplate> <%#Eval("DiscontinuedDate","{0:d}")%></ItemTemplate>
                         <EditItemTemplate>
                         <img id="imgCalendar" src="calendar.jpg" height="25px" style="cursor:pointer"
                            onclick="fnShowCalendar('<%# ((GridViewRow)Container).FindControl("tbxDate").ClientID %>', 300, 180);" />
                          <asp:TextBox ID="tbxDate" runat="server" Text='<%#Eval("DiscontinuedDate","{0:d}")%>'></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
               <asp:TemplateField>
                   <ItemTemplate>
                       <asp:LinkButton ID="btnedit" runat="server" CommandName="Edit" Text="Edit"/>
                   </ItemTemplate>
                   <EditItemTemplate>
                       <asp:LinkButton ID="btnupdate" runat="server"
    			                            CommandName="Update" Text="Update" />
                       <asp:LinkButton ID="btncancel" runat="server"
    			                    CommandName="Cancel" Text="Cancel"/>
                   </EditItemTemplate>
                </asp:TemplateField>
                </Columns>
            </asp:gridview>
    

    Click on “Edit” link and the grid would go into edit mode.  If you look at event handling function, you would notice that we are setting edit index of the grid to the row you trying to edit

    protected void gvProducts_RowEditing(object sender,
                                            GridViewEditEventArgs e)
    {
        gvProducts.EditIndex = e.NewEditIndex;
    }
    

    When user clicks on the calendar image, we call a javascript function fnShowCalendar. We pass input textbox, width of the calendar page to be set, height of the calendar page to be set as arguments.  In this function, we open a new window and set “DatePicker.aspx” as its source and pass those 3 arguments in the query string.

    <script type="text/javascript">
        function fnShowCalendar(ClientID, width, height) {
            var popup = null;
            settings = 'width=' + width + ',height=' + height + ',location=no,directories=no,menubar=no,toolbar=no,status=no,scrollbars=no,resizable=no,dependent=no';
            popup = window.open('DatePicker.aspx?Ctl=' + ClientID, 'DatePicker', settings);
            popup.focus();
        }
    </script>
    

    Create a new page DatePicker.aspx. This is our calendar selection page. The page design is pretty simple. We just have a calendar server control.

    <asp:calendar id="Calendar1" runat="server"
      nextprevformat="shortmonth" CssClass="MyCalendar"
      daynameformat="firsttwoletters" ondayrender="OnDayRender">
      <TitleStyle Font-Size="14px" Font-Bold="True" BorderWidth="2px"
         ForeColor="#000055"></TitleStyle>
    </asp:calendar>
    

    We would want to call a javascript function fnSetDate when user selects a day. In the ondayrender event, we add a javascript call to all visible days.

    protected void OnDayRender(object sender, DayRenderEventArgs e)
            {
                HyperLink lnk = new HyperLink();
                lnk.Text = ((LiteralControl)e.Cell.Controls[0]).Text;
                lnk.Attributes.Add("href", "javascript:fnSetDate('" +
                e.Day.Date.ToShortDateString() + "')");
                e.Cell.Controls.Clear();
                e.Cell.Controls.Add(lnk);
            }
    

    When the user clicks on the day javascript function fnSetDate is invoked. In this function, we get the name of the input control where we were supposed to set the selected date from the query string. We get reference to the control based on this name and will set the selected date.

    <script type="text/javascript">
    function fnSetDate(dateValue)
    {
    // retrieve the date control name from the querystring
    // that is the name of the input control on the parent form
    // that the user want to set with the clicked date
    Var ctl = window.location.search.substr(1).substring(4);
    window.opener.document.forms[0].elements[ctl].value = dateValue;
    // close this popup
    self.close();
    }
    </script>
    

    Run the application and you would see the following page with top 10 products from the database.

    Click on “Edit” button on the second row and gridview would enter into “Edit” mode. You would notice that the data for the selected index is rendered in the controls specified in “EditItemIndex”.

    Click on Calendar image and “DatePicker.aspx” would be popped up as shown below:

    Select June 26, 2012 from the calendar control. The value be passed to “Discontinued Date” input box and calendar control would be closed. Change product number, product and  price to 50. When you click on “Update” button, gvProducts_RowUpdating event is fired. Based on the selected row, get the gridviewrow. Once you get the gridviewrow, you could search for the content controls and get the updated values. Once we have the latest values, we set those values to update parameters of the sqlDsProducts. Finally, we simply need to call Update function of sqlDsProducts  to perisist changes to database.

    protected void gvProducts_RowUpdating(Object sender,
                                    GridViewUpdateEventArgs e)
    {
    
        // Get the product id of the selected product    
        string ID = gvProducts.DataKeys[e.RowIndex].Value.ToString();
    
        // Get the GridViewRow object that represents the row being edited
        // from the Rows collection of the GridView control.            
        GridViewRow row = gvProducts.Rows[e.RowIndex];
    
        // Get the controls that contain the updated values. In this
        // example, the updated values are contained in the TextBox 
        // controls declared in the edit item templates of each TemplateField 
        // column fields in the GridView control.
        TextBox txtProductNumber = (TextBox)row.FindControl("txtProductNumber");
        TextBox txtProductName = (TextBox)row.FindControl("txtProductName");
        TextBox txtListPrice = (TextBox)row.FindControl("txtListPrice");
        TextBox DateTextBox = (TextBox)row.FindControl("tbxDate");
    
        sqlDSProducts.UpdateParameters["ProductName"].DefaultValue = txtProductName.Text;
        sqlDSProducts.UpdateParameters["ProductNumber"].DefaultValue = txtProductNumber.Text;
        sqlDSProducts.UpdateParameters["Price"].DefaultValue = txtListPrice.Text;
        sqlDSProducts.UpdateParameters["DiscontinuedDate"].DefaultValue = DateTextBox.Text;
        sqlDSProducts.UpdateParameters["ProductID"].DefaultValue = ID.ToString();
        sqlDSProducts.Update();
        
        gvProducts.EditIndex = -1;
        gvProducts.DataBind();
    }
    

    Cancel Edit:
    If you ever want to get out the edit mode, click on “Cancel” button and you would be back in view mode.

    protected void gvProducts_RowCancelingEdit
            (object sender, GridViewCancelEditEventArgs e)
    {
        gvProducts.EditIndex = -1;
        gvProducts.DataBind();
    }
    
    Be Sociable, Share!
      Post Tagged with ,

    Written by

    Software architect with over 10 years of proven experience in designing & developing n-tier and web based software applications, for Finance, Telecommunication, Manufacturing, Internet and other Commercial industries. He believes that success depends on one's ability to integrate multiple technologies to solve a simple as well as complicated problem.

    View all articles by

    Email : [email protected]

    One Responseso far.

    1. nice artical, it helped me.

    Leave a Reply