1

I am trying to attach a datepicker to the startdate column of my dynamic gridview using javascript. I am choosing to use javascript so that even when the user adds a row (by clicking the add button at the bottom of the grid), the datepicker will be available at the new row. Please see my code below.

The current javascript for manipulating a the contact column of the grid.

<script src="javascript/jquery-ui-1.7.1.custom.min.js" type="text/javascript"></script>
<script type="text/javascript" src="javascript/jquery-1.3.2.min.js"></script>
 <script type="text/javascript">
        $(document).ready(function () {
           $(".ddlClass").change(function () {
              var txt = $(this).closest("tr").find(".txtClass");
              if ($(this).val() == "First") {
                 txt.css("background", "#cccccc");
                 txt.attr("disabled", "disabled");
              }
              else {
                 txt.css("background", "#ffffff");
                 txt.attr("disabled","");                                         
              }
            }); 
        });
 </script>

The Gridview.

<div>
    <asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowCreated="Gridview1_RowCreated">
        <Columns>
            <asp:BoundField DataField="RowNumber" HeaderText="No." />                
            <asp:TemplateField HeaderText="AGE">
                <ItemTemplate>
                    <asp:TextBox runat="server" ID="StartDate" />  
                </ItemTemplate>                        
            </asp:TemplateField>
            <asp:TemplateField HeaderText="CONTACT">
                <ItemTemplate>
                    <asp:DropDownList ID="dlstContact" runat="server" AppendDataBoundItems="true" CssClass="ddlClass">
                            <asp:ListItem Text="--Select--" Value="" />
                            <asp:ListItem>First</asp:ListItem>
                            <asp:ListItem>Repeat</asp:ListItem>                               
                        </asp:DropDownList> 
                </ItemTemplate>                        
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ContactDate">
                <ItemTemplate>
                    <asp:TextBox runat="server" ID="ContactDate" CssClass="txtClass"></asp:TextBox>                         
                </ItemTemplate>                        
            </asp:TemplateField>
        </Columns>
    </asp:gridview>
    <br />
    <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click" />

</div>

The ButtonAdd_Click calls the following function

private void AddNewRowToGrid()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {

            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

            DataRow drCurrentRow = null;

            if (dtCurrentTable.Rows.Count > 0)
            {

                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {

                    //extract the TextBox values

                    TextBox idno = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("txtIDNO");
                    TextBox names = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txtNames");
                    DropDownList sex = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("dlstSex");
                    TextBox age = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("txtAge");
                    DropDownList maritalstatus = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("dlstMaritalstatus");
                    DropDownList sector = (DropDownList)Gridview1.Rows[rowIndex].Cells[6].FindControl("dlstSector");
                    DropDownList attachment = (DropDownList)Gridview1.Rows[rowIndex].Cells[7].FindControl("dlstAttachment");
                    DropDownList contact = (DropDownList)Gridview1.Rows[rowIndex].Cells[8].FindControl("dlstContact");
                    jQueryDatePicker contactdate = (jQueryDatePicker)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtContactdate");
                    DropDownList session = (DropDownList)Gridview1.Rows[rowIndex].Cells[10].FindControl("dlstSession");

                    drCurrentRow = dtCurrentTable.NewRow();

                    drCurrentRow["RowNumber"] = i + 1;

                    dtCurrentTable.Rows[i - 1]["IDNO"] = idno.Text;
                    dtCurrentTable.Rows[i - 1]["Names"] = names.Text;
                    dtCurrentTable.Rows[i - 1]["Sex"] = sex.Text;
                    dtCurrentTable.Rows[i - 1]["Age"] = age.Text;
                    dtCurrentTable.Rows[i - 1]["MaritalStatus"] = maritalstatus.Text;
                    dtCurrentTable.Rows[i - 1]["Sector"] = sector.Text;
                    dtCurrentTable.Rows[i - 1]["Attachment"] = attachment.Text;
                    dtCurrentTable.Rows[i - 1]["Contact"] = contact.Text;
                    dtCurrentTable.Rows[i - 1]["ContactDate"] = contactdate.Text;
                    dtCurrentTable.Rows[i - 1]["Session"] = session.Text;

                    rowIndex++;

                }

                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                Gridview1.DataSource = dtCurrentTable;
                Gridview1.DataBind();

            }

        }

        else
        {

            Response.Write("ViewState is null");

        }

        //Set Previous Data on Postbacks
        SetPreviousData();

    }

And the setPreviousData function is here.

 private void SetPreviousData()
    {

        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {

            DataTable dt = (DataTable)ViewState["CurrentTable"];

            if (dt.Rows.Count > 0)
            {

                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    TextBox idno = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("txtIDNO");

                    TextBox names = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txtNames");

                    DropDownList sex = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("dlstSex");

                    TextBox age = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("txtAge");

                    DropDownList maritalstatus = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("dlstMaritalStatus");

                    DropDownList sector = (DropDownList)Gridview1.Rows[rowIndex].Cells[6].FindControl("dlstSector");

                    DropDownList attachment = (DropDownList)Gridview1.Rows[rowIndex].Cells[7].FindControl("dlstAttachment");

                    DropDownList contact = (DropDownList)Gridview1.Rows[rowIndex].Cells[8].FindControl("dlstContact");

                    //jQueryDatePicker contactdate = (jQueryDatePicker)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtContactDate");
                    TextBox contactdate = (TextBox)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtContactDate");

                    DropDownList session = (DropDownList)Gridview1.Rows[rowIndex].Cells[10].FindControl("dlstSession");

                    age.Attributes.Add("onkeypress", "var key; if(window.event){ key = event.keyCode;}else if(event.which){ key = event.which;} return (key == 45 || key == 13 || key == 8 || key == 9 || key == 189 || (key >= 48 && key <= 58) )");

                    contactdate.Attributes.Add("onkeypress", "");

                    idno.Text = dt.Rows[i]["IDNO"].ToString();

                    names.Text = dt.Rows[i]["Names"].ToString();

                    sex.Text = dt.Rows[i]["Sex"].ToString();

                    age.Text = dt.Rows[i]["Age"].ToString();

                    maritalstatus.Text = dt.Rows[i]["MaritalStatus"].ToString();

                    sector.Text = dt.Rows[i]["Sector"].ToString();

                    attachment.Text = dt.Rows[i]["Attachment"].ToString();

                    contact.Text = dt.Rows[i]["Contact"].ToString();

                    contactdate.Text = dt.Rows[i]["ContactDate"].ToString();

                    session.Text = dt.Rows[i]["Session"].ToString();


                    rowIndex++;

                }

            }

        }

    }

Please not i editted the grid in this post just to focus our discussion otherwise the functions called by the click event have some detailed code for columns i eliminated from the grid.

Any help will be highly appreciated. Even if its not a javascript solution.

Michael

5
  • Can you share the code you're using in your code-behind in "ButtonAdd_Click"? Commented Mar 31, 2011 at 13:41
  • Alison, i have updated my question to include all the functions in my code behind. Please note that i had editted the grid just to focus the discussion. Otherwise the two function have code to handle other columns not included in the grid here. Thanks Commented Mar 31, 2011 at 15:26
  • What is the problem you're facing? Is it that the datepicker is not working? Commented Mar 31, 2011 at 17:24
  • Exactly. The datepicker just does not show up. Commented Apr 1, 2011 at 5:17
  • The easiest solution that I was able to find is here. stackoverflow.com/questions/3650009/… Commented Feb 27, 2014 at 21:21

2 Answers 2

0

jQueryUI's datepicker is a clientside solution. All .NET sees in the codebehind is a textbox control with a date value.

Your $(document).ready function probably needs to read something like this:

$(document).ready(function () {
    $("select.ddlClass").change(function () {
        var txt = $(this).closest("tr").find(".txtClass");
        if ($(this).val() == "First") {
            txt.css("background", "#cccccc");
            txt.attr("disabled", "disabled");
        }
        else {
            txt.css("background", "#ffffff");
            txt.attr("disabled","");                                         
        }
    });

   $("input.txtClass").datepicker({
       // Add config options here
   });
});

Notice that I modified your original selector to read "select.ddlClass". Any time you can add a tagname to a class selector you should. The performance increase can be dramatic as your site grows.

In BtnAdd_Click, you'll want to replace this:

jQueryDatePicker contactdate = (jQueryDatePicker)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtContactdate");

with this

TextBox contactdate = (TextBox)Gridview1.Rows[rowIndex].Cells[9].FindControl("txtContactdate");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you chprpipr. Its been very very helpful.
0

I also encountered similar problem

<asp:GridView ID="GridView1" runat="server" Height="300px"
            AllowPaging="true" 
            ShowFooter="True"           
            AutoGenerateColumns="false"
            OnRowDeleting="GridView1_RowDeleting" 
            OnRowEditing="GridView1_RowEditing"
            OnRowUpdating="GridView1_RowUpdating"
            OnRowCancelingEdit="GridView1_RowCancelingEdit"
            OnRowCommand="GridView1_RowCommand"  
            >
        <Columns> 
        <asp:TemplateField HeaderText="Holiday"> 
            <EditItemTemplate> 
                <asp:TextBox ID="txtEditHoliday" runat="server" Text='<%# Eval("HOLIDY_CAL_NM") %>'></asp:TextBox> 
            </EditItemTemplate>
            <FooterTemplate> 
                <asp:TextBox ID="txtNewHoliday" runat="server"></asp:TextBox>
            </FooterTemplate>
            <ItemTemplate> 
                <asp:Label ID="lblHoliday" runat="server" Text='<%#Eval("HOLIDY_CAL_NM")%>'></asp:Label> 
            </ItemTemplate>
        </asp:TemplateField>                 
        <asp:TemplateField HeaderText="Date">
           <EditItemTemplate> 
                <asp:TextBox ID="txtEditDate" runat="server" Text='<%# GetDate(Eval("CAL_DT")) %>' OnLoad="DisplayDatePicker1"  ReadOnly="true"></asp:TextBox> 
           </EditItemTemplate>
           <FooterTemplate> 
                <asp:TextBox ID="txtNewDate"  runat="server"  OnLoad="DisplayDatePicker2" ReadOnly="true"></asp:TextBox>
           </FooterTemplate> 
           <ItemTemplate> 
                <asp:Label ID="lblDate" runat="server" Text='<%# GetDate(Eval("CAL_DT")) %>'></asp:Label> 
           </ItemTemplate> 
        </asp:TemplateField> 



    protected void DisplayDatePicker1(object sender, EventArgs e)
    {
        StringBuilder scriptText = new StringBuilder();
        string clientID = (sender as TextBox).ClientID;
        scriptText.Append("$(function() {");
        scriptText.Append("var DateSelector1 = $('#" + clientID + "'); ");
        scriptText.Append("DateSelector1.datepicker();");
        scriptText.Append(" });");
        this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
                       "DateScript1", scriptText.ToString(), true); 
    }

2 Comments

This is a good soultion. How do i deal with the line "string CliendID = (sender as TextBox).ClientID; " Its says Object reference not set to an instance of an object. Please help.
Great. I worked that out because i needed to attach the onLoad to the textBox itself. Now do i need to attach references to jquery in the header section. Apparently am using this inside a contentplaceholder. Thanks

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.