asp.net - How to create text file and write text programmatically

Create a text file and write text programmatically
The following asp.net c# example code demonstrates how we can create a text file and write text on it programmatically in the .net framework.

We can get the application's physical path using HttpRequest.PhysicalApplicationPath property as Request.PhysicalApplicationPath. We also can get the file path by adding two strings, which are the physical application path and file name with extension. In this example, we created a text file name Text.txt and programmatically wrote two lines of text in this file at run time.

StreamWriter Class allows us to implement a TextWriter for writing characters to a stream in a particular encoding. In this example code, we initialize a StreamWriter object.

The File class’s CreateText(path) method creates or opens a file for writing UTF-8 encoded text. this method requires passing a parameter name 'path'. The path parameter value specifies the file to be opened for writing. This method’s return value type is System.IO.StreamWriter.

StreamWriter WriteLine(String) method allows us to write a string followed by a line terminator to the text string or stream.

StreamWriter Flush() method clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

StreamWriter Close() method closes the current StreamWriter object and the underlying stream.

In an app.net page, we need to include the System.IO namespace before working with files and directories.
StreamWriter.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<!DOCTYPE html>

<script runat="server">

    protected void Button1_Click(object sender, System.EventArgs e)
    {
        string appPath = Request.PhysicalApplicationPath;
        string filePath = appPath + "Text.txt";
        StreamWriter w;
        w = File.CreateText(filePath);
        w.WriteLine("This is a test line.");
        w.WriteLine("This is another line.");
        w.Flush();
        w.Close();
        Label1.Text = "File created and write successfully!<br />";
        Label1.Text += filePath;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to create text file and write text programmatically in asp.net</title>
</head> 
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Red">asp.net StreamWriter example:<br />Create File and Write In It</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Large"
             ForeColor="SeaGreen"
             Font-Bold="true"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             OnClick="Button1_Click"
             Font-Bold="true"
             Text="Create File and Write Text"
             ForeColor="SeaGreen"
             />   
    </div>
    </form>
</body>
</html>

c# - How to get index of an element from an array

Array IndexOf() Method
The following asp.net c# example code demonstrate us how can we get index of an array element programmatically at run timein an asp.net application. Array Class Array.IndexOf(Array, Object) overloaded method search for the specified object and returnthe index of its first occurrence in a one-dimensional array.

Array.IndexOf(Array, Object) method has two required parameters named 'array' and 'value'. The 'array' parameter represent theone-dimensional array to search and 'value' parameter represent the object to locate in array. In this example code, we initializesa string array with elements and pass a string object as 'value' parameter value to IndexOf() method to get its index.

Array.IndexOf() method return an integer value which represent the index of the first occurrence of specified object in array, if found;otherwise it return the lower bound of the array minus 1. The method throw RankException exception, if the array is multidimensional.Array contain zero-based index.
ArrayIndexOf.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    private string[] controls = { "SqlDataSource", "AccessDataSource", "ObjectDataSource", "XmlDataSource", "LinqDataSource", "EntityDataSource", "SiteMapDataSource" };
    protected void Page_Load(object sender, System.EventArgs e) {
        if(!this.IsPostBack)
        {
            Label1.Text = "String array created successfully!<br />Array elements:<br /><br />";
            foreach (string element in controls)
            {
                Label1.Text += element + "<br />";
            }
        }

    }
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        int indexOf = Array.IndexOf(controls, "LinqDataSource");
        Label2.Text ="We Find [LinqDataSource] At the index position: " + indexOf.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to get (search, find) array index position by array element value in asp.net(Array.IndexOf)</title>
</head> 
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Red">asp.net Array.IndexOf() example:<br />Search Array Index Number By Element Value</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Large"
             ForeColor="SeaGreen"
             Font-Bold="true"
             Font-Italic="true"
             >
        </asp:Label>
        <br />
        <asp:Label 
             ID="Label2" 
             runat="server" 
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Bold="true"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             OnClick="Button1_Click"
             Font-Bold="true"
             Text="Search Array [LinqDataSource] Index Position"
             ForeColor="SeaGreen"
             />   
    </div>
    </form>
</body>
</html>

asp.net - DataBind a RadioButtonList with an array

DataBind a RadioButtonList with array
The following ASP.NET C# example code demonstrates to us how can we data bind a RadioButtonList with an Array data source. RadioButtonList is an ASP.NET list web server control. RadioButtonList control renders a radio group on the web page.

RadioButtonList’s each ListItem object renders a single RadioButton with the same group name. We can populate RadioButtonList items from various data sources such as SqlDataSource, ObjectDataSource, Array, ArrayList, Generic List, Dictionary, etc.

The Array is a popular data source object to data bind with a list web server control such as RadioButtonList, BulletedList, ListBox, etc. Each element from the Array object creates a new ListItem object when we data bind a list server control with the Array data source.

To populate a RadioButtonList with an Array data source is very simple in the ASP.NET C# environment. First, we need to create an Array object. Next, we populate the Array object with items/elements. Then we can define the RadioButtonList control's data source to an Array object by using the RadioButtonList control's DataSource property.

Finally, we can call the RadioButtonList control's DataBind() method to populate RadioButtonList items from Array elements.
StringArrayRadioButtonList.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    protected void Button1_Click(object sender, System.EventArgs e)
    {
        string[] controlArray = { "TextBox", "Label", "ImageMap", "MultiView", "View" };
        Label1.Text = "String array created and bind with RadioButtonList successfully!";
        RadioButtonList1.DataSource = controlArray;
        RadioButtonList1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to populate (DataBind) RadioButtonList using string array DataSource in asp.net</title>
</head> 
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">asp.net array example:<br />String Array and RadioButtonList</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Large"
             ForeColor="SeaGreen"
             Font-Bold="true"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:RadioButtonList 
             ID="RadioButtonList1" 
             runat="server" 
             BackColor="Crimson" 
             ForeColor="Snow"
             RepeatColumns="2"
             >
        </asp:RadioButtonList>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             OnClick="Button1_Click"
             Font-Bold="true"
             Text="Populate RadioButtonList With String Array"
             ForeColor="Crimson"
             />   
    </div>
    </form>
</body>
</html>

asp.net - How to DataBind a CheckBoxList with an array

DataBind a CheckBoxList with array
The following ASP.NET C# example code demonstrates to us how can we data bind a CheckBoxList web server control programmatically at run time with an Array data source object. CheckBoxList is an ASP.NET list web server control. CheckBoxList allows web users to select/check one or more items at a time.

CheckBoxList contains ListItem objects. Each ListItem object represents an item. We can populate a CheckBoxList from Array elements. To do this, first, we need to initialize an array object. Then we populate the Array with items (elements). Next, we need to specify the newly created Array as CheckBoxList control's DataSource. Finally, we can data bind CheckBoxList control with Array by calling the CheckBoxList DataBind() method.

The populated CheckBoxlist creates the same number of items as the number of elements that exist in the Array. Each Array element creates an item in CheckBoxList. We populated CheckBoxList from a one-dimensional String Array, so the CheckBoxList item 'Text' and 'Value' properties carry the same value.
StringArrayCheckBoxList.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    protected void Button1_Click(object sender, System.EventArgs e)
    {
        string[] controlArray = { "Localize", "Label", "Panel", "ListBox", "RadioButton" };
        Label1.Text = "String array created and bind with CheckBoxList successfully!";
        CheckBoxList1.DataSource = controlArray;
        CheckBoxList1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to populate (DataBind) CheckBoxList using string array DataSource in asp.net</title>
</head> 
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">asp.net array example: String Array and CheckBoxList</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Large"
             ForeColor="SaddleBrown"
             Font-Bold="true"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:CheckBoxList 
             ID="CheckBoxList1" 
             runat="server" 
             BackColor="SteelBlue" 
             ForeColor="FloralWhite"
             >
        </asp:CheckBoxList>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             OnClick="Button1_Click"
             Font-Bold="true"
             Text="Populate CheckBoxList With String Array"
             ForeColor="SaddleBrown"
             />   
    </div>
    </form>
</body>
</html>

asp.net - How to data bind a DropDownList with an array

DataBind DropDownList with array
The following asp.net c# example code demonstrates to us how can we populate a DropDownList server control with items from an Array data source.

DropDownList is a list web server control. DropDownList can contain one or more ListItem objects. A ListItem object includes Text and an optional Value. The Array is the most preferable data source for .NET developers to populate a list server control.

In this example code, we initialized a String data type Array object with items/elements. Then we set the DropDownList's DataSource property value to the newly initialized Array object. Next, we call the DropDownList DataBind() method to data bind DropDownList with the Array data source.

Each element of the Array creates an item in DropDownList. This is a one-dimensional Array, so DropDownList's each ListItem object's 'Text' and 'Value' properties hold the same value; such as if Array's element is 'Red' then DropDownList's corresponding ListItem object Text will be 'Red' and Value will be 'Red'.
StringArrayDropDownList.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    protected void Button1_Click(object sender, System.EventArgs e)
    {
        string[] controlArray = { "FileUpload", "Label", "HyperLink", "ListBox", "Literal" };
        Label1.Text = "String array created and bind with DropDownList successfully!";
        DropDownList1.DataSource = controlArray;
        DropDownList1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to populate (DataBind) DropDownList using string array DataSource in asp.net</title>
</head> 
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">asp.net array example: String Array and DropDownList</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Large"
             ForeColor="IndianRed"
             Font-Bold="true"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:DropDownList 
             ID="DropDownList1" 
             runat="server" 
             BackColor="Crimson" 
             ForeColor="FloralWhite"
             >
        </asp:DropDownList>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             OnClick="Button1_Click"
             Font-Bold="true"
             Text="Populate DropDownList With String Array"
             ForeColor="DodgerBlue"
             />   
    </div>
    </form>
</body>
</html>

c# - How to compare two strings by ignoring case


String Compare() Method - case insensitive/ ignore case



The .NET C# developers can compare two specified String objects using the String class’s Compare() method. The String Compare() method returns an integer that indicates their relative position in the sort order. This method is overloaded.




String Compare(String, String, Boolean) method overload compares two specified String objects by ignoring or honoring their case. So we can use this overloaded method to compare two string objects by ignoring case (case insensitive String comparison).




This overloaded method requires three parameters. First, two parameters are two String objects those we need to compare. And third parameter is a Boolean value. We must set the Boolean parameter value to True when we need to ignore the case during comparison. Or we must set the Boolean parameter value to False to respect the case during String comparison.




If the method returned integer is less than zero, then the first String (strA) is less than the second String (strB). If it returns zero, then two specified Strings are equal. And if the return value is greater than zero, then the first String is greater than the second string.




The following ASP.NET C# example code demonstrates to us how can we compare two Strings by ignoring their case.




CompareIgnoreCase.aspx



<%@ Page Language="C#" %>


<!DOCTYPE html>

<script runat="server">
protected void page_Load(object sender, System.EventArgs e) {
if(!this.IsPostBack)
{
TextBox1.Text = "Jones";
TextBox2.Text = "jones";
}
}
protected void Button1_Click(object sender, System.EventArgs e) {
string testString1 = TextBox1.Text.ToString();
string testString2 = TextBox2.Text.ToString();
int result = string.Compare(testString1, testString2,true);
Label1.Text = "";

if(result == 0)
{
Label1.Text += "Two strings are equal";
}
else if(result == 1)
{
Label1.Text += "Test String1 is greater than Test String2";
}
else if (result == -1)
{
Label1.Text += "Test String1 is less than Test String2";
}

}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to compare two string in asp.net (case insensitive/ ignore case)</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">asp.net string example: Compare() [Ignore case]</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="HotPink"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Test String1"
ForeColor="DodgerBlue"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="DodgerBlue"
ForeColor="Snow"
>
</asp:TextBox>
<br />
<asp:Label
ID="Label3"
runat="server"
Text="Test String2"
ForeColor="DodgerBlue"
>
</asp:Label>
<asp:TextBox
ID="TextBox2"
runat="server"
BackColor="DodgerBlue"
ForeColor="Snow"
>
</asp:TextBox>
<br /><br />
<asp:Button

ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Compare"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>








c# - How to compare two strings


String Compare() Method - case sensitive



The .NET framework has many methods to properly manipulate String. String Compare() method allows us to compare two String objects. This method is overloaded for various support such as we can compare strings by ignoring or honoring cases, we also can use culture-specific information to influence the comparison.




String class’s Compare(String, String, Boolean) overloaded method allows us to compare two string objects by honoring their case (case-sensitive string comparison). First, two parameters are two String objects that we want to compare and the third parameter is a Boolean value name ignoreCase. This Boolean parameter value False specifies the method to honor the case of the string during comparison.




This method return value is a 32-bit signed integer that indicates the relationship between the two string objects. If the return value is less than zero then the first string is less than the second String. Return value zero means two strings are equal. And the method return value greater than zero indicates the first string (strA) is greater than the second string (strB).




In the following example code, we use String Compare(String, String) method to compare strings by honoring their case. This comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters.




The following ASP.NET C# example code demonstrates to us a simple way to compare two strings by honoring their case in the .NET framework.




Compare.aspx



<%@ Page Language="C#" %>


<!DOCTYPE html>

<script runat="server">
protected void page_Load(object sender, System.EventArgs e) {
if(!this.IsPostBack)
{
TextBox1.Text = "apple.";
TextBox2.Text = "Apple.";
}
}
protected void Button1_Click(object sender, System.EventArgs e) {
string testString1 = TextBox1.Text.ToString();
string testString2 = TextBox2.Text.ToString();
int result = string.Compare(testString1, testString2);
Label1.Text = "";

if(result == 0)
{
Label1.Text += "Two strings are equal";
}
else if(result == -1)
{
Label1.Text += "Test String1 is less than Test String2";

}
else if(result == 1)
{
Label1.Text += "Test String1 is greater than Test String2";

}

}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to compare two string (case sensitive)</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Green">asp.net string example: Compare()</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="SeaGreen"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Test String1"
ForeColor="Red"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="OrangeRed"
ForeColor="AliceBlue"
>
</asp:TextBox>
<br />
<asp:Label
ID="Label3"
runat="server"
Text="Test String2"
ForeColor="Red"
>
</asp:Label>
<asp:TextBox
ID="TextBox2"
runat="server"
BackColor="OrangeRed"
ForeColor="AliceBlue"
>
</asp:TextBox>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Compare"
ForeColor="Crimson"
/>
</div>
</form>
</body>
</html>








c# - How to join an array elements into a new string


String Join() Method



The following asp.net c# example code demonstrate us how can we use .net framework's String Class Join() method
in an asp.net application. String.Join() method allow us to concatenate the elements of a specified array or the members
of a collection, using the specified separator between each element or member.




This member is overloaded, those are String.Join(String, IEnumerable<String>), Join<T>(String, IEnumerable<T>),
Join(String, Object[]), Join(String, String[]) and Join(String, String[], Int32, Int32). In this tutorial, we only discuss
about String.Join(String, String[]) overloaded method.




String.Join(String, String[]) method concatenate all the elements of a string array, using the specified separator between
each element. This method require to pass two parameters named 'separator' and 'value'. The 'separator' parameter value represent
a string to use as a separator and 'value' parameter represent an array that contains the elements to concatenate.




In this example, we concatenate a string array's elements by using a comma and a white space (, ) separator. Finally we get a System.String
object from a specified array elements where array items are separated by specified separator.



Join.aspx



<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
private string[] colorArray = { "Red", "Green", "Yellow", "HotPink", "SeaGreen" };

protected void page_Load(object sender, System.EventArgs e) {
if(!this.IsPostBack)
{
ListBox1.DataSource = colorArray;
ListBox1.DataBind();
}
}
protected void Button1_Click(object sender, System.EventArgs e) {
string testString = string.Join(", ", colorArray);
Label1.Text = "Joined successfully: " + testString;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to join an array of strings (elements) into a new string with specific separator</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Green">asp.net string example: Join()</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="Crimson"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
ForeColor="DodgerBlue"
Font-Bold="true"
Text="ListBox populated by an array"
>
</asp:Label>
<br />
<asp:ListBox
ID="ListBox1"
runat="server"
BackColor="DodgerBlue"
ForeColor="Snow"
>
</asp:ListBox>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Join array elements and build String"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>








c# - How to split a string with specific delimiter to populate an array


String Split() Method



The following asp.net c# example code demonstrates to us how can we split a String by specified delimiter and populate an array with splitter elements programmatically at run time in an asp.net application. The .net framework String Class represents text as a series of Unicode characters.




The String class’s Split() method returns a new String Array that contains the substrings in this instance that are delimited by elements of a specified String or Unicode character Array. This member is overloaded, those are Split(Char[]), Split(Char[], Int32), Split(Char[], StringSplitOptions), Split(Char[], Int32, StringSplitOptions) and Split(String[], Int32, StringSplitOptions).




In this example, we only discuss the Split(Char[]) overloaded method. The Split(Char[]) method returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array. This method requires passing a parameter named 'separator' which type is System.Char[]. This parameter value represents an array of Unicode characters that delimit the substrings in this instance, an empty array that contains no delimiters or null.




The Split(Char[]) method return’s value type is String[] which represents a String Array whose elements contain the substrings in this instance that are delimited by one or more characters in the parameter value.




In the following example, we initialize a String object with value, whose substrings are separated by '.' (dot). Then we call the Split(Char[]) method and pass the parameter value (Char Array) to it. We specify that the String will be split by the character '.' (dot) and create an Array with elements.





Split.aspx



<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
protected void page_Load(object sender, System.EventArgs e) {
if(!this.IsPostBack)
{
TextBox1.Text = "Red.Green.Blue.HotPink.Pink";
TextBox1.Width = 250;
}
}
protected void Button1_Click(object sender, System.EventArgs e) {
string myString = TextBox1.Text.ToString();
char[] separator = new char[] {'.'};
string[] colorList = myString.Split(separator);
ListBox1.DataSource = colorList;
ListBox1.DataBind();
ListBox1.Height = 100;
Label1.Text = "String split and populate ListBox successfully!";
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to split a string with specific delimiter and populate an array in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Teal">asp.net string example: Split</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="HotPink"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:ListBox
ID="ListBox1"
runat="server"
BackColor="DodgerBlue"
ForeColor="AliceBlue"
>
</asp:ListBox>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Test String"
ForeColor="DarkGreen"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="DarkSeaGreen"
ForeColor="DarkGreen"
>
</asp:TextBox>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Split String And Populate ListBox"
ForeColor="DarkGreen"
/>
</div>
</form>
</body>
</html>








c# - How to replace a substring of a string


String Replace() Method



In the .net framework, we can replace a string or a substring from a specified string with another string. The String Replace(String, String) method allows us to replace a string with another string.




This method returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string. Replace method requires two parameters. Both parameters type is System.String. The first parameter's name is oldValue that the string to be replaced. And the second parameter's name is newValue where the string replaces all occurrences of the old value.




If the method does not find oldValue in the current instance then it returns the current instance unchanged. Otherwise, it replaces the string with a specified string and returns a new string.




This method performs an ordinal (case sensitive and culture insensitive) search to find oldValue.




String.Replace(Char, Char) method returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character.




The following asp.net c# example code demonstrates to us how can we perform string replacement in the .net framework.





Replace.aspx



<%@ Page Language="C#" %>
<!DOCTYPE html>

<script runat="server">
protected void page_Load(object sender, System.EventArgs e) {
if(!this.IsPostBack)
{
TextBox1.Text = "This is a sample string.";
}
}
protected void Button1_Click(object sender, System.EventArgs e) {
string myString = TextBox1.Text.ToString();
string replaceString = myString.Replace("sample","test");

Label1.Text = "String replaced successfully [sample with test]!";
TextBox1.Text = replaceString;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to replace a specified substring with another string in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Maroon">asp.net string example: Replace()</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="Red"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Test String"
ForeColor="DarkSlateBlue"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="DarkSlateBlue"
ForeColor="AliceBlue"
>
</asp:TextBox>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Replace sample With test"
ForeColor="DarkSlateBlue"
/>
</div>
</form>
</body>
</html>








c# - How to convert a string to uppercase characters


String ToUpper() Method



The String represents text as a series of Unicode characters. String class’s ToUpper() method return a copy of the String converted to uppercase. This method is overloaded, those are ToUpper() and ToUpper(CultureInfo).




String ToUpper() method is in the System namespace and its return value type is a String. That returned 'string' is uppercase characters equivalent to the specified String. This ToUpper() method uses the casing rules of the current culture to convert each character to an uppercase equivalent.




The ToUpper() method does not modify the specified String instance, it just returns a new String instance in which all characters are converted to uppercase from the specified String.




The string ToUpper(CultureInfo) method returns a copy of the specified String converted to uppercase, using the casing rules of the specified culture.




The following .NET C# example code demonstrates to us how can we convert a String to uppercase characters in an ASP.NET application.





ToUpper.aspx



<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
protected void page_Load(object sender, System.EventArgs e) {
if(!this.IsPostBack)
{
TextBox1.Text = "Click the button for change characters to uppercase.";
TextBox1.Width = 450;
}
}
protected void Button1_Click(object sender, System.EventArgs e) {
string myString = TextBox1.Text.ToString();
string modifiedString = myString.ToUpper();

Label1.Text = "String converted successfully to upper case!";
TextBox1.Text = modifiedString;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to convert (change) a string to uppercase characters in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">asp.net string example: ToUpper()</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="Crimson"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Test String"
ForeColor="DarkCyan"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="DarkCyan"
ForeColor="Snow"
>
</asp:TextBox>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Change String To Uppercase"
ForeColor="DarkCyan"
/>
</div>
</form>
</body>
</html>








c# - How to get a substring from a string


String Substring() Method



The .net String class’s Substring() method allows us to retrieve a substring from a String object. This method has two overloaded methods those are Substring(Int32) and Substring(Int32, Int32).




The Substring(Int32) overloaded method retrieves a substring from a String by starting at a specified character position and continuing to the end of the String. This method needs to pass a parameter name startIndex. This parameter data type is Int32. The startIndex parameter value specifies a zero-based starting character position of the String. This method does not modify the current string instance, it returns a new String that begins at the startIndex position of the current String.




The Substring(Int32, Int32) overloaded method allows us to get a substring from a String that starts a specified character position String and has a specified length. This method has two parameters, which are startIndex and length. The startIndex is the zero-based starting character position of a substring in this instance. The length parameter specifies the number of characters in the substring.




The following asp.net c# example code demonstrates to us how we can get a substring from a String in the .net framework.





Substring.aspx



<%@ Page Language="C#" %>


<!DOCTYPE html>

<script runat="server">
protected void page_Load(object sender, System.EventArgs e) {
if(!this.IsPostBack)
{
TextBox1.Text = "Jones is here.";
}
}
protected void Button1_Click(object sender, System.EventArgs e) {
string myString = TextBox1.Text.ToString();
string subString = myString.Substring(0,5);

Label1.Text = "Substring[0,5]: " + subString;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to get substring from a string in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">asp.net string example: Substring()</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="Firebrick"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Test String"
ForeColor="Purple"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="Purple"
ForeColor="Snow"
>
</asp:TextBox>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Get Substring [0,5]"
ForeColor="Purple"
/>
</div>
</form>
</body>
</html>




c# - How to convert a string to int


Convert.ToInt32() Method - Convert string to numeric value



The .NET Convert class allows us to convert a base data type to another base data type. Convert class ToInt32(String) method converts the specified string representation of a number to an equivalent 32-bit signed integer.




Convert class’s ToInt32(String) overloaded method requires passing a parameter. This parameter name is 'value' which data type is String. This parameter passes the String that contains the number to convert. This method returns a 32-bit signed integer that is equivalent to the number in value. If the parameter value is null then the method returns zero (0).




We also can convert a string object to a numeric value (int 32-bit integer) by using Int32 Parse(String) method or Int32 TryParse() method. Int32 TryParse() method returns an additional value that indicates whether the conversion succeeded.




The following ASP.NET C# example code demonstrates to us how can we convert a string to an int32 numeric value in the .NET framework.





ToInt32.aspx



<%@ Page Language="C#" %>


<!DOCTYPE html>

<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e) {
string testString = "55";
int testNumber = Convert.ToInt32(testString);
int sum = testNumber + 5;
Label1.Text = "Test String: " + testString;
Label1.Text += "<br />Test String now converted to number[Int32]: " + testNumber;
Label1.Text += "<br />Test Number+5[after convert]: " + sum;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to convert string to numeric value (number ToInt32) in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">asp.net example: ToInt32()</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="DodgerBlue"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Convert String To Number"
ForeColor="DarkBlue"
/>
</div>
</form>
</body>
</html>




c# - How to get the number of days in a given month

Get days in month
DateTime.DaysInMonth() method return the number of days in the specified month and year. this method exists in System namespace.DateTime.DaysInMonth(year, month) method require to pass two parameters named 'year' and 'month'. the 'year' parameter valuedata type is System.Int32 which represent the specified year. the 'month' parameter value data type also System.int32 which representa month number ranging from 1 to 12.

This method return value data type is System.Int32 which represent the number of days in specified month for the specified year. this is very useful method to get the number of days in February month in a specified year which depend on leap year.

The following asp.net c# example code demonstrate us how can we get days (count number of days) in a specified month and year programmaticallyat run time in an asp.net application.
DaysInMonth.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        if(!this.IsPostBack)
        {
            Button1.Font.Bold = true;
            Button1.ForeColor = System.Drawing.Color.IndianRed;
            Button1.Text = "Get DaysInMonth";
            Label1.Font.Size = FontUnit.Larger;
            Label1.ForeColor = System.Drawing.Color.IndianRed;
            Label1.Font.Bold = true;
            Label1.Font.Italic = true;
        }
    }

    protected void Button1_Click(object sender, System.EventArgs e) {
        int year = DateTime.Now.Year;
        int month = DateTime.Now.Month;

        string dyasInMonth = DateTime.DaysInMonth(year,month).ToString();

        Label1.Text = "Today " + DateTime.Now.ToLongDateString();
        Label1.Text += "<br />Days In Month?: " + dyasInMonth;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to get days in month (DaysInMonth) in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Teal">asp.net date time example: DaysInMonth</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             OnClick="Button1_Click"
             />   
    </div>
    </form>
</body>
</html>

c# - How to get the current time of day

Get time of day
The following ASP.NET C# c# example code demonstrates to us how we can get the time from a DateTime object. The DateTime object represents an instance in time typically expressed as a date and time of day. The DateTime object exists in the .NET System namespace.

DateTime Now property gets a DateTime object that is set to the current date and time on a web server, expressed as the local time. In this example code at first, we create a DateTime variable and assign value by using the DateTime Now property.

Finally, we extract the time object from the DateTime variable by DateTime TimeOfDay property. TimeOfDay property gets a time interval that represents the fraction of the day that has elapsed since midnight from a DateTime object. This property value type is System.TimeSpan. So using the DateTime TimeOfDay property we can get the time from a DateTime object.

The TimeSpan object represents a time interval. We can display the time of day direct to the browser or we can format the result using DateTime ToString() method. We can use The ToString() method format parameter or composite formatting feature with the 't' or 'T' standard format string. 't' format specifier display the first character of the AM/PM designator. 'tt' format specifier display the AM/PM designator.
TimeOfDay.aspx

<%@ Page Language="C#" %>


<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        if(!this.IsPostBack)
        {
            Label1.Font.Size = FontUnit.Large;
            Label1.ForeColor = System.Drawing.Color.RoyalBlue;
            Label1.Font.Bold = true;
            Label1.Font.Italic = true;
            Button1.Font.Bold = true;
            Button1.ForeColor = System.Drawing.Color.RoyalBlue;
            Button1.Text = "Get Time Of Day";
        }
    }

    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime now = DateTime.Now;
        string timeOfDay = now.TimeOfDay.ToString();

        Label1.Text = "Now: " + DateTime.Now.ToString();
        Label1.Text += "<br />Time Of Day: " + timeOfDay;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to get time of day in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Red">asp.net date time example: TimeOfDay</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             OnClick="Button1_Click"
             />   
    </div>
    </form>
</body>
</html>

c# - How to subtract two DateTimes

Subtract two DateTimes
The following ASP.NET C# example code demonstrates to us how can we subtract two DateTime objects programmatically at run time in an asp.net application. The .NET framework's DateTime Subtract() method allows us to subtract the specified time or duration from this instance. DateTime Subtract() method is overloaded, those are Subtract(DateTime) and Subtract(TimeSpan).

DateTime Subtract(DateTime) overloaded method subtracts the specified date and time from the instance. We need to pass a DateTime object to this method as a parameter. This method returns a TimeSpan value. The return TimeSpan object represents a time interval that is equal to the date and time of the instance minus the date and time of the parameter.

DateTime Subtract(TimeSpan) overloaded method subtracts the specified duration from this instance. This method is required passing a TimeSpan object as the parameter. The TimeSpan represents the time interval to subtract. This overloaded method returns a System.DateTime object which is equal to the date and time of instance minus the time interval of the parameter.

After getting the return TimeSpan value from DateTime Subtract(DateTime) method, we can convert the TimeSpan to total days, hours, minutes, seconds, etc. So we can get the total days, hours, and minutes difference between two DateTime objects.
SubtractDateTime.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime firstDateTime = DateTime.Now;
        DateTime secondDateTime = DateTime.Now.AddDays(3);
        TimeSpan dateTimeDifference;
        dateTimeDifference = secondDateTime.Subtract(firstDateTime);


        double totalHours = dateTimeDifference.TotalHours;

        Label1.Text = "FirstDateTime: " + firstDateTime.ToString();
        Label1.Text += "<br />SecondDateTime: " + secondDateTime.ToString();
        Label1.Text += "<br /><br />Total Hours Difference Between Two DateTime Object: " + totalHours;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to subtract between two date time object</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">asp.net date time example: subtract date time</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Larger"
             Font-Italic="true"
             Font-Bold="true"
             ForeColor="DodgerBlue"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Font-Bold="true" 
             ForeColor="DarkBlue" 
             OnClick="Button1_Click"
             Text="Subtract Two DateTime Object"
             />   
    </div>
    </form>
</body>
</html>

c# - How to get days between two DateTimes

Days between two DateTimes
The following asp.net c# example code demonstrate us how can we get total days difference between two DateTime objectsprogrammatically at run time in an asp.net application.

DateTime.Subtract(DateTime) method allow us to subtract the specified date and time from this instance. We just need to passa DateTime object as parameter to subtract from specified DateTime object. DateTime.Subtract(DateTime) method return aSystem.TimeSpan type value. This TimeSpan value represents a time interval that is equal to the date and time of instance minusdate and time of parameter.

TimeSpan.TotalDays property get the value of the current TimeSpan structure expressed in whole and fractional days.

TimeSpan.Days property get the days component of the time interval represented by the current TimeSpan structure. This property doesnot return any fractional day, it just return full day part from a TimeSpan object. Result can be negative or positive number.

So to get the days between two datetimes, the procedure is; first subtract the two DateTime objects. Next, convert the returnTimeSpan object to number of days by using TimeSpan.TotalDays property or TimeSpan.Days property. Finally, we will getthe days difference between two date time objects.
TotalDays.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime myDate1 = DateTime.Now;
        DateTime myDate2 = DateTime.Now.AddYears(2);
        TimeSpan difference = myDate2.Subtract(myDate1);

        double totalDays = difference.TotalDays;

        Label1.Text = "MyDate1: " + myDate1.ToLongDateString();
        Label1.Text += "<br />MyDate2: " + myDate2.ToLongDateString();
        Label1.Text += "<br /><br />Total Days Difference: " + totalDays;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to get total days difference between two date time object</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">asp.net date time example: days difference</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Larger"
             Font-Italic="true"
             Font-Bold="true"
             ForeColor="Magenta"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Font-Bold="true" 
             ForeColor="Magenta" 
             OnClick="Button1_Click"
             Text="Get Toatal Days Difference"
             />   
    </div>
    </form>
</body>
</html>

c# - How to get hours between two DateTimes

Hours between two DateTimes
The following asp.net c# example code demonstrate us how can we get number of hours between two DateTimeobjects programmatically at run time in an asp.net application.

.Net framework's DateTime Class DateTime.Subtract(DateTime) overloaded method allow us to subtract a specifieddate and time from this instance. DateTime.Subtract() method need to pass a DateTime object to subtract from specifiedDateTime object.

This method return a System.TimeSpan value. This TimeSpan represent a time interval that is equalto the date and time represented by this instance minus the date and time passed by parameter.

TimeSpan.TotalHours property allow us to get the value of the current TimeSpan structure expressed in wholeand fractional hours.

TimeSpan.Hours property allow us to get the hours component of the time interval represented by the currentTimeSpan structure. This property return value type is System.Int32.

So, we can get total hours difference between two DateTime objects by this way. First, we subtarct two DateTime objects usingDateTime.Subtract(DateTime) method. Next, we get the total hours and fraction of hours from the returned TimeSpan objectusing TimeSpan.TotalHours property. We also can get the total hours difference without fraction of hours by using TimeSpan.Hoursproperty.
TotalHours.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime myDate1 = DateTime.Now;
        DateTime myDate2 = DateTime.Now.AddDays(8);
        TimeSpan difference = myDate2.Subtract(myDate1);

        double totalHours = difference.TotalHours;

        Label1.Text = "MyDate1: " + myDate1.ToString();
        Label1.Text += "<br />MyDate2: " + myDate2.ToString();
        Label1.Text += "<br /><br />Total Hours Difference: " + totalHours;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to get total hours difference between two date time object</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">asp.net date time example: hours difference</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Larger"
             Font-Italic="true"
             Font-Bold="true"
             ForeColor="Navy"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Font-Bold="true" 
             ForeColor="Navy" 
             OnClick="Button1_Click"
             Text="Get Toatal Hours Difference"
             />   
    </div>
    </form>
</body>
</html>

c# - How to add milliseconds to DateTime

DateTime AddMilliseconds() Method
The following asp.net c# example code demonstrate us how can we add specified number of Milliseconds witha DateTime object programmatically at run time. .Net framework's DateTime Class DateTime.AddMilliseconds() methodreturn a new DateTime object that add the specified number of milliseconds to the value of this instance.

DateTime.AddMilliseconds() method require to pass a parameter named 'value'. The 'value' parameter data type isSystem.Double which represent a number of whole and fractional milliseconds. This parameter value can be negative orpositive. So, we can technically add or subtract number of milliseconds from a DateTime instance. This parameter valueis rounded to the nearest integer.

DateTime.AddMilliseconds() method return value data type is System.DateTime. This return DateTime value is sum ofthe date and time represented by this instance and the number of milliseconds passed by parameter.

DateTime.AddMilliseconds() method through ArgumentOutOfRangeException, if the resulting DateTime object is less thanMinValue or greater than MaxValue.

One millisecond equal to 10000 ticks. The fractional part of the parameter value is the fractional part of millisecond.as example, parameter value 5.5 is equivalent to 5 milliseconds and 5000 ticks.
DateTimeAddMilliseconds.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime now = DateTime.Now;
        DateTime modifiedDatetime = now.AddMilliseconds(5000);
        Label1.ForeColor = System.Drawing.Color.IndianRed;
        Label1.Text ="ToDaty :" + now.ToString();
        Label1.Text += "<br />Your Date Time [after added 5000 milliseconds]: " + modifiedDatetime.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to add milliseconds (DateTime.Now.AddMilliseconds())</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">asp.net date time example: AddMilliseconds()</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Larger"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Font-Bold="true" 
             ForeColor="DarkCyan" 
             OnClick="Button1_Click"
             Text="Add 5000 Milliseconds With Now"
             />   
    </div>
    </form>
</body>
</html>

c# - How to add years to DateTime

DateTime AddYears() Method
The following asp.net c# example code demonstrate us how can we add one or more years with aDateTime object programmatically at run time in an asp.net application. .Net framework's DateTime Classhas a built in method to add years with a date.

DateTime.AddYears() method return a new DateTime object that add the specified number of years to the valueof this instance. This method require to pass a parameter named 'value'. The 'value' parameter data type isSystem.Int32. This integer value represent a number of years to add with specified DateTime object. This isinteresting that this parameter can be negative or positive. So, technically we can subtract years from a DateTime object.

DateTime.AddYears() method return value data type is System.DateTime. The return value represent a DateTime that is the sum ofthe date and time of this instance and the number of years pass by parameter.

DateTime.AddYears() method through ArgumentOutOfRangeException if the parameter or the resulting DateTime is less thanMinValue or greater than MaxValue.
DateTimeAddYears.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        Label1.Text = "Today :" + DateTime.Now.ToLongDateString();
    }
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime now = DateTime.Now;
        DateTime modifiedDatetime = now.AddYears(4);
        Label1.ForeColor = System.Drawing.Color.SlateBlue;
        Label1.Text ="ToDaty :" + now.ToLongDateString();
        Label1.Text += "<br />Your Date Time [after added 4 years]: " + modifiedDatetime.ToLongDateString();

    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to add years (DateTime.Now.AddYears())</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">asp.net date time example: AddYears()</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Larger"
             ForeColor="DarkSlateBlue"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Font-Bold="true" 
             ForeColor="DarkGreen" 
             OnClick="Button1_Click"
             Text="Add 4 Years With Today"
             />   
    </div>
    </form>
</body>
</html>

c# - How to add months to DateTime

DateTime AddMonths() Method
The following asp.net c# example code demonstrate us how can we add specified months with a DateTime objectprogrammatically at run time in an asp.net application. .Net framework's has a built in method DateTime.AddMonths()to add one or more months with a DateTime instance.

DateTime.AddMonths() method return a new DateTime object that add the specified number of months to the valueof this instance. This method require to pass a parameter named 'months'. The 'months' parameter value data typeis System.Int32. This integer value represent a number of months to add with a date. This parameter value can be negative orpositive. So, we can technically add or subtract/remove months from a date.

DateTime.AddMonths() method return a value which data type is System.DateTime. This return value is the sum of the date andtime represented by this instance and number of months passed by parameter.

DateTime.AddMonths() through ArgumentOutOfRangeException if the resulting DateTime object is less than MinValue or greaterthan MaxValue or passed number of months is less than -120000 or greater than 120000.
DateTimeAddMonths.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        Label1.Text = "Now :" + DateTime.Now.ToLongDateString();
    }
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime now = DateTime.Now;
        DateTime modifiedDatetime = now.AddMonths(2);
        Label1.ForeColor = System.Drawing.Color.DarkGreen;
        Label1.Text ="Now :" + now.ToLongDateString();
        Label1.Text += "<br />Your Date Time [after added 2 months]: " + modifiedDatetime.ToLongDateString();

    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to add months (DateTime.Now.AddMonths())</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Red">asp.net date time example: AddMonths()</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Larger"
             ForeColor="Green"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Font-Bold="true" 
             ForeColor="DeepPink" 
             OnClick="Button1_Click"
             Text="Add 2 Months With Now"
             />   
    </div>
    </form>
</body>
</html>

c# - How to add hours to DateTime

DateTime AddHours() Method
The following ASP.NET C# example code demonstrates to us how can we add one or more hours to a DateTime object programmatically at run time. The .Net framework's DateTime AddHours() method returns a new DateTime object that adds the specified number of hours to the value of this instance.

DateTime AddHours() method has a required parameter. This parameter name is value and its data type is a Double. This Double value represents the number of whole and fractional hours. This parameter value can be negative or positive. So, we can also subtract hours from a DateTime object if we pass a negative value as the parameter.

DateTime AddHours() method returns a DateTime object. The return DateTime object is the sum of the DateTime instance and the number of hours passed by the parameter. The fractional part of the value parameter value is the fractional part of an hour. Such as the Parameter value 5.5 is equivalent to 5 hours and 30 minutes.

This method does not change or modify the provided dateTime object instead it returns a new DateTime object which is the result of this operation.
DateTimeAddHours.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        Label1.Text = "Now :" + DateTime.Now.ToString();
    }
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime now = DateTime.Now;
        DateTime modifiedDatetime = now.AddHours(6);
        Label1.ForeColor = System.Drawing.Color.OrangeRed;
        Label1.Text ="Now :" + now.ToString();
        Label1.Text += "<br />Your Date Time [after added 6 hours]: " + modifiedDatetime.ToString();

    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to add hours (DateTime.Now.AddHours())</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">asp.net date time example: AddHours()</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Larger"
             ForeColor="SaddleBrown"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Font-Bold="true" 
             ForeColor="SaddleBrown" 
             OnClick="Button1_Click"
             Text="Add 6 Hours With Now"
             />   
    </div>
    </form>
</body>
</html>

c# - How to add minutes to DateTime

DateTime AddMinutes() Method
The following ASp.NET C# example code demonstrates to us how can we add minutes to a DateTime object programmatically at run time. The .Net framework's DateTime AddMinutes() method allows us to add one or more minutes with a DateTime object.

DateTime AddMinutes() method exists in the System namespace. AddMinutes() method has a required parameter named value. This value parameter data type is a Double which represents a number of whole and fractional minutes. This is very useful in that the value parameter value can be negative or positive. So, technically we can also subtract minutes from a DateTime object.

DateTime AddMinutes() method returns value data type is System.DateTime. This return value is a DateTime object which is the sum of specified minutes passed by the parameter and specified DateTime object. AddMinutes() method does not modify/change the provided DateTime object instead it returns a new DateTime object that is the result of this operation.

The DateTime AddMinutes() method through ArgumentOutOfRangeException exception if the resulting DateTime is less than MinValue or greater than MaxValue.
DateTimeAddMinutes.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        Label1.Text = "Now :" + DateTime.Now.ToString();
    }
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime now = DateTime.Now;
        DateTime modifiedDatetime = now.AddMinutes(30);
        Label1.ForeColor = System.Drawing.Color.HotPink;
        Label1.Text ="Now :" + now.ToString();
        Label1.Text += "<br />Your Date Time [after added 30 minutes]: " + modifiedDatetime.ToString();

    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to add minutes(DateTime.Now.AddMinutes())</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Purple">asp.net date time example: AddMinutes()</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Larger"
             ForeColor="DodgerBlue"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Font-Bold="true" 
             ForeColor="DodgerBlue" 
             OnClick="Button1_Click"
             Text="Add 30 Minutes With Now"
             />   
    </div>
    </form>
</body>
</html>

c# - How to add days to DateTime

Add days to a DateTime object
In the .NET framework, there are many built-in methods and properties are exists to manage DateTime objects. DateTime AddDays() method returns a new DateTime that adds the specified number of days to the value of this DateTime object instance.

This method requires passing a parameter. This parameter name is 'value' and its data type is Double. This value parameter passes a number of whole and fractional days. This value parameter can be a negative or positive number.

DateTime AddDays() method returns a System.DateTime type value. Return DateTime object is the sum of provided DateTime instance and the number of days passes by the parameter.

This method does not modify the provided DateTime object instead it returns the result as a new DateTime object.

The following ASP.NET C# example code demonstrates to us how can we add days with a DateTime object in the .NET framework.
DateTimeAddDays.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        Label1.Text = "Today :" + DateTime.Now.ToLongDateString();
    }
    protected void Button1_Click(object sender, System.EventArgs e) {
        DateTime date = DateTime.Now;
        DateTime arrivalDate = date.AddDays(7);
        Label1.ForeColor = System.Drawing.Color.DeepPink;
        Label1.Text ="Today :" + date.ToLongDateString();
        Label1.Text +="<br />Arraival day[after 7 days]: " + arrivalDate.ToLongDateString();

    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net date time example: how to add days(DateTime.Now.AddDays())</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Purple">asp.net date time example: AddDays()</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Larger"
             ForeColor="Green"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Font-Bold="true" 
             ForeColor="DeepPink" 
             OnClick="Button1_Click"
             Text="Add 7 days"
             />   
    </div>
    </form>
</body>
</html>