Bind Events in ASP.Net Calendar control from Database using C# and VB.Net

Last Reply 4 months ago By dharmendr

Posted 4 months ago

hello,

i want to get dates and description from database from page load and assign values to asp.net calendar

i have following fields in sql column

date                               desc

01/July/2019                    party time

02/July/2019                   holiday

please advice

<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>

 

You are viewing reply posted by: dharmendr 4 months ago.
Posted 4 months ago

Hi nauna,

Check this example. Now please take its reference and correct your code.

You have to use Calendar OnDayRender event to change the cell value.

HTML

<asp:Calendar ID="Calendar1" runat="server" Width="500px" BorderColor="Red" ForeColor="#663399"
    OnDayRender="Calendar1_DayRender" ShowGridLines="True"></asp:Calendar>

Code

C#

private System.Data.DataTable GetData()
{
    System.Data.DataTable dt = new System.Data.DataTable();
    dt.Columns.Add("Date");
    dt.Columns.Add("Desc");
    dt.Rows.Add("01/July/2019 ", "party time");
    dt.Rows.Add("02/July/2019", "holiday");
    dt.Rows.Add("30/June/2019", "holiday");
    dt.Rows.Add("15/August/2019", "holiday");
    return dt;
}

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    System.Data.DataTable dt = GetData();
    foreach (System.Data.DataRow row in dt.Rows)
    {
        if (Convert.ToDateTime(e.Day.Date) == Convert.ToDateTime(row["Date"]))
        {
            e.Cell.Controls.Add(new Label { Text = "<br/>" });
            e.Cell.Controls.Add(new Label { Text = row["Desc"].ToString() });
        }
    }
}

VB.Net

Private Function GetData() As Data.DataTable
    Dim dt As Data.DataTable = New Data.DataTable()
    dt.Columns.Add("Date")
    dt.Columns.Add("Desc")
    dt.Rows.Add("01/July/2019 ", "party time")
    dt.Rows.Add("02/July/2019", "holiday")
    dt.Rows.Add("30/June/2019", "holiday")
    dt.Rows.Add("15/August/2019", "holiday")
    Return dt
End Function

Protected Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As DayRenderEventArgs)
    Dim dt As Data.DataTable = GetData()
    For Each row As Data.DataRow In dt.Rows
        If Convert.ToDateTime(e.Day.Date) = Convert.ToDateTime(row("Date")) Then
            e.Cell.Controls.Add(New Label With {.Text = "<br/>"})
            e.Cell.Controls.Add(New Label With {.Text = row("Desc").ToString()})
        End If
    Next
End Sub

Screenshot