Asp.net 使用 javascript 将日期选择器添加到动态 gridview

发布于 2024-10-28 19:11:25 字数 8544 浏览 2 评论 0原文

我正在尝试使用 javascript 将日期选择器附加到动态 gridview 的开始日期列。我选择使用 javascript,这样即使用户添加一行(通过单击网格底部的添加按钮),日期选择器也将在新行中可用。请参阅下面我的代码。

当前用于操作网格的联系人列的 javascript。

<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>

网格视图。

<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>

ButtonAdd_Click 调用以下函数

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

    }

,setPreviousData 函数在这里。

 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++;

                }

            }

        }

    }

请注意,我在这篇文章中编辑网格只是为了集中我们的讨论,否则单击事件调用的函数有一些我从网格中删除的列的详细代码。

任何帮助将不胜感激。即使它不是一个 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月野兔 2024-11-04 19:11:25

jQueryUI 的日期选择器是一个客户端解决方案。 .NET 在代码隐藏中看到的所有内容都是带有日期值的文本框控件。

您的 $(document).ready 函数可能需要读取如下内容:

$(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
   });
});

请注意,我修改了您的原始选择器以读取“select.ddlClass”。任何时候您都可以将标记名添加到类选择器中。随着站点的增长,性能的提升可能会非常显着。

在 BtnAdd_Click 中,您需要将其替换

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

为:

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

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");
爱情眠于流年 2024-11-04 19:11:25

我也遇到类似的问题

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

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); 
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文