I want tu put 0 before the day and month dates. How can we modify the following codes?

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs formatting)
{
if (formatting.Value != null)
{
try
{
System.Text.StringBuilder dateString = new System.Text.StringBuilder();
DateTime theDate = DateTime.Parse(formatting.Value.ToString());
dateString.Append(theDate.Day);
dateString.Append("/");
dateString.Append(theDate.Month);
dateString.Append("/");
dateString.Append(theDate.Year.ToString());
formatting.Value = dateString.ToString();
formatting.FormattingApplied = true;
}
catch (FormatException)
{
// Set to false in case there are other handlers interested trying to
// format this DataGridViewCellFormattingEventArgs instance.
formatting.FormattingApplied = false;
}
}
}
Vishal JoshiPosted Apr 29, 2024, 7:01 AM
Hello Mehmet Faith
You can use PadLeft function of c#.
Please try the below sample code to add zero before day and month if it's in single digit.
Thanks
Vishal Joshi
Mehmet FatihPosted Apr 29, 2024, 7:38 AM
Thanks Vishal Joshi, It worked for me.
Jignesh KumarPosted Apr 29, 2024, 5:35 AM
Hello Mehmet,
Please use this way and check column is date column or not,
Mehmet FatihPosted Apr 28, 2024, 11:30 AM
Thanks Jignesh Kumar I tried both codes but both give the error shown in the picture.
Jignesh KumarPosted Apr 28, 2024, 10:30 AM
Hello,
You need to add a format for your date, You no need to write all code for that you can use below one,
if not work then please do below,