How To Create a Date in C#

Microsoft's C#, pronounced C-Sharp, programming language provides a middle ground for developers between the complexity and power of C++ and the simplicity of Visual Basic. Dealing with dates in C# is easy using the "MonthCalendar" user interface control and the "DateTime" class from the .NET framework.

Things You'll Need

  • Visual C# 2010
Show More

Instructions

  1. Retrieve Date from User

    • 1

      Create a project by clicking "File" and "New Project." Select "Windows Forms Project" from the list of project templates and name it "dateApp."

    • 2

      Click "Toolbox" on the left side of the screen to be shown the Graphical User Interface (GUI) controls.

    • 3

      Drag the "MonthCalendar" control into your application. This will display a small monthly calendar program inside your application window.

    • 4

      Drag the "TextBox" control into your application window.

    • 5

      Double-click the "MonthCalendar" control to create some code that will be run whenever the user changes the selected date. Paste the following code to have the user's selected date appear in the textbox.

      textBox1.Text = monthCalendar1.SelectionRange.Start.ToShortDateString();

      If the user selects the date "March 4, 2010," this will display "3/4/2010" in the textbox.

      You can get fancier with this. For example, if the user selects a range of dates, you can use the following code to represent it in the textbox:

      textBox1.Text = "You selected " +
      monthCalendar1.SelectionRange.Start.ToShortDateString() + " to "
      monthCalendar1.SelectionRange.End.ToShortDateString() +".";

      Now, if the user drags his mouse over the calendar selecting the range from March 4 to March 12, the result in the textbox will be:

      "You selected 3/4/2010 to 3/12/2010."

    Set Calendar's Selected Date Programmatically

    • 6

      Repeat steps 1 through 4 from the first section to get your application set up with a MonthCalendar control and a textbox.

    • 7

      Drag a button from the toolbox into your application. Right-click the button and select "properties." Find the "text" property and change it to "Load."

      This button will load a date typed into the textbox and select it on the calendar.

    • 8

      Double-click the button and paste the following code into the source code editor. This code will take a date given by a user in the textbox and select that date on the calendar.

      monthCalendar1.SelectionStart =
      DateTime.Parse(textBox1.Text,
      System.Globalization.CultureInfo.InvariantCulture);

      monthCalendar1.SelectionEnd =
      DateTime.Parse(textBox1.Text,
      System.Globalization.CultureInfo.InvariantCulture);

Related Searches:

References

Comments

Related Ads

Featured