C# DateTimePicker => ListBox - Add Date,Update Date

June 19, 2017 Oclemy C# DateTimePicker, C# ListBox 1 minute, 48 seconds

Date and Time are something we frequently work with from time to time.The best and easiest way to work with dates in windows forms is with the help of the DateTimePicker component.DatetimePicker allows us to easily select and navigate dates we want and its easy to get the selected date. We can also of course update an existing date in the datetimepicker,say from a textbox. This is what we do in short :

  • We have a ListBox and we want to fill it with dates.The dates we get from a datetimepicker.
  • The user selects a given date from the datetimepicker and we add that date in the ListBox.
  • Moreover if the user selects a vale from the ListBox,we set the selected date to our datetimepicker component.
  • So at the end of the day,we add dates from datetimepicker to ListBox,and update ListBox date values via a datetimepicker.

How To Download and Run

  • Download the project above.
  • You'll get a zipped file,extract it.
  • Open the Visual Studio.
  • From the Menu bar click on File >Open > Project/Solution
  • Now Choose a Destination Folder, from where you have the extracted project.
  • Now Click on “OK“.
  • Done, Now edit it.

Form 1 Class

  • This is our main class of course.
  • Add DateTimePicker to your Form ,two buttons and a ListBox.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ListBox__Add_Date
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void addBtn_Click(object sender, EventArgs e)
    {
      listBox1.Items.Add(dateTimePicker1.Value.ToLongDateString());

    }

    //UPDATE ITEM
    private void updateBtn_Click(object sender, EventArgs e)
    {
      int index = listBox1.SelectedIndex;
      if(index != -1)
      {
        listBox1.Items.RemoveAt(index);
        listBox1.Items.Insert(index, dateTimePicker1.Value.ToLongDateString());
      }
    }

   // USER SELECTS AN ITEM TO EDIT.SET SELECTED ITEM TO DATETIMEPICKER
    private void listBox1_MouseClick(object sender, MouseEventArgs e)
    {

       int index = listBox1.SelectedIndex;
       if (index != -1)
       {
         dateTimePicker1.Value = DateTime.Parse(listBox1.SelectedItem.ToString());

       }
    }
  }
}

YouTube

Facebook

Oclemy,Cheers.

Comments