首页 > 解决方案 > 如何在带有复选框的列表框中显示 1 个月的数据库

问题描述

所以我能够将每日数据显示到列表框中,但是如果我使用一个复选框,它将显示 1 个月的数据,我该怎么办?

private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {

            //label1.Text = monthCalendar1.SelectionStart.ToString();
            lstres.Items.Clear();
            con.Open();
            string date = monthCalendar1.SelectionStart.ToString();

            
            SqlCommand cmd = new SqlCommand("Select * from reservation where Date = '" + date + "'", con);
            //sqlcommand cmd= to choose all the data from database where date is from Date

            DataTable dt = new DataTable();
            // datatable = to represents data table
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            //sqldataadapter = to link database connection
            da.Fill(dt);

            //DateTime dateAndTime = DateTime.Now;
            // Will give you smth like 25/05/2011
            //lstres.Text = dateAndTime.ToString("dd/MM/yyyy");

            foreach (DataRow dr in dt.Rows)
            //foreach to transfer items in an array and display it
            {

                string dateonly = Convert.ToDateTime(dr["Date"]).ToString("dd/MM/yyyy");
                string show = dateonly + " " + dr["TimeStart"].ToString() +
                            " " + "-" + " " + dr["TimeEnd"].ToString() + "  " + dr["RoomType"].ToString();
                lstres.Items.Add(show);

            }

            con.Close();
        }

这段代码是每天的,但如何为每月做任何想法?

标签: c#

解决方案


要得到整个月,你需要计算当月的第一天,以及下个月的第一天,你可以这样做:

DateTime selectedDate = monthCalendar1.SelectionStart;
DateTime fromDate = date.AddDays(-date.Day + 1);
DateTime toDate = fromDate.AddMonths(1);

然后,您可以将它们种植在 sql 命令中,如下所示:

SqlCommand cmd = new SqlCommand($"Select * from reservation where Date >= '{fromDate:yyyy-MM-dd}' AND Date < '{toDate:yyyy-MM-dd}'", con);

推荐阅读