Asp.net2.0裏Calendar控件的使用

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Calendar : System.Web.UI.Page
{
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    { 
       //連接數據庫,填充數據集DataTable
        SqlConnection conn = new SqlConnection("server=192.168.0.17;uid=sa;pwd=sa;database=calendar");
        conn.Open();
        SqlDataAdapter dad = new SqlDataAdapter("select * from cal", conn);
        dad.Fill(dt);
        //獲取請求頁面的參數id
        string strId = this.Request.QueryString["id"];
        //首次加載時不需綁定GridView;注意,若是空值就不要ToString(),否則得到的是“ ”空字符串,會引發空指針異常
        if (strId != null)
        {
            //把DataTable綁定到DataView裏
            DataView dv = new DataView(dt);
            //根據calendarId篩選DataView裏的值並綁定到GridView中
            dv.RowFilter = "calendarId=" + strId;
            this.GridView1.DataSource = dv;
            this.GridView1.DataBind();
        }
        //設置在Calendar控件上要顯示的月份的日期,防止還原到當前的月份的日期
        if (this.Session["NewDate"]!= null) {
            this.Calendar1.VisibleDate=(DateTime)this.Session["NewDate"];
        }

    }
  
    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
      
        //根據數據集裏的數據設置Calendar控件呈現的外觀,
        foreach(DataRow dr in dt.Rows){
            //判斷當前選中的日期是否在數據集,並各自添加一個hyperlink和一個listeralControl兩個看控件
            if (e.Day.Date.ToString() == dr["cal_time"].ToString()) {
                HyperLink hl = new HyperLink();
                hl.NavigateUrl = this.Request.CurrentExecutionFilePath +"?id=" + dr["calendarId"].ToString();
                hl.Text = dr["cal_short"].ToString();
                LiteralControl lc = new LiteralControl("<br/>");
                e.Cell.Controls.Add(hl);
                e.Cell.Controls.Add(lc);
            }
        }
      
    }
    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
       //篩選當前選中的日期所得到的數據綁定到GridView裏
        DataView dv = new DataView(dt);
        dv.RowFilter = "calendarId=" + this.Calendar1.SelectedDate.Date.ToString();
        this.GridView1.DataSource = dv;
        this.GridView1.DataBind();
    }
    protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
    {  //設置月份的值,保存到Session裏;
        this.Session["NewDate"] = this.Calendar1.VisibleDate;
    }
}
 

發佈了33 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章