您的位置:首页 > 编程语言 > C#

C# 创建年、月、周、日TreeView

2014-04-29 10:38 363 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace VideoPatrolControl
{
public partial class zz : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.CreatYear(2014);
}

/// <summary>
/// 创建整年
/// </summary>
/// <param name="mp_year">年份</param>
private void CreatYear(int mp_year)
{
int week = 0;
int year = mp_year;
TreeView tree = new TreeView();
TreeNode NodeYear = new TreeNode(string.Format("{0}年", mp_year));
tree.Nodes.Add(NodeYear);
for (int Month = 1; Month < 13; Month++)
{
TreeNode NodeMonth = new TreeNode(string.Format("{0}月", Month.ToString()));
NodeYear.ChildNodes.Add(NodeMonth);
NodeMonth.Expanded = false;

int days = GetMonthNum(year, Month);

for (int day = 1; day <= days; day++)
{
string dateStr = string.Format("{0}/{1}/{2}", mp_year, Month, day);
DateTime dt = DateTime.Parse(dateStr);
DayOfWeek dow = dt.DayOfWeek;

if (dow == DayOfWeek.Monday)
{
week++;
TreeNode NodeWeek = new TreeNode(string.Format("第{0}周", week.ToString()));
NodeMonth.ChildNodes.Add(NodeWeek);
NodeWeek.Expanded = false;

for (int weekDay = 0; weekDay < 7; weekDay++)
{
dow = dt.DayOfWeek;
string strWeek = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(dow);
TreeNode NodeDay = new TreeNode(string.Format("{0}({1}.{2})", strWeek, dt.Month, dt.Day));
NodeWeek.ChildNodes.Add(NodeDay);
dt = dt.AddDays(1);
}
}
}
}
this.panel1.Controls.Add(tree);
}

/// <summary>
/// 返回每月天数
/// </summary>
/// <param name="mp_Year">年份</param>
/// <param name="mp_Month">月份</param>
/// <returns>天数</returns>
private int GetMonthNum(int mp_Year, int mp_Month)
{
int days = 0;
int Year = mp_Year;
int Month = mp_Month;

if (Month == 1 || Month == 3 || Month == 5 || Month == 7 || Month == 8 || Month == 10 || Month == 12)
{
days = 31;
}
if (Month == 4 || Month == 6 || Month == 9 || Month == 11)
{
days = 30;
}
if ((Year % 400) != 0)//不是闰年
{
if (Month == 2)
{
days = 28;
}
}
else
{
if (Month == 2)
{
days = 29;
}
}
return days;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: