Get full name of the day C# datetime

get day name datetime c#
In most C# programs while formatting the dates we need to show complete or full name of the day. Here we are going to see how “dddd” format specifier is used to show full name of the day.

Sample code to show the full name of the day [C#]

using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTime dateToFormat =  new DateTime(2008, 8, 29, 19, 27, 15); 
Console.WriteLine(dateToFormat.ToString("dddd"));
}
}
//Output
//Friday

Date in Month Day, Year Format (MMMM dd, yyyy)

format datetime in Month Day, Year
Some times we need to show date in Month Day, Year Format like January 12, 2012. Here we will see how to format DateTime using string formatter.

Sample code to show date time in Month Day, Year format [C#]


using System;
using System.Globalization;

public class DateTimeFomrateString
{
 public static void Main()
 {
  DateTime datetoFormat = new DateTime(2012, 1, 12);
  Console.WriteLine("Today's Date is " + datetoFormat.ToString("MMMM dd, yyyy") + ".");
 }
}
//Code will display the following output:
//Today's Date is June 10, 2011.

Here MMMM is format specifier that represents month as name like for 05 it will display May. dd is format specifier from day of the month with digits from 01 to 31 and yyyy is the format specifier with four digit number like 2012.

Date in MM-dd-yy format

get date in MM-dd-yy format
Most of the time in C# code we need to format datetime as per requirement. Here we are going to discuss how to format date in MM-dd-yy format.So when we give input date as “10-29-11” then date will get formatted like “10/29/11”.

Sample code to format date in MM-dd-yy format [C#] :


using System;
using System.Globalization;

public class DateFormatSample
{
 public static void Main()
 {
  string dateToFormat = "10-29-11";
  string strFormatPattern = "MM-dd-yy";
  DateTime formattedDate;
  DateTime.TryParseExact(dateToFormat, strFormatPattern, null, 
  DateTimeStyles.None, out formattedDate);
  Console.WriteLine("Date '{0}' Formatted to {1:d}.", dateToFormat, formattedDate);
 }
}
//    output:
//    Date '12-30-11' Formatted to 12/30/2011.

Here MM displays in format 01 to 12, dd represents Day of the month with range from 01 to 31 and yy is year from 00 to 99.

do Postback in Javascript [ASP.NET]

dopostback javascript
In this post we will see how to postback page in ASP.NET from the client side using JavaScript. In some cases we need to postback page from client side i.e. by using JavaScript.
We can use __doPostBack() to postback page from client script using JavaScript.Or we can use Page.GetPostBackEventReference() to do postback from JavaScript. When we use Page.GetPostBackEventReference() it internally get converted to __doPostBack().

Sample that shows how to do postback from JavaScript [ASP.NET, C#]:


< input type="button" id="BaseButton1" onclick="submitPage()" value="OK"/>

Now after clicking on button it will call JavaScript function that will do the postback and then in page load we will capture and perform the operation that is needed.In code behind we use Request[ "__EVENTARGUMENT"] to get the request so that we can perform some operation on that event argument.So below is JavaScript function that uses Page.GetPostBackEventReference() and do the postback from Javascript.


function submitpage() 
{ 
  // trigger postback from JavaScript
   <%= this.Page.GetPostBackEventReference(this,"Delete")%> 
} 


GetPostBackEventReference Here “this” parameter in Page.GetPostBackEventReference(this, “Delete”) is the controls id and referred to as __EVENTTARGET and accessed using Request[“__EVENTTARGET”] in code behind to determine which control caused postback from JavaScript.And “Delete” is __EVENTARGUMENT and accessed using Request[ "__EVENTARGUMENT"] in code behind.

So now in code behind we can check for Request[ "__EVENTARGUMENT"] and perform some operations based on that condition like:


protected void Page_Load(object sender, EventArgs e) 
{ 
string eventArg = Request["__EVENTARGUMENT"]; 
if (!String.IsNullOrEmpty(eventArg)) 
{ 
 if(eventArg == "Delete")
 DeleteRecords();
}
} 

private void DeleteRecords() 
{ 
 //Do something
} 

List to array c#

array to list
In this post we will se how to convert list to array.We need to convert list to array many times in C# programming. Converting list to array can be done by various ways. We are going to see C# examples to convert the list to array.

we will see the way to convert list to an array. we use .ToArray() parameter less instance method that converts list to an array. Below example shows how list get converted in to array using .ToArray() method:

Example to convert list to array [C#]

using System;
using System.Collections.Generic;

class Program
{
 static void Main()
 {
  // List to convert into Array.
  List<string> lstString = new List<string>();
  lstString.Add("Convert");
  lstString.Add("List");
  lstString.Add("TO");
  lstString.Add("Array");
  // use .ToArray() Method to convert list to array
  string[] strArray = lstString.ToArray();
 }
}

Array to List [C#]

convert array to list

Some times we need add elements of an array to list in C# programming. We can use .Add() method of List class to add array elements to the List.Using . we also can use .Add() method to while converting array to List.

We will see example that will show how used .Add method to convert array to List. Here we iterate through array elements and then one by one we add those elements to List.



using System.Collections.Generic; 

protected void Button1_Click(object sender, EventArgs e) 
{     
 string[] arrStr = { "Add", "Array", "Elements", "To", "List", "C#" };      
 List <string> strList = new List<string>();     
 foreach (string stritem in arrStr)    
 {          
  lstString.Add(stritem);    
 }      
}

Base64 to String [C#]

C# convert string to base64

In this post we will see how to convert Base64 string to string. .Net provides .FromBase64String() method in System.Convert class to convert Base64 string to string. While converting Base64 string to string it first converts base64 string to byte array and then byte array converted to string.

Sample code to convert Base64 string to string [C#]


//Convert Base64 string to string
public static string Base64ToString(string strBase64)       
{  
byte[] byteArray = Convert.FromBase64String(strBase64);            
return(System.Text.Encoding.UTF8.GetString(byteArray));        
}

String to Base64 [C#]

string to base64

In this post we will look how to convert string to Base64 using C#. .Net provides .ToBase64String() method in System.Convert class that we can use to convert string to base64. It basically converts value of an array of 8-bit unsigned integers to its equivalent String representation consisting of base 64 digits.

Converting string to Base64 is bit tricky. We need to follow some steps mentioned as below

  • 1. We need to convert string to byte array.
  • 2. then we need to use Convert.ToBase64String() to convert byte array to base64 string.

Sample code to convert string to Base64 string [C#]


str ="How to convert string to nase64 in C#"; 
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(str);
// Now convert the byte array to a Base64 string
strBase64 = Convert.ToBase64String(byteArray);

Write to text file [C#]

c# write to text file
File class in System.IO Namespace also contains methods to write contents to text tile. WriteAllText() method to write string to text file. WriteAllLines() method is used to write line by line into text file. And WriteLine() method writes or appends text to the text file with existing contents.
How to write to a text file?
TO write to a text file in file system .net has provided below methods in File class of System.IO namespace:
1.WriteAllText.
2.WriteAllLines.
3.WriteLine.

1.WriteAllText.

WriteAllText method in File class writes one string to the text file

Sample code that shows how to write into to text file[C#]

class WriteFileAllText
{
 static void Main()
 {
  // Example to Write one string into text file.
   string textToWrite = "To write one string into a text file use 
   WriteAllText method, " ;
   System.IO.File.WriteAllText(@"C:\\TextFileFolder\NewTextFile.txt", textToWrite);
 }
}  

2.WriteAllLines.

WriteAllLines method in File class writes contents to a text file line by line.

Sample code that show how to write into a text file line by line[C#]

class WriteFileLines
{
 static void Main()
 {  
  // Example to Write the contents line by line into text file.
  string[] lines = {"Line One", "Line Two", "Line Three"};
  System.IO.File.WriteAllLines(@"C:\TextFileFolder\WriteLines.txt", lines);}
 }  

3.WriteLine.

WriteLine method in File class writes or appends line to a text file that already have some data.

Sample code that show how to append text line into a text file.[C#]

It uses StreamWriter class of System.IO namespace to append line in existing text file
class WriteFileLine
{
static void Main()
{  
 // Append text line to existing file
 System.IO.StreamWriter file = new System.IO.StreamWriter ("C:\TextFileFolder\WriteLines.txt", true)
 {
  file.WriteLine("Line Four");
 }
}

C# Uppercase First Character or Letter

uppercase first letter in string

Some times we need to uppercase the first letter. There are various ways to make first word in uppercase. we will look at some of the ways to uppercase the first letter in strings in the C#. We can take out first character of string from it’s zero index and the using char.ToUpper(str[0]) we can capitalize first character and then concatenate it with remaining string and make string again. Other way to uppercase first character or letter is use .ToCharArray() method and then from array of characters take zero index character make it uppercase and then formulate new string again. Other alternative is to use Substring() method and take characters from position 0 to 1 and capitalize first character and then using substring from 1 position concatenate those strings.

Here we will see how first way will work to uppercase first character or letter of the string using c#.

C# code to uppercases first character

using System;
class Program 
{ 
 static void Main()
 {
  Console.WriteLine(UppercaseFirstLetter("first")); 
 }
 static string UppercaseFirstLetter(string str)
 {
  var  firstChar = str[0];
  var  UpperCaseFirstCharacter =  char.ToUper(firstChar);
  var convertedFirstCharToUpper = UpperCaseFirstCharacter +  str.Substring(1);
  return convertedFirstCharToUpper ;
 }
}


//Result:
//First.

In above code sample for upper case first letter we first take first char as str[0] and using char.ToUpper(str[0]) we Capitalized first character and then concatenated remaining string with first capitalized char and the returns the new string with first letter capitalized.


Second way to Uppercase the First latter of the String:


C# code to uppercases first letter


using System;

class Program
{
 static void Main()
 {
  Console.WriteLine(UppercaseFirstCharacter("first"));    
 }

 static string UppercaseFirstCharacter(string str)
 {
  char[] strArray = str.ToCharArray();
  strArray[0] = char.ToUpper(strArray [0]);
  return new string(strArray);
 }
}


//Result
//First.

In above C# code we have converted input string in to array of characters using .ToCharArray() and then took zero index character and uppercase it and the formed new string with new string constructor to construct string.

Third way to uppercase first character of string using c#

C# code to uppercases first character [C#]


public static string Capitalize(string input)   
{
 str = "first";
 return str.Substring(0, 1).ToUpper() + str.Substring(1);
}


//Result:
//First

In above C# example to uppercase first character of string we used Substring() method. using Substring(0,1) we get first character of string and then we capitalized that character like Substring(0,1).ToUpper() and then we concatenated remaining string from first position onwards to it.