开发者

Asp.net add a datepicker to dynamic gridview using javascript

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


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");


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); 
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜