Solved

Add date to textbox on Enter-key c#

Posted on 2008-11-02
2
1,417 Views
Last Modified: 2013-12-17
I was wondering if anyone could help me to get the code to do the following:
1. I have a textbox on the form that contains text
2. I want the program to automatically insert shortDateString to the top of the textbox when a user hits the "Enter"-key on the keyboard.
3. The date is only going to be inserted when the position of cursor is at beginning of textbox text when the enter key is pressed.
4. The user should then be able to start typing text right under the date.

I do not know a better way to explain this. Will try to explain better if it is not understanable.
0
Comment
Question by:orjanmj
2 Comments
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 250 total points
ID: 22861867
For C# WinForms:
        private void textBox1_KeyDown(object sender, KeyEventArgs e)

        {

            if (e.KeyCode == Keys.Enter)

            {

                e.Handled = true;

                if (textBox1.SelectionStart == 0 && textBox1.SelectionLength == 0)

                {

                    textBox1.SelectedText = DateTime.Now.ToString("d");

                }

            }

        }

Open in new window

0
 

Author Comment

by:orjanmj
ID: 22862092
Thanks a bunch. I actually had already tried this before, but I had done a mixup with the selection start... This was exactly what I wanted!
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now