Clear the DateTimePicker control in c# winfoms - c#

I want to clear the DateTimePicker control value when i click on clear button but i can't do that with simple double qoutes, So please help me
tbAddress.Text = "";
dtpBirth.Value = "";
cBoxGender.SelectedIndex = -1;

This should do the trick
dtpBirth.CustomFormat = " ";
dtpBirth.Format = DateTimePickerFormat.Custom;
it will clear the input box.

try is
dateTimePickerDOB.Value = DateTimePicker.MinimumDateTime
in this your date and time going to be minimum date and time in your DateTimePicker and dateTimePickerDOB mean your Design(name)
or
try this for clear the date
dateTimePicker_dob.Text = string.Empty;
in here dateTimePickerDOB mean your Design(name)

The DateTimePicker.Value is from type DateTime and not a String.
dtpBirth.Value = DateTime.Now;

You can do this:
private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
{
if (dateTimePicker1.Value == DateTimePicker.MinimumDateTime)
{
dateTimePicker1.Value = DateTime.Now; // This is required in order to show current month/year when user reopens the date popup.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";
}
else
{
dateTimePicker1.Format = DateTimePickerFormat.Short;
}
}
private void Clear_Click(object sender, EventArgs e)
{
dateTimePicker1.Value = DateTimePicker.MinimumDateTime;
}

Related

retain previous value of text box till the form is closed

I am very new to c# , and learning to make data entry application,
in my entry form when the user clicks save all the data text boxes are refreshed and saved to database and the text box appears empty to enter gain. This is a continuous process.
Now i want my textbox1 to retain the same value where the user first entered till the form is closed.
Please help me how to achieve this?
i tried this code but the textbox is still empty:
private string value;
private void materiaNumberTextBox_TextChanged(object sender, EventArgs e)
{
var oldValue = value;
value = ((TextBox)sender).Text; // text1.Text
}
here's the code that does while saving:
private void btnsave_Click(object sender, EventArgs e)
{
try
{
String msg = "Confirm Save?";
String caption = "Save Record";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
MessageBoxIcon ico = MessageBoxIcon.Question;
DialogResult result;
result = MessageBox.Show(this, msg, caption, buttons, ico);
if (result == DialogResult.Yes)
{
generateautoID();
this.iP_SpoolsBindingSource.EndEdit();
MessageBox.Show("The Record saved Successfully:" + outputSpoolNoTextBox.Text, "Save_Update",
MessageBoxButtons.OK, MessageBoxIcon.Information);
this.iP_SpoolsTableAdapter.Update(this.pINQCDataSet.IP_Spools);
this.iP_SpoolsTableAdapter.Fill(this.pINQCDataSet.IP_Spools);
//MessageBox.Show("The Record saved Successfully:", "Save_Update",
//MessageBoxButtons.OK, MessageBoxIcon.Information);
this.iP_SpoolsBindingSource.AddNew();
string strStartenddateformat = "dd-MM-yyyy";
materialTypeComboBox.ValueMember = "Tungsten";
unitComboBox.ValueMember = "Mic";
statusComboBox.ValueMember = "Accepted";
cFComboBox.ValueMember = "";
bowOutOfComboBox.ValueMember = "";
ductilityOutofComboBox.ValueMember = "";
finishUOMComboBox.ValueMember = "Mic";
finishTypeComboBox.ValueMember = "Clean";
rejectReason1ComboBox.ValueMember = "";
rejectReason2ComboBox.ValueMember = "";
rejectReason3ComboBox.ValueMember = "";
lotNoTextBox.Text = "0";
dOEDateTimePicker.Format = DateTimePickerFormat.Custom;
dOEDateTimePicker.CustomFormat = strStartenddateformat;
dOEDateTimePicker.Value = DateTime.Now;
dOPDateTimePicker.Format = DateTimePickerFormat.Custom;
dOPDateTimePicker.CustomFormat = strStartenddateformat;
dOPDateTimePicker.Value = DateTime.Now;
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Saving Failed:" + ex.Message.ToString(), "Save",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
here's the image of my form:
You can try the following code to save the first input text in the textbox.
Please use the event textbox_Leave event.
private void button1_Click(object sender, EventArgs e)
{
//Update the database
MessageBox.Show("Update success");
textBox1.Text = textbox; // return to the first input in the textbox
}
int i = 0;
string textbox = "";
private void textBox1_Leave(object sender, EventArgs e)
{
if (i == 0)
{
textbox = textBox1.Text;
i++;
}
}
Result:
Use a data reader to get the values from database and then populate values in textbox using those values.

ASP.NET increase & decrease date by clicking image

I want to increase & decrease date on Image click like this. '<' for decrease and '>' for increment and show them in textbox. I tried like following code but not working
kindly help me to do so
protected void ImageButtonNextDate_Click(object sender, ImageClickEventArgs e)
{
DateTime date = DateTime.Now;
DateTime nextday = date.AddDays(1);
txtDate.Text = nextday.ToShortDateString();
}
protected void ImageButtonPrevDate_Click(object sender, ImageClickEventArgs e)
{
DateTime date = DateTime.Now;
DateTime nextday = date.AddDays(-1);
txtDate.Text = nextday.ToShortDateString();
}
Every time you handle click event on your images, you create a new date variable with value equal to current date. You need to store data between clicks somehow, so that it's retained for the next event. There are multiple ways to do so, for example, session variables:
protected void ImageButtonPrevDate_Click(object sender, ImageClickEventArgs e)
{
DateTime date = Session["MyDateVariable"] as DateTime ?? DateTime.Now;
DateTime nextday = date.AddDays(-1);
Session["MyDateVariable"] = nextday;
txtDate.Text = nextday.ToShortDateString();
}
I think you need to get the current value from the txtDate, then perform the logic.
protected void ImageButtonNextDate_Click(object sender, ImageClickEventArgs e)
{
txtDate.Text = (Convert.ToDateTime(txtDate.Text).AddDays(1)).ToShortDateString();
}
protected void ImageButtonPrevDate_Click(object sender, ImageClickEventArgs e)
{
txtDate.Text = (Convert.ToDateTime(txtDate.Text).AddDays(-1)).ToShortDateString();
}
UPDATE
You only need to load the value of DateTime.Now to txtDate on first page load, on every post back, do not set it.
if(!IsPostBack()){
txtDate.Text = DateTime.Now.ToShortDateString();
}

Disable all dates after some months from a certain date Android DatePicker

I have two DatePickers in my app. First, shows the FromDate which is CurrentDate+1, the second shows the ToDate ie. FromDate+1.
I have got the above scenario working. But now I want to disable all the dates after 6 months from the FromDate.
I tried doing the following,but the calender then shows 01/01/1970 as the current date.
BookingActivity.cs
void IbtnToDate_Click(object sender, EventArgs e)
{
toDateClicked = true;
fromDateClicked = false;
dateFragment = new DatePickerFragment(this, DateTime.Parse (editFromDate.Text.ToString ()).AddDays (1), this, DateTime.Parse (editFromDate.Text.ToString ()));
dateFragment.Show(FragmentManager, null);
}
void IbtnFromDate_Click(object sender, EventArgs e)
{
fromDateClicked = true;
toDateClicked = false;
dateFragment = new DatePickerFragment(this, date.AddDays (1), this, date.AddDays (1));
dateFragment.Show(FragmentManager, null);
}
public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
var date1 = new DateTime(year, monthOfYear + 1, dayOfMonth);
if (fromDateClicked)
UpdateFromDate (date1);
else if (toDateClicked) {
UpdateToDate (date1);
}
}
DatePickerFragment.cs
public class DatePickerFragment : DialogFragment
{
private readonly Context _context;
private DateTime _date, _minDate, _maxDate;
private readonly Android.App.DatePickerDialog.IOnDateSetListener _listener;
public DatePickerFragment(Context context, DateTime date, Android.App.DatePickerDialog.IOnDateSetListener listener, DateTime minDate)
{
_context = context;
_date = date;
_listener = listener;
_minDate = minDate;
}
public override Dialog OnCreateDialog(Bundle savedState)
{
var dialog = new Android.App.DatePickerDialog(_context, _listener, _date.Year, _date.Month - 1, _date.Day);
dialog.DatePicker.MinDate =_minDate.AddDays (1).Millisecond;
dialog.DatePicker.MaxDate = _date.AddMonths(6).Millisecond;
return dialog;
}
}
How can I achieve it? Any help would be appreciated.
You can use setMaxDate and can do something like:
1- Get the date from _mindate string:
String dateString = "03/26/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2- Get date of 6 months from min_date:
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(convertedDate);
cal.add(Calendar.MONTH, 1);
Date 6MonthsFromCurrentDate = cal.getTime();
3- Restricting the datePicker to that date:
datePickerDialog.getDatePicker().setMaxDate(6MonthsFromCurrentDate.getTime());
Use these lines of code.
Calendar ci = Calendar.getInstance();
String CiDateTime = ci.get(Calendar.YEAR) + "-" +
(ci.get(Calendar.MONTH) + 7) + "-" + //for 6 month future
ci.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
Date d;
try {
d = f.parse(CiDateTime);
long milliseconds = d.getTime();
_date.setMaxDate(milliseconds);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to Add Custom Time Format?

I am making a NetcafeProgram in C# and I want to get the current DateTime. I want my output like this (hr.mins)"0.25". I have the current DateTime but I want to show it like this (hr.mins)"0.25" in the labelTime_1 but it is not working. This is the command which I used
starttime_1 = DateTime.Now.ToString("h:mm:ss tt");
and I changed it to
starttime_1 = DateTime.Now.ToString("h.mm");
and then I wanted to get the duration like this
TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
but it gives me errors.
Here is a Screenshot of My Formv:
I want the time to get posted On that Time Elapsed Label but it doesn't work. Here is the coding of BtnStop1
private void btnStop_1_Click(object sender, EventArgs e)
{
//string duration = Convert.ToInt32(((starttime_1) - (endtime_1)));
gbx_1.BackColor = Color.LimeGreen;
btnStop_1.Enabled = false;
//endtime_1 = DateTime.Now.ToString("h:mm:ss tt");
//TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
endtime_1 = DateTime.Now.ToString("h.mm tt");
TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
lblTime_1.Text = Convert.ToString(duration);
string var = "Cabin One is Free";
btnStart_1.Enabled = true;
HP_1.Enabled = true;
CR_1.Enabled = true;
reader = new SpeechSynthesizer();
reader.SpeakAsync(var);
}
Coding of BtnStart
private void btnStart_1_Click(object sender, EventArgs e)
{
gbx_1.BackColor = Color.Red;
btnStart_1.Enabled = false;
//starttime_1 = DateTime.Now.ToString("h:mm:ss tt");
starttime_1 = DateTime.Now.ToString("h.mm tt");
lblTime_1.Text = "CountingTime";
string var = "Cabin One is Occupied";
reader = new SpeechSynthesizer();
reader.SpeakAsync(var);
HP_1.Enabled = false;
CR_1.Enabled = false;
}
Here Are My Variables
public string starttime_1;
public string starttime_2;
public string starttime_3;
public string starttime_4;
public string starttime_5;
public string starttime_6;
public string endtime_1;
public string endtime_2;
public string endtime_3;
public string endtime_4;
public string endtime_5;
public string endtime_6;
I would strongly suggest changing your variable types to DateTime?. It is better to store data in its native type and then do the convert to string on display. This way, when you want the duration, you are not parsing back to DateTime. You can handle any rounding you want on the base data.
So, your conversion to string should be at the highest level of you stack. It will keep your code cleaner and make it easier to refactor the logic away from the UI later if appropriate.
Not really sure I understand all this parsing but if you're just trying to record start and stop times and output a timespan I would do as Jon Skeet recommend with the stopwatch. Something along these lines looks like what you're going for but a bit cleaner.
// Build stopwatch and lists
Stopwatch sw = new Stopwatch();
List<string> startTimes = new List<string>();
List<string> endTimes = new List<string>();
private void startBtn_Click(object sender, EventArgs e)
{
// Start stopwatch and record start time
sw.Start();
startTimes.Add(DateTime.Now.ToString("h.mm"));
}
private void stopBtn_Click(object sender, EventArgs e)
{
// Stop stopwatch
sw.Stop();
// Record stop time and reset stopwatch
endTimes.Add(DateTime.Now.ToString("h.mm"));
sw.Reset();
// Output timespan
outputLbl.Text = sw.Elapsed.ToString();
}

DateTime format not showing correctly

Firstly, apologies for asking a question that has been asked before, but even with the examples I am not getting the desired results.
All I am trying to do is display the current time, which it does, but I noticed that the datetime format was 9:5:6 instead of 09:05:06. I read the examples about formatting DateTime but it doesn't work for some reason. Can anyone shed any light on where I am going wrong?
Thanks for your help as always.
public MainWindow()
{
InitializeComponent();
DispatcherTimer dispatchTimer = new DispatcherTimer();
dispatchTimer.Tick += new EventHandler(dispatchTimer_Tick);
dispatchTimer.Interval = new TimeSpan(0, 0, 1);
dispatchTimer.Start();
}
private void dispatchTimer_Tick(object sender, EventArgs e)
{
var hour = DateTime.Now.Hour.ToString();
var min = DateTime.Now.Minute.ToString();
var sec = DateTime.Now.Second.ToString();
var today = hour + ":" + min + ":" + sec;
label1.Content = today;
textBlock1.Text = today;
button1.Content = today;
}
Just use a custom format string:
var today = DateTime.Now.ToString("HH:mm:ss");
Or the standard one:
var today = DateTime.Now.ToString("T");
string now = DateTime.Now.ToString("HH:mm:ss");
Check TimeZoneInfo Class for more detailed globalization.
I think there are many ways to tackle this issue.
Personally, and to keep things simple, I would do it this way:
private void dispatchTimer_Tick(object sender, EventArgs e)
{
string wTime = DateTime.Now.ToString("HH:mm:ss");
// OR THIS WAY
string wTime2 = DateTime.Now.ToString("T");
label1.Content = wTime;
textBlock1.Text = wTime;
button1.Content = wTime;
}
But if you want for some reasons to keep your initial logic then this would do it too.
private void dispatchTimer_Tick(object sender, EventArgs e)
{
string hour = DateTime.Now.Hour.ToString("00");
string min = DateTime.Now.Minute.ToString("00");
string sec = DateTime.Now.Second.ToString("00");
var today = hour + ":" + min + ":" + sec;
label1.Content = today;
textBlock1.Text = today;
button1.Content = today;
}
You may also wish to look at this http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

Categories