locked
DateTimePicker in autogenerated gridview RRS feed

  • Question

  • User-106287432 posted

    I am having autogenerated gridview which took all the data from db. I want to add DateTimePicker to the fields with specific column name. I tried with DateTimePicker class but it doesn`t work because after creating the field I have to add it to Grid control and it shows me error: "Cannot convert from 'System.Windows.Forms.DateTimePicker' to 'System.Web.UI.Control'" 

    Do you have any ideas how i can add DatePicker to the gridview without using html?
    My code: 

    if (DataTable.Columns[i].ToString() == "start_date_time")
    { System.Windows.Forms.DateTimePicker dp = new System.Windows.Forms.DateTimePicker();
    dp.Name = "DateTimePicker";
    DBTableGrid.Rows[0].Cells[i + 1].Controls.Add(dp);
    }

    Thanks :)

    Friday, February 26, 2021 12:43 PM

All replies

  • User-1330468790 posted

    Hi HoneyMG,

     

    Do you have any ideas how i can add DatePicker to the gridview without using html?

    Looks like you are using a grid view from a webforms project, correct?

    If so, I am afraid you cannot move around using html. If you simply don't want to write html codes or js codes, you could add "CalendarExtender" in your aspx page.

    It is working if you put it in the grid view. You could refer to below codes.

    .aspx

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                    <Columns>
                         <asp:TemplateField HeaderText="Date">
                            <ItemTemplate>
                               <asp:TextBox ID="dateTxt" runat="server" ></asp:TextBox>
                                <ajaxToolkit:CalendarExtender ID="CalendarExtender1" TargetControlID="dateTxt"  runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

    Demo: (if the grid view is bound with few rows data)

     

    Reference:

    http://www.ajaxcontroltoolkit.net/Calendar/Calendar.aspx

    https://www.c-sharpcorner.com/UploadFile/2f59d0/use-ajaxcontroltoolkit-calendar-extender-with-Asp-Net/

     

    Hope helps.

    Best regards,

    Sean

    Monday, March 1, 2021 5:45 AM
  • User-106287432 posted

    Hey! 
    Thank you for your answer. 

    I have one more question. On my page i have dropdownlist and after user choose option from that list in gridview is loaded different table and i don`t know how many columns i will have for any table. 

    Can i write the code for CalendarExtender directly in c# like:

     if (DataTable.Columns[i].ToString() == "start_date_time")
    {
         TxtBox.Visible = false;
         CalendarExtender CalendarExtender1 = new CalendarExtender();
         CalendarExtender1.TargetControlID = DataTable.Columns[i].ToString(); 
         DBTableGrid.Rows[0].Cells[i + 1].Controls.Add(CalendarExtender1);
    }



    Monday, March 1, 2021 8:15 AM
  • User503812343 posted

    yes you can do it. Are you facing any issue with it?

    Monday, March 1, 2021 2:39 PM
  • User-106287432 posted

    Hey, yes i am facing issue. 
    This is the code that i wrote:

    if (DataTable.Columns[i].ToString() == "start_date_time")
                        {
                            
                            TxtBox.ID = DataTable.Columns[i].ToString();
                            TxtBox.ClientIDMode = ClientIDMode.Static;
                            
                            CalendarExtender1 = new CalendarExtender();
                            CalendarExtender1.TargetControlID = TxtBox.ID;
                            CalendarExtender1.ID = "CalendarExtender1"+i;
                            CalendarExtender1.Format = "dd/MM/yyyy";
    
                            DBTableGrid.Rows[0].Cells[i + 1].Controls.Add(TxtBox);
                            DBTableGrid.Rows[0].Cells[i + 1].Controls.Add(CalendarExtender1);
    
                        }

    And on html i added ScriptManagerProxy because i have ScriptManager on the Master page:

     <asp:ScriptManagerProxy ID="ScriptManagerProxy" runat="server"></asp:ScriptManagerProxy>

    I have button for new row (add new row with new values in the gridview) with Textboxes but when i add DBTableGrid.Rows[0].Cells[i + 1].Controls.Add(CalendarExtender1); I can`t add new role. Nothing happens.

    Thank you for your time

    Monday, March 1, 2021 2:50 PM
  • User503812343 posted

    are you calling this code with some condition of Page.IsPostBack?

    Monday, March 1, 2021 3:11 PM
  • User-1545767719 posted

    Do you have any ideas how i can add DatePicker to the gridview without using html?

    How about the jQuery UI DatePicker?

    jQuery UI DatePicker
    https://jqueryui.com/datepicker/

    Sample Code (Web Site Project with the C# code in .aspx file) 

    <%@ Page Language="C#" %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <script runat="server">    
      protected void GridView1_PreRender(object sender, EventArgs e)
      {
        int index = GridView1.EditIndex;
     
        if (index >= 0)
        {
          TextBox tb = 
            (TextBox)GridView1.Rows[index].FindControl("TextBox1");
     
          if (tb != null)
          {
            ClientScriptManager cs = Page.ClientScript;
            Type cstype = this.GetType();
            string csname = "jQueryUiDatepicker";
     
            if (!cs.IsClientScriptBlockRegistered(cstype, csname))
            {
              string cstext = "$(function () { $('#" 
                  + tb.ClientID + "').datepicker(); });";
     
              cs.RegisterClientScriptBlock(
                  cstype, 
                  csname, 
                  cstext, 
                  true);
            }
          }
        }
      }
    </script>
     
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
      <title>jQuery UI Datepicker in GridView</title>
      <script src="Scripts/jquery.js" type="text/javascript">
      </script>
      <script src="Scripts/jquery-ui.js" type="text/javascript">
      </script>
      <link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
      <form id="form1" runat="server">
      <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:Northwind %>" 
        SelectCommand="SELECT TOP 10 
          [OrderID], [CustomerID], [ShippedDate] 
          FROM [Orders]" 
        UpdateCommand="UPDATE [Orders] 
          SET [CustomerID] = @CustomerID, 
              [ShippedDate] = @ShippedDate 
          WHERE [OrderID] = @OrderID">
        <UpdateParameters>
          <asp:Parameter Name="CustomerID" Type="String" />
          <asp:Parameter Name="ShippedDate" Type="DateTime" />
          <asp:Parameter Name="OrderID" Type="Int32" />
        </UpdateParameters>
      </asp:SqlDataSource>
     
      <asp:GridView ID="GridView1"
        runat="server"
        AutoGenerateColumns="False"
        DataKeyNames="OrderID"
        DataSourceID="SqlDataSource1"
        OnPreRender="GridView1_PreRender">
        <Columns>
          <asp:CommandField ShowEditButton="True" />
          <asp:BoundField DataField="OrderID"
            HeaderText="OrderID"
            InsertVisible="False"
            ReadOnly="True"
            SortExpression="OrderID" />
          <asp:BoundField DataField="CustomerID"
            HeaderText="CustomerID"
            SortExpression="CustomerID" />
          <asp:TemplateField HeaderText="ShippedDate"
            SortExpression="ShippedDate">
            <EditItemTemplate>
              <asp:TextBox ID="TextBox1"
                runat="server"
                Text='<%# Bind("ShippedDate") %>'>
              </asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
              <asp:Label ID="Label1"
                runat="server"
                Text='<%# Bind("ShippedDate") %>'>
              </asp:Label>
            </ItemTemplate>
          </asp:TemplateField>
        </Columns>
      </asp:GridView>
      </form>
    </body>
    </html>

    Tuesday, March 2, 2021 1:23 AM
  • User-106287432 posted

    are you calling this code with some condition of Page.IsPostBack?

    No

    Tuesday, March 2, 2021 7:15 AM
  • User-1330468790 posted

    Hi HoneryMG,

     

    I cannot tell you what is wrong in your codes since you only provide us with a part of your codes.

    Could you please post more codes so that I can reproduce the problem and help you target it?

     

    The only thing I can confirm now is that it is allowed to add the CalendarExtender from code behind.

    You could refer to below codes and demo.

    aspx:

    <asp:GridView ID="DBTableGrid" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" />
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:templateField HeaderText="datetime"></asp:templateField>
                </Columns>
            </asp:GridView>
            <asp:Button ID="AddRowBtn" runat="server" Text="Add Text Box and Canlendar for the First Row" OnClick="AddRowBtn_Click" />

    Code behind:

    // Simulation of the database
            private static DataTable _gridviewDT;
            public static DataTable GridviewDT
            {
                get
                {
                    if (_gridviewDT is null)
                    {
                        _gridviewDT = new DataTable();
    
                        _gridviewDT.Columns.Add("ID", typeof(int));
                        _gridviewDT.Columns.Add("Name", typeof(string));
    
                        _gridviewDT.Rows.Add(1, "Name-1");
                        _gridviewDT.Rows.Add(2, "Name-2");
                        _gridviewDT.Rows.Add(3, "Name-3");
                        _gridviewDT.Rows.Add(4, "Name-4");
                        _gridviewDT.Rows.Add(5, "Name-5");
                        _gridviewDT.Rows.Add(6, "Name-6");
                        _gridviewDT.Rows.Add(7, "Name-7");
    
                    }
    
                    return _gridviewDT;
                }
                set
                {
                    _gridviewDT = value;
                }
            }
    
    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindGridView1();
                }
            }
    
    protected void BindGridView1()
            {
                DBTableGrid.DataSource = GridviewDT;
                DBTableGrid.DataBind();
            }
    
    protected void AddRowBtn_Click(object sender, EventArgs e)
            {
                TextBox TxtBox = new TextBox();
                TxtBox.ID = "abc";
                TxtBox.ClientIDMode = ClientIDMode.Static;
    
                CalendarExtender CalendarExtender1 = new CalendarExtender();
                CalendarExtender1.TargetControlID = TxtBox.ID;
                CalendarExtender1.ID = "CalendarExtender1";
                CalendarExtender1.Format = "dd/MM/yyyy";
               // the first row: Rows[0], the third cell: Cells[2]
                DBTableGrid.Rows[0].Cells[2].Controls.Add(TxtBox);
                DBTableGrid.Rows[0].Cells[2].Controls.Add(CalendarExtender1);
            }

    Demo:

     

    Best regards,

    Sean

    Tuesday, March 2, 2021 10:57 AM
  • User-106287432 posted
     private void CreateTextBoxes(bool LeaveEmptyRow, bool WriteTextToTxtBoxes)
            {
                List<GridViewRow> SelectedRow = new List<GridViewRow>();
    
                try
                {
                    //Checks to see if the update flag has been set
                    if (WriteTextToTxtBoxes)
                        SelectedRow = DecideAction(); //Loads the data from the row
    
                    //DataBind must happen after the call to DecideAction() so that the selected rows are not lost
                    DBTableGrid.DataBind();
    
                    //Add a textbox in each column
                    for (int i = 0; i < DataTable.Columns.Count; i++)
                    {
                        TextBox TxtBox = new TextBox();
                        DropDownList DropDownList1 = new DropDownList();
                        CalendarExtender CalendarExtender1;
    
                        if (WriteTextToTxtBoxes)
                        {
                            if (DataTable.Columns[i].ToString().ToLower().Contains("id"))
                            {
                                if (SelectedRow[0].Cells[i + 1].Text.ToLower().Contains("("))
                                {
                                    string[] ParsedText = SelectedRow[0].Cells[i + 1].Text.Split('(');
                                    SelectedRow[0].Cells[i + 1].Text = ParsedText[0].Trim();
                                }
                            }
                            TxtBox.Text = SelectedRow[0].Cells[i + 1].Text; //Sets the text from the Row's cells to the textboxes
    
                            if (SelectedRow[0].Cells[i + 1].Text == "&nbsp;")
                            {
                                TxtBox.Text = SelectedRow[0].Cells[i + 1].Text.Replace("&nbsp;", "");
                            }
                        }
    
                        if (i == 0)
                            TxtBox.ReadOnly = true;
    
    
                        TxtBox.ToolTip = ColumnTypes[i].Name;
                        TxtBox.Attributes.Add("class", "form-control");
                        TxtBox.ID = DataTable.Columns[i].ToString();
    
                        //.Cells[i + 1] to not add a textbox to the checkbox column
                        DBTableGrid.Rows[0].Cells[i + 1].Controls.Add(TxtBox);
    
                        snackbar.InnerText += DataTable.Columns[i].ToString() + "}}";
                    
                        //DropDownList for Bool Values 
                        if (ColumnTypes[i].ToString().Contains("System.Boolean"))
                        {
                            TxtBox.Visible = false;
                            DropDownList1.Items.Add("True");
                            DropDownList1.Items.Add("False");
                            DropDownList1.DataBind();
                            DropDownList1.Attributes.Add("class", "form-control");
                            DropDownList1.ID = DataTable.Columns[i].ToString();
                            DBTableGrid.Rows[0].Cells[i + 1].Controls.Add(DropDownList1);
                            TxtBox.Text = DropDownList1.SelectedValue;
    
    
                        }
                         if (DataTable.Columns[i].ToString() == "start_date_time")
                        {
                            TxtBox.ID = DataTable.Columns[i].ToString();
                            TxtBox.ClientIDMode = ClientIDMode.Static;
                            
                            CalendarExtender1 = new CalendarExtender();
                            CalendarExtender1.TargetControlID = TxtBox.ID;
                            CalendarExtender1.ID = "CalendarExtender1"+i;
                            CalendarExtender1.Format = "dd/MM/yyyy";
    
                            DBTableGrid.Rows[0].Cells[i + 1].Controls.Add(TxtBox);
                            DBTableGrid.Rows[0].Cells[i + 1].Controls.Add(CalendarExtender1);
    
                         
    
                        }
                   
    
                    }
                        Save.Visible = true;
                        Cancel.Visible = true;
                    
                    }
                catch (Exception ex)
                {
                    Logger.GetLogger().Error(String.Format("   {0}: {1}", ex.GetType().Name, ex.Message), CookieList);
                    throw;
                }
            }
    <asp:ScriptManagerProxy ID="ScriptManagerProxy" runat="server"></asp:ScriptManagerProxy>
                <asp:GridView ID="DBTableGrid" runat="server" CssClass="GridDataStyle" HeaderStyle-CssClass="GridStyleHeader" RowStyle-CssClass="GridStyleRows" PagerStyle-CssClass="GridStylePager" PageSize="10" AllowPaging="true" OnPageIndexChanging="Grid_Projects" ShowHeaderWhenEmpty="True">
                      
                     <Columns>
                            <asp:TemplateField ItemStyle-Width="120px">
                                <HeaderTemplate>
                                    <asp:CheckBox ID="SelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="SelectAll_CheckedChanged" />
                                    All
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="itmSelect" runat="server" AutoPostBack="true" OnCheckedChanged="itmSelect_CheckedChanged"></asp:CheckBox>
                                </ItemTemplate> 
                               
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>

    I think the problem is with that "ScriptManagerProxy" tag but i can`t add ScriptManager because it is used in the MasterPage.
    When i try to debug it throws: 

    Application Insights: Exception "System.Web.HttpUnhandledException"	

    I use AutoGeneratedGridview and i don`t need to add

    <asp:GridView ID="DBTableGrid" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" />
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:templateField HeaderText="datetime"></asp:templateField>
                </Columns>
            </asp:GridView>
            <asp:Button ID="AddRowBtn" runat="server" Text="Add Text Box and Canlendar for the First Row" OnClick="AddRowBtn_Click" />
           

    I am really thankful for helping me :)

    Tuesday, March 2, 2021 2:46 PM
  • User-1330468790 posted

    Hi HoneyMG,

     

    I have tested your codes removing some complex logic parts and the codes works except that

    • I didn't use a ScriptManagerProxy in the child page.
    • The codes provided by you do not tell me how to set the data source for the grid view control so I add it by my self
    • The code "Cells[i+1]" throws an exception of "IndexOutofRange Exception" so I simply add the CalendarExtender in the Cells[i]

    You could refer to the codes and demo at the end of this reply.

    I think the problem is with that "ScriptManagerProxy" tag but i can`t add ScriptManager because it is used in the MasterPage.
    When i try to debug it throws: 

    Application Insights: Exception "System.Web.HttpUnhandledException"

    It might be the reason of the problem. Actually, you don't need to add a ScriptManagerProxy in the child page since there is already a ScriptManager control in your Master page. Just remove it.

      

    Site.Master:

    <form runat="server">
            <asp:ScriptManager runat="server">
                <Scripts>
                    <%--To learn more about bundling scripts in ScriptManager see https://go.microsoft.com/fwlink/?LinkID=301884 --%>
                    <%--Framework Scripts--%>
                    <asp:ScriptReference Name="MsAjaxBundle" />
                    <asp:ScriptReference Name="jquery" />
                    <asp:ScriptReference Name="bootstrap" />
                    <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
                    <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
                    <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
                    <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
                    <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
                    <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
                    <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
                    <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
                    <asp:ScriptReference Name="WebFormsBundle" />
                    <%--Site Scripts--%>
                </Scripts>
            </asp:ScriptManager>
    
    ................................................... abbreviation..................................

    aspx (Child page):

    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
         <asp:GridView ID="DBTableGrid" runat="server" AutoGenerateColumns="true"></asp:GridView>
    </asp:Content>
    

    Code behind from Child page:

     // Simulation of the data
            private static DataTable _gridviewDT;
            public static DataTable DataTable
            {
                get
                {
                    if (_gridviewDT is null)
                    {
                        _gridviewDT = new DataTable();
    
                        _gridviewDT.Columns.Add("Id", typeof(int));
                        _gridviewDT.Columns.Add("Name", typeof(string));
                        _gridviewDT.Columns.Add("start_date_time", typeof(DateTime));
    
                        _gridviewDT.Rows.Add(1, "name1", new DateTime(2020, 1, 1));
                        _gridviewDT.Rows.Add(2, "name2", new DateTime(2020, 1, 1));
                        _gridviewDT.Rows.Add(3, "name3", new DateTime(2020, 1, 1));
                        _gridviewDT.Rows.Add(4, "name4", new DateTime(2020, 1, 1));
    
    
                    }
    
                    return _gridviewDT;
                }
                set
                {
                    _gridviewDT = value;
                }
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    CreateTextBoxes(true, true);
                }
            }
    
            private void CreateTextBoxes(bool LeaveEmptyRow, bool WriteTextToTxtBoxes)
            {
                List<GridViewRow> SelectedRow = new List<GridViewRow>();
    
                try
                {
    
    
                    //DataBind must happen after the call to DecideAction() so that the selected rows are not lost
                    DBTableGrid.DataSource = DataTable;
                    DBTableGrid.DataBind();
    
                    //Add a textbox in each column
                    for (int i = 0; i < DataTable.Columns.Count; i++)
                    {
                        TextBox TxtBox = new TextBox();
                        DropDownList DropDownList1 = new DropDownList();
                        CalendarExtender CalendarExtender1;
    
    
    
                        if (i == 0)
                            TxtBox.ReadOnly = true;
    
    
                        //TxtBox.ToolTip = ColumnTypes[i].Name;
                        TxtBox.Attributes.Add("class", "form-control");
                        TxtBox.ID = DataTable.Columns[i].ToString();
    
                        //.Cells[i + 1] to not add a textbox to the checkbox column
                        DBTableGrid.Rows[0].Cells[i].Controls.Add(TxtBox);
    
    
                        
                        if (DataTable.Columns[i].ToString() == "start_date_time")
                        {
                            TxtBox.ID = DataTable.Columns[i].ToString();
                            TxtBox.ClientIDMode = ClientIDMode.Static;
    
                            CalendarExtender1 = new CalendarExtender();
                            CalendarExtender1.TargetControlID = TxtBox.ID;
                            CalendarExtender1.ID = "CalendarExtender1" + i;
                            CalendarExtender1.Format = "dd/MM/yyyy";
    
                            DBTableGrid.Rows[0].Cells[i].Controls.Add(TxtBox);
                            DBTableGrid.Rows[0].Cells[i].Controls.Add(CalendarExtender1);
    
    
    
                        }
    
    
                    }
    
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
    
                }
            }

    Demo:

     

    Note that we only focus on how to add CalendarExtender in the code behind this thread.

    If we move forward, one problem would be that you cannot preserver the control after the post back since the controls would be only saved in the view state in Page Init event. However, it is another story.

      

    Best regards,

    Sean

    Thursday, March 4, 2021 11:56 AM