<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/" >

<channel>
	<title>Asp.Net &#8211; AspDotnetHelp.com</title>
	<atom:link href="https://aspdotnethelp.com/tutorials/asp-net/feed/" rel="self" type="application/rss+xml" />
	<link>https://aspdotnethelp.com</link>
	<description>Asp.Net and C#.Net Tutorials</description>
	<lastBuildDate>Sat, 23 Dec 2023 08:33:04 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.1</generator>

<image>
	<url>https://aspdotnethelp.com/wp-content/uploads/2023/08/aspdotnethelp-favicon-150x150.png</url>
	<title>Asp.Net &#8211; AspDotnetHelp.com</title>
	<link>https://aspdotnethelp.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Find Prime Numbers in an Array in C#?</title>
		<link>https://aspdotnethelp.com/find-prime-numbers-in-an-array-in-csharp/</link>
		
		<dc:creator><![CDATA[Bijay]]></dc:creator>
		<pubDate>Mon, 18 Dec 2023 08:00:00 +0000</pubDate>
				<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Find Prime Numbers in an Array in C#]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=842</guid>

					<description><![CDATA[Do you want to find prime numbers in a C# array? In this C# tutorial, I will explain how to find prime numbers in an array in C#. To find prime numbers in an array in C#, iterate through the array and check each number with a function that determines if it&#8217;s prime. This function ... <a title="How to Find Prime Numbers in an Array in C#?" class="read-more" href="https://aspdotnethelp.com/find-prime-numbers-in-an-array-in-csharp/" aria-label="Read more about How to Find Prime Numbers in an Array in C#?">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Do you want to find prime numbers in a C# array? In this C# tutorial, I will explain how to find prime numbers in an array in C#.</p>



<p class="wp-block-paragraph"><strong>To find prime numbers in an array in C#, iterate through the array and check each number with a function that determines if it&#8217;s prime. This function should return false for numbers less than 2 and then check divisibility up to the square root of the number, returning true only for numbers that are not divisible by any other number except 1 and themselves.</strong></p>



<h2 class="wp-block-heading">Find Prime Numbers in an Array in C#</h2>



<p class="wp-block-paragraph">Now, let us write a program to find prime numbers in an array in C#.</p>



<p class="wp-block-paragraph">A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, and so on.</p>



<p class="wp-block-paragraph">To check if a number is prime, we need to test if it is not divisible by any number less than itself and greater than 1. The most efficient way to do this is to check divisibility up to the square root of the number.</p>



<pre class="wp-block-code"><code>using System;
using System.Collections.Generic;

class PrimeFinder
{
    static void Main()
    {
        int&#91;] array = {2, 3, 4, 5, 6, 7, 11, 13, 17, 18, 19, 23, 29};
        List&lt;int&gt; primes = FindPrimesInArray(array);

        Console.WriteLine("Prime numbers in the array are:");
        foreach (int prime in primes)
        {
            Console.WriteLine(prime);
        }
    }

    static List&lt;int&gt; FindPrimesInArray(int&#91;] arr)
    {
        List&lt;int&gt; primeList = new List&lt;int&gt;();
        foreach (int num in arr)
        {
            if (IsPrime(num))
            {
                primeList.Add(num);
            }
        }
        return primeList;
    }

    static bool IsPrime(int num)
    {
        if (num &lt;= 1) return false;
        if (num &lt;= 3) return true;

        if (num % 2 == 0 || num % 3 == 0) return false;

        for (int i = 5; i * i &lt;= num; i += 6)
        {
            if (num % i == 0 || num % (i + 2) == 0)
                return false;
        }
        return true;
    }
}
</code></pre>



<ol class="wp-block-list">
<li><strong>Main Method</strong>: We define an array of integers and call <code>FindPrimesInArray</code> to filter out the primes.</li>



<li><strong>FindPrimesInArray Method</strong>: This method iterates through the array and uses <code>IsPrime</code> to check if each number is prime.</li>



<li><strong>IsPrime Method</strong>: It efficiently checks if a number is prime. We handle edge cases for numbers less than 4 and then check divisibility starting from 5, incrementing by 6 each time (since any prime number greater than 3 can be written in the form of 6k±1).</li>
</ol>



<p class="wp-block-paragraph">Once you run the code using a console application in C#, you can see the output in the below screenshot.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="1024" height="814" src="https://aspdotnethelp.com/wp-content/uploads/2023/11/find-prime-numbers-in-an-array-in-c-1024x814.png" alt="find prime numbers in an array in c#" class="wp-image-843" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/11/find-prime-numbers-in-an-array-in-c-1024x814.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2023/11/find-prime-numbers-in-an-array-in-c-300x239.png 300w, https://aspdotnethelp.com/wp-content/uploads/2023/11/find-prime-numbers-in-an-array-in-c-768x611.png 768w, https://aspdotnethelp.com/wp-content/uploads/2023/11/find-prime-numbers-in-an-array-in-c.png 1210w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">Finding prime numbers in an array using C# is a great way to understand basic programming concepts and number theory. In this C# tutorial, I have explained <strong>how to find prime numbers in an array in C#</strong> using the above simple program.</p>



<p class="wp-block-paragraph">You may also like:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/find-second-largest-number-in-an-array-in-csharp/">Write A Program To Find Second Largest Number In An Array In C#</a></li>



<li><a href="https://aspdotnethelp.com/csharp-string-array-contains-multiple-values/">C# String Array Contains Multiple Values</a></li>



<li><a href="https://aspdotnethelp.com/csharp-string-array-contains-null/">How to Check If C# String Array Contains Null?</a></li>



<li><a href="https://aspdotnethelp.com/csharp-string-array-contains-substring/">C# String Array Contains Substring</a></li>



<li><a href="https://aspdotnethelp.com/write-a-csharp-program-to-print-fibonacci-series/">Write a C# Program to Print Fibonacci Series</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://aspdotnethelp.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Bijay Kumar is a renowned software engineer, accomplished author, and distinguished <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="nofollow noopener" target="_blank">Microsoft Most Valuable Professional</a> (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. <a href="https://aspdotnethelp.com/about/" rel="nofollow noopener">Read more&#8230;</a></p>
</div></div><div class="saboxplugin-web "><a href="https://aspdotnethelp.com" target="_self">aspdotnethelp.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Youtube" target="_self" href="https://www.youtube.com/c/enjoysharepoint?sub_confirmation=1" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-youtube" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 576 512"><path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to create an array in asp.net using c#.net?</title>
		<link>https://aspdotnethelp.com/create-an-array-in-asp-net-using-csharp/</link>
		
		<dc:creator><![CDATA[Bijay]]></dc:creator>
		<pubDate>Thu, 17 Aug 2023 16:36:23 +0000</pubDate>
				<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[create an array in asp.net using c#.net]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=374</guid>

					<description><![CDATA[Arrays are fundamental data structures in C#.Net used to store multiple items of the same type. In this tutorial, we&#8217;ll focus exclusively on different ways to create an array in asp.net using c#.net. Create an array in asp.net using c#.net Let us now check, how to create different types of arrays in C#.Net. I am ... <a title="How to create an array in asp.net using c#.net?" class="read-more" href="https://aspdotnethelp.com/create-an-array-in-asp-net-using-csharp/" aria-label="Read more about How to create an array in asp.net using c#.net?">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Arrays are fundamental data structures in C#.Net used to store multiple items of the same type. In this tutorial, we&#8217;ll focus exclusively on different ways to <strong>create an array in asp.net using c#.net</strong>.</p>



<h2 class="wp-block-heading">Create an array in asp.net using c#.net</h2>



<p class="wp-block-paragraph">Let us now check, how to create different types of arrays in C#.Net. I am doing all the examples using an asp.net web form application and using C# as the language.</p>



<h3 class="wp-block-heading">Create a One-dimensional Array in C#.Net</h3>



<p class="wp-block-paragraph">Follow the below steps to <a href="https://aspdotnethelp.com/single-dimensional-array-in-csharp-with-example/" data-type="link" data-id="https://aspdotnethelp.com/single-dimensional-array-in-csharp-with-example/">create a one-dimensional array</a> in asp.net using C#.Net.</p>



<h4 class="wp-block-heading">Declare and Initialize Simultaneously</h4>



<p class="wp-block-paragraph">To declare an array and initialize it at the same time in C#.Net follow the below syntax:</p>



<pre class="wp-block-code"><code>int&#91;] numbers = { 1, 2, 3, 4, 5 };
</code></pre>



<h4 class="wp-block-heading">Declare First, Then Initialize</h4>



<p class="wp-block-paragraph">We can also create a one-dimensional array by declaring first and then initializing it.</p>



<p class="wp-block-paragraph">First, declare the array:</p>



<pre class="wp-block-code"><code>int&#91;] numbers;
</code></pre>



<p class="wp-block-paragraph">Then initialize it by specifying the size:</p>



<pre class="wp-block-code"><code>numbers = new int&#91;5];
</code></pre>



<p class="wp-block-paragraph">Or by specifying the values:</p>



<pre class="wp-block-code"><code>numbers = new int&#91;] { 1, 2, 3, 4, 5 };
</code></pre>



<h3 class="wp-block-heading">Create Multidimensional Arrays in C#.Net</h3>



<p class="wp-block-paragraph">Now, I will show you how to create a multidimensional array in C.Net.</p>



<h4 class="wp-block-heading">Rectangular Arrays</h4>



<p class="wp-block-paragraph">A C#.net rectangular array has multiple dimensions.</p>



<p class="wp-block-paragraph"><strong>Declare and Initialize:</strong></p>



<pre class="wp-block-code"><code>int&#91;,] matrix = new int&#91;2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
</code></pre>



<h3 class="wp-block-heading">Create Jagged Arrays in C#.Net</h3>



<p class="wp-block-paragraph">Now, let us see, how to create a jagged array in C#.Net.</p>



<p class="wp-block-paragraph">A jagged array is an array of arrays. Each sub-array can have a different length.</p>



<h4 class="wp-block-heading">Declare and Initialize</h4>



<pre class="wp-block-code"><code>int&#91;]&#91;] jaggedArray = new int&#91;3]&#91;];
jaggedArray&#91;0] = new int&#91;] { 1 };
jaggedArray&#91;1] = new int&#91;] { 2, 3 };
jaggedArray&#91;2] = new int&#91;] { 4, 5, 6 };

</code></pre>



<h3 class="wp-block-heading">Create an array using Array Class Methods</h3>



<p class="wp-block-paragraph">The <code>Array</code> class in C# offers methods to create and manipulate arrays.</p>



<p class="wp-block-paragraph"><code>Array.CreateInstance</code> allows you to create an array dynamically:</p>



<pre class="wp-block-code"><code>Array dynamicArray = Array.CreateInstance(typeof(int), 5);
</code></pre>



<p class="wp-block-paragraph">This creates an integer array of size 5.</p>



<h3 class="wp-block-heading">Create an array with default values in C#.Net</h3>



<p class="wp-block-paragraph">In C#, when an array is constructed without values, it&#8217;s initialized with default values. This is helpful in ASP.NET scenarios where placeholder values are needed.</p>



<pre class="wp-block-code"><code>int&#91;] defaultValuesArray = new int&#91;5];
string&#91;] defaultStrings = new string&#91;3];
bool&#91;] defaultBools = new bool&#91;3];</code></pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">Arrays in C#.Net are a pillar of ASP.NET development, allowing for versatile data storage and manipulation. With this guide, ASP.NET developers now have a robust understanding of <strong>creating arrays in C#.Net</strong>.</p>



<p class="wp-block-paragraph">You may also like:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/add-trailing-zeros-to-a-string-in-csharp/">add trailing zeros to a string in C#.net</a></li>



<li><a href="https://aspdotnethelp.com/generate-random-numbers-in-csharp-within-a-range-without-repeating/">generate random numbers in c#.net within a range without repeating</a></li>



<li><a href="https://aspdotnethelp.com/check-if-object-is-empty-or-null-in-c-sharp-net/">check if an object is empty or null in C#.Net</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://aspdotnethelp.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Bijay Kumar is a renowned software engineer, accomplished author, and distinguished <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="nofollow noopener" target="_blank">Microsoft Most Valuable Professional</a> (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. <a href="https://aspdotnethelp.com/about/" rel="nofollow noopener">Read more&#8230;</a></p>
</div></div><div class="saboxplugin-web "><a href="https://aspdotnethelp.com" target="_self">aspdotnethelp.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Youtube" target="_self" href="https://www.youtube.com/c/enjoysharepoint?sub_confirmation=1" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-youtube" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 576 512"><path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ASP.NET Control Naming Conventions</title>
		<link>https://aspdotnethelp.com/asp-net-control-naming-conventions/</link>
		
		<dc:creator><![CDATA[Bijay]]></dc:creator>
		<pubDate>Wed, 10 May 2023 12:39:50 +0000</pubDate>
				<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[ASP.NET Control Naming Conventions]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=167</guid>

					<description><![CDATA[Naming conventions are a crucial part of development best practices. Adopting appropriate naming conventions can improve code readability, maintenance, and understanding. In this tutorial, we will focus on ASP.NET Control Naming Conventions. The naming conventions can be used for all the ASP.NET Web Forms controls. ASP.NET Control Naming Conventions One of the most common conventions ... <a title="ASP.NET Control Naming Conventions" class="read-more" href="https://aspdotnethelp.com/asp-net-control-naming-conventions/" aria-label="Read more about ASP.NET Control Naming Conventions">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Naming conventions are a crucial part of development best practices. Adopting appropriate naming conventions can improve code readability, maintenance, and understanding. In this tutorial, we will focus on <strong>ASP.NET Control Naming Conventions</strong>. The naming conventions can be used for all the ASP.NET Web Forms controls.</p>



<h2 class="wp-block-heading">ASP.NET Control Naming Conventions</h2>



<p class="wp-block-paragraph">One of the most common conventions in ASP.NET control naming is the use of prefixes. A prefix is a short identifier added to the start of the name of the control. This prefix usually denotes the type of control.</p>



<p class="wp-block-paragraph">Here are some common prefixes used for ASP.NET controls with examples:</p>



<figure class="wp-block-table"><table><thead><tr><th>Control</th><th>Prefix</th><th>Example</th></tr></thead><tbody><tr><td>Button</td><td>btn</td><td><code>btnSubmit</code></td></tr><tr><td>Label</td><td>lbl</td><td><code>lblUsername</code></td></tr><tr><td>TextBox</td><td>txt</td><td><code>txtEmail</code></td></tr><tr><td>DropDownList</td><td>ddl</td><td><code>ddlCountry</code></td></tr><tr><td>ListBox</td><td>lst</td><td><code>lstOptions</code></td></tr><tr><td>DataGrid</td><td>dg</td><td><code>dgCustomerData</code></td></tr><tr><td>GridView</td><td>gv</td><td><code>gvOrderDetails</code></td></tr><tr><td>DetailsView</td><td>dv</td><td><code>dvEmployee</code></td></tr><tr><td>FormView</td><td>fv</td><td><code>fvRegistration</code></td></tr><tr><td>Repeater</td><td>rpt</td><td><code>rptProductList</code></td></tr><tr><td>DataList</td><td>dl</td><td><code>dlImages</code></td></tr><tr><td>CheckBox</td><td>chk</td><td><code>chkRememberMe</code></td></tr><tr><td>RadioButton</td><td>rdo</td><td><code>rdoGender</code></td></tr><tr><td>Calendar</td><td>cal</td><td><code>calBirthDate</code></td></tr><tr><td>ImageButton</td><td>imgbtn</td><td><code>imgbtnProfilePic</code></td></tr><tr><td>HyperLink</td><td>hlnk</td><td><code>hlnkHomepage</code></td></tr><tr><td>Image</td><td>img</td><td><code>imgLogo</code></td></tr><tr><td>Panel</td><td>pnl</td><td><code>pnlSidebar</code></td></tr><tr><td>PlaceHolder</td><td>ph</td><td><code>phContent</code></td></tr><tr><td>Literal</td><td>lit</td><td><code>litWelcomeMessage</code></td></tr><tr><td>Table</td><td>tbl</td><td><code>tblScores</code></td></tr><tr><td>TableRow</td><td>tr</td><td><code>trHeader</code></td></tr><tr><td>TableCell</td><td>tc</td><td><code>tcName</code></td></tr></tbody></table></figure>



<h2 class="wp-block-heading">Naming Convention Rules for Asp.Net Controls</h2>



<p class="wp-block-paragraph">When naming your controls, you should adhere to some rules that will make your code cleaner and more understandable.</p>



<h3 class="wp-block-heading">1. Use Camel Case</h3>



<p class="wp-block-paragraph">Camel case starts with a lowercase letter and the first letter of each subsequent concatenated word is capitalized. For example: <code>btnSubmit</code>.</p>



<h3 class="wp-block-heading">2. Use Meaningful Names</h3>



<p class="wp-block-paragraph">The name of the control should reflect its purpose. For example, a button used to submit a form could be named <code>btnSubmit</code>.</p>



<h3 class="wp-block-heading">3. Avoid Using Reserved Words</h3>



<p class="wp-block-paragraph">Avoid using language-specific reserved words in your control names. This can lead to confusion and potential runtime errors.</p>



<h3 class="wp-block-heading">4. Consistency</h3>



<p class="wp-block-paragraph">Ensure that you are consistent in your naming throughout your application. Consistency makes your code easier to read and understand.</p>



<h2 class="wp-block-heading">Examples</h2>



<p class="wp-block-paragraph">Following the above rules and using the standard control prefixes, here are some examples of control names:</p>



<ul class="wp-block-list">
<li>Button used for submitting a form: <code>btnSubmit</code></li>



<li>Text box to enter a username: <code>txtUsername</code></li>



<li>Drop down list for selecting a country: <code>ddlCountry</code></li>



<li>Label for displaying error messages: <code>lblError</code></li>



<li>Image button for a profile picture: <code>imgbtnProfilePic</code></li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="576" src="https://aspdotnethelp.com/wp-content/uploads/2023/05/ASP.NET-Control-Naming-Conventions-1024x576.jpg" alt="ASP.NET Control Naming Conventions" class="wp-image-168" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/05/ASP.NET-Control-Naming-Conventions-1024x576.jpg 1024w, https://aspdotnethelp.com/wp-content/uploads/2023/05/ASP.NET-Control-Naming-Conventions-300x169.jpg 300w, https://aspdotnethelp.com/wp-content/uploads/2023/05/ASP.NET-Control-Naming-Conventions-768x432.jpg 768w, https://aspdotnethelp.com/wp-content/uploads/2023/05/ASP.NET-Control-Naming-Conventions.jpg 1280w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">ASP.NET Control Naming Conventions</figcaption></figure>
</div>


<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">Adopting the right <strong>naming conventions for your ASP.NET controls</strong> can greatly improve your code quality. It enhances readability, makes maintenance easier, and overall, leads to more efficient development. Remember to use the standard control prefixes, meaningful names, camel case, and avoid using reserved words, and most importantly, be consistent in your naming throughout your application.</p>



<p class="wp-block-paragraph">You may also like:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/gridview-in-asp-net/">Gridview in asp.net</a></li>



<li><a href="https://aspdotnethelp.com/how-to-use-jquery-modal-popup-in-asp-net/">How to use jquery modal popup in asp.net</a></li>



<li><a href="https://aspdotnethelp.com/c-net-fields-naming-conventions/">C#.Net Fields Naming Conventions</a></li>



<li><a href="https://aspdotnethelp.com/c-sharp-dot-net-enum-naming-conventions/" target="_blank" rel="noreferrer noopener">C#.NET Enum Naming Conventions</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://aspdotnethelp.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Bijay Kumar is a renowned software engineer, accomplished author, and distinguished <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="nofollow noopener" target="_blank">Microsoft Most Valuable Professional</a> (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. <a href="https://aspdotnethelp.com/about/" rel="nofollow noopener">Read more&#8230;</a></p>
</div></div><div class="saboxplugin-web "><a href="https://aspdotnethelp.com" target="_self">aspdotnethelp.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Youtube" target="_self" href="https://www.youtube.com/c/enjoysharepoint?sub_confirmation=1" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-youtube" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 576 512"><path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to create a SOAP API request with Username Token in .Net</title>
		<link>https://aspdotnethelp.com/create-a-soap-api-request-with-username-token-in-net/</link>
		
		<dc:creator><![CDATA[Bijay]]></dc:creator>
		<pubDate>Mon, 24 Apr 2023 08:51:27 +0000</pubDate>
				<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[create a SOAP API request with Username Token in .Net]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=62</guid>

					<description><![CDATA[This c#.net tutorial explains, how to create a SOAP API request with user name token in .Net while connecting to a web service. Create a SOAP API request with Username Token in .Net Suppose I have a Web service URL from which I want to retrieve the data from outside organizations. https://15.32.54.09:80/enjoySharePoint_HTTPRouter/enjoySharePointWebservice Here I am ... <a title="How to create a SOAP API request with Username Token in .Net" class="read-more" href="https://aspdotnethelp.com/create-a-soap-api-request-with-username-token-in-net/" aria-label="Read more about How to create a SOAP API request with Username Token in .Net">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This c#.net tutorial explains, how to <strong>create a SOAP API request with user name token in .Net</strong> while connecting to a web service.</p>



<h2 class="wp-block-heading">Create a SOAP API request with Username Token in .Net</h2>



<p class="wp-block-paragraph">Suppose I have a Web service URL from which I want to retrieve the data from outside organizations.</p>



<p class="wp-block-paragraph">https://15.32.54.09:80/enjoySharePoint_HTTPRouter/enjoySharePointWebservice</p>



<p class="wp-block-paragraph">Here I am using <strong>SOAP UI</strong> to call the secure web service using WCF.  The SOAP header I need to generate to do this should contain a username, password, and created mob&#8230;</p>



<p class="wp-block-paragraph">Here is an example of a soap UI header that I use to hit the same service.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1024" height="554" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-soap-header-request.png" alt="create a soap header request" class="wp-image-64" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-soap-header-request.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-soap-header-request-300x162.png 300w, https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-soap-header-request-768x416.png 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">create a soap header request</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>How to get the same information using C # code</strong></p>



<p class="wp-block-paragraph"><strong>Step 1:</strong> Open the Visual Studio &#8211; &gt; Create a  new console application</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1024" height="283" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-SOAP-API-request-with-Username-Token.png" alt="create a SOAP API request with Username Token" class="wp-image-65" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-SOAP-API-request-with-Username-Token.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-SOAP-API-request-with-Username-Token-300x83.png 300w, https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-SOAP-API-request-with-Username-Token-768x212.png 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">create a SOAP API request with Username Token</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Step 2:</strong> Go to the references and add a service reference as per the below screenshot.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="341" height="413" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-soap-header-request-1.png" alt="create a soap header request" class="wp-image-66" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-soap-header-request-1.png 341w, https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-soap-header-request-1-248x300.png 248w" sizes="auto, (max-width: 341px) 100vw, 341px" /><figcaption class="wp-element-caption">create a soap header request</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Step 3:</strong> Add the above web service in your service reference and click on Go &#8211; &gt; Change the namespace name to any custom name -&gt; Click on <strong>OK </strong>after getting &#8220;<strong>GetUserInfo</strong>&#8221; function over here.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="534" height="429" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/how-to-create-a-SOAP-API-request-with-Username-Token.png" alt="how to create a SOAP API request with Username Token" class="wp-image-67" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/how-to-create-a-SOAP-API-request-with-Username-Token.png 534w, https://aspdotnethelp.com/wp-content/uploads/2023/04/how-to-create-a-SOAP-API-request-with-Username-Token-300x241.png 300w" sizes="auto, (max-width: 534px) 100vw, 534px" /><figcaption class="wp-element-caption">how to create a SOAP API request with Username Token</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Step 4: </strong> Next, copy and paste the below code which we can used to get the service output </p>



<pre class="wp-block-code"><code> &#91;WebMethod]
        public string GetUserInfo()
        {
            Soap.UserDTO dto = new Soap.UserDTO();

            try
            {
                Soap.UserBeanSEIClient client = new Soap.UserBeanSEIClient();
                client.ClientCredentials.UserName.UserName = "rswain";
                client.ClientCredentials.UserName.Password = "password@123";
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) =&gt; true);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                PasswordDigestBehavior behavior = new PasswordDigestBehavior("rswain", "password@123");
                client.Endpoint.Behaviors.Add(behavior);
                dto = client.getUserInfo("8873493980", "37232732", "kswain");
                var tem = dto;              
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return dto.cpyEngName;
        }</code></pre>



<p class="wp-block-paragraph"><strong>Note: </strong>Sometimes we will get certificate issues while connecting to outside service. So here we will call a method called PasswordDigestBehavior to generate the certificate automatically.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1024" height="283" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-SOAP-API-request-with-Username-Token-1.png" alt="create a soap header request c#.net" class="wp-image-68" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-SOAP-API-request-with-Username-Token-1.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-SOAP-API-request-with-Username-Token-1-300x83.png 300w, https://aspdotnethelp.com/wp-content/uploads/2023/04/create-a-SOAP-API-request-with-Username-Token-1-768x212.png 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">create a soap header request c#.net</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Step 6:</strong> Next create one more class called  <strong>PasswordDigestBehavior </strong>and copy and paste the below code.  </p>



<p class="wp-block-paragraph"><strong>PasswordDigestBehavior.cs</strong></p>



<pre class="wp-block-code"><code>using Microsoft.Web.Services3.Security.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Web;
using System.Xml;

namespace COTCWS
{
    partial class PasswordDigestBehavior : IEndpointBehavior
    {


        public string Username { get; set; }
        public string Password { get; set; }


        public PasswordDigestBehavior(string username, string password)
        {
            this.Username = username;
            this.Password = password;
        }


        void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            return;// throw new NotImplementedException();
        }


        void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(new PasswordDigestMessageInspector(this.Username, this.Password));

        }

        void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            return;// throw new NotImplementedException();
        }

        void IEndpointBehavior.Validate(ServiceEndpoint endpoint)
        {
            return;// throw new NotImplementedException();
        }
    }


    partial class PasswordDigestMessageInspector : IClientMessageInspector
    {
        public string Username { get; set; }
        public string Password { get; set; }


        public PasswordDigestMessageInspector(string username, string password)
        {
            this.Username = username;
            this.Password = password;
        }


        void IClientMessageInspector.AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            return;// throw new NotImplementedException();
        }


        object IClientMessageInspector.BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            // Use the WSE 3.0 security token class
            UsernameToken token = new UsernameToken(this.Username, this.Password, PasswordOption.SendPlainText);

            // Serialize the token to XML
            XmlElement securityToken = token.GetXml(new XmlDocument());

            //
            MessageHeader securityHeader = MessageHeader.CreateHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", securityToken, false);
            request.Headers.Add(securityHeader);

            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();
            try
            {
                System.IO.File.WriteAllText(@"c:\temp\testthord\" + DateTime.Now.ToString("MMddyyyyhhmmssfff") + ".xml", request.ToString());
            }
            catch { }

            // complete
            return Convert.DBNull;

            //throw new NotImplementedException();
        }
    }
}</code></pre>



<p class="wp-block-paragraph"><strong>Step 7:</strong> Next build the code and debug. Now you can get the output that is the same as your SOAP UI output.</p>



<p class="wp-block-paragraph">You may like the following tutorials:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/generate-otp-asp-net/">Generate One Time Password (OTP) in Asp.Net using C#.Net</a></li>



<li><a href="https://aspdotnethelp.com/how-to-create-a-guid-in-c-net/">How to create a GUID in C#.Net</a></li>
</ul>



<p class="wp-block-paragraph">This is the process to retrieve results from SOAP API.  </p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://aspdotnethelp.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Bijay Kumar is a renowned software engineer, accomplished author, and distinguished <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="nofollow noopener" target="_blank">Microsoft Most Valuable Professional</a> (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. <a href="https://aspdotnethelp.com/about/" rel="nofollow noopener">Read more&#8230;</a></p>
</div></div><div class="saboxplugin-web "><a href="https://aspdotnethelp.com" target="_self">aspdotnethelp.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Youtube" target="_self" href="https://www.youtube.com/c/enjoysharepoint?sub_confirmation=1" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-youtube" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 576 512"><path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Generate One Time Password (OTP) in Asp.Net using C#.Net (generate OTP in c#)</title>
		<link>https://aspdotnethelp.com/generate-otp-asp-net/</link>
		
		<dc:creator><![CDATA[Bijay]]></dc:creator>
		<pubDate>Mon, 24 Apr 2023 08:43:21 +0000</pubDate>
				<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[generate OTP asp.net]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=53</guid>

					<description><![CDATA[Are you trying to generate otp in c# or looking for an otp.net c# example? In this asp.net tutorial, I will explain with an example, how to generate Unique Random OTP i.e. One Time Password in Asp.Net using C#.Net. We will see a c# otp generator. generate otp in c# One Time Passwords are widely ... <a title="Generate One Time Password (OTP) in Asp.Net using C#.Net (generate OTP in c#)" class="read-more" href="https://aspdotnethelp.com/generate-otp-asp-net/" aria-label="Read more about Generate One Time Password (OTP) in Asp.Net using C#.Net (generate OTP in c#)">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Are you trying to <strong>generate otp in c#</strong> or looking for an <strong>otp.net c# example</strong>? In this asp.net tutorial, I will explain with an example, how to generate Unique Random OTP i.e. One Time Password in Asp.Net using C#.Net. We will see a <strong>c# otp generator</strong>.</p>



<h2 class="wp-block-heading">generate otp in c#</h2>



<p class="wp-block-paragraph">One Time Passwords are widely used by banks and other firms to validate the Mobile Numbers of their users. OTPs can be Alphanumeric or Numeric and generally have a length between 5-10 characters. We can easily do <strong>otp generation and verification in c#</strong>.</p>



<p class="wp-block-paragraph">My application is basically a login screen that uses username and password. Next, it will validate with the server to check a valid user or not. Once it validates with success result, next it will <strong>generate an OTP</strong> which will send to your register mobile no. The <strong>OTP last 5 minutes</strong>, after this time, it will expire and the user will need to generate a new one.</p>



<p class="wp-block-paragraph">Now I am going to explain to make easier your comprehension. First I start with a screenshot of my application. So here is the <strong>otp generation and verification in c#</strong> or <strong>c# otp generator</strong> example.</p>



<p class="wp-block-paragraph"><strong>Step 1:</strong> Open your Visual Studio next create a new solution.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="347" height="490" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/generate-otp-asp.net_.png" alt="generate otp asp.net" class="wp-image-54" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/generate-otp-asp.net_.png 347w, https://aspdotnethelp.com/wp-content/uploads/2023/04/generate-otp-asp.net_-212x300.png 212w" sizes="auto, (max-width: 347px) 100vw, 347px" /><figcaption class="wp-element-caption">generate otp asp.net</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Step 2: </strong>First I am going to create a simple login screen which will valid a registered user or not in my application.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="571" height="295" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/generate-otp-asp.net-using-c.net_.png" alt="generate otp asp.net using c#.net" class="wp-image-55" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/generate-otp-asp.net-using-c.net_.png 571w, https://aspdotnethelp.com/wp-content/uploads/2023/04/generate-otp-asp.net-using-c.net_-300x155.png 300w" sizes="auto, (max-width: 571px) 100vw, 571px" /><figcaption class="wp-element-caption">generate otp asp.net using c#.net</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Step 3: </strong>In this step, it will validate the credential if it will success then it will redirect to OTP page where you can see your registered mobile no which can help you to send an OTP.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="773" height="340" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generator-c.png" alt="otp generator c#" class="wp-image-56" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generator-c.png 773w, https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generator-c-300x132.png 300w, https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generator-c-768x338.png 768w" sizes="auto, (max-width: 773px) 100vw, 773px" /><figcaption class="wp-element-caption">otp generator c#</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Step 4: </strong>Next it will generate an OTP and same time OTP will send to your registered mobile no and the validity is only for 5 minutes after that it does not work. <br></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="840" height="618" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generation-and-verification-in-c.png" alt="otp generation and verification in c#" class="wp-image-57" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generation-and-verification-in-c.png 840w, https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generation-and-verification-in-c-300x221.png 300w, https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generation-and-verification-in-c-768x565.png 768w" sizes="auto, (max-width: 840px) 100vw, 840px" /><figcaption class="wp-element-caption">otp generation and verification in c#</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Step 4:</strong> If you will enter the correct OTP, then you can able to see the next page otherwise you will receive an alert ( Invalid OTP ).</p>



<p class="wp-block-paragraph"><strong>Note</strong>: One point should be noted.  Here I am using cookies to save the user credential because, If the same user wants to log in this application in the second time in the same day with the same browser then it won&#8217;t ask for OTP as this user has already logged in to the site for the same day. </p>



<p class="wp-block-paragraph">If the user will log in to the site in a different browser or different system then only it will ask you for OTP. The validity of the cookies is only for 24 hours after that it will delete automatically from your browser.</p>



<p class="wp-block-paragraph"><strong>Step 5:</strong> Here is the simple code to <strong>generate otp in c#.net</strong>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="651" height="114" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/how-to-generate-otp-asp.net_.png" alt="how to generate otp asp.net" class="wp-image-58" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/how-to-generate-otp-asp.net_.png 651w, https://aspdotnethelp.com/wp-content/uploads/2023/04/how-to-generate-otp-asp.net_-300x53.png 300w" sizes="auto, (max-width: 651px) 100vw, 651px" /><figcaption class="wp-element-caption">how to generate otp asp.net</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Step 6: </strong>Make sure you have created two tables in your database.  The name of the database is OTPdb and here I have created two tables called <strong>Login_Check_SP</strong> and <strong>OTPhistortbl</strong>.</p>



<p class="wp-block-paragraph">In <strong>Login_Check_Sp</strong> table: It will validate the authenticate user and <strong>OTPhistortbl </strong>is used to keep all OTP generation history of the user. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="601" height="616" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generator-c-1.png" alt="otp generator c#" class="wp-image-59" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generator-c-1.png 601w, https://aspdotnethelp.com/wp-content/uploads/2023/04/otp-generator-c-1-293x300.png 293w" sizes="auto, (max-width: 601px) 100vw, 601px" /><figcaption class="wp-element-caption">otp generator c#</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>Step 7:</strong> When your database gets created, next connect to your database through connection string which you have to set in web.config file.</p>



<pre class="wp-block-code"><code>&lt;configuration&gt;

    &lt;system.web&gt;
      &lt;compilation debug="true" targetFramework="4.5.2" /&gt;
      &lt;httpRuntime targetFramework="4.5.2" /&gt;
    &lt;/system.web&gt;
  &lt;connectionStrings&gt;
    &lt;add name="conStr" connectionString="Data Source=WIN-EGHTVPHQ2VT;Initial Catalog=OTPdb;Integrated Security=True;" providerName="System.Data.SqlClient" /&gt;
  &lt;/connectionStrings&gt;
&lt;/configuration&gt;</code></pre>



<p class="wp-block-paragraph"><strong>Step 8:</strong> Here is the HTML code for the Login screen and <strong>generate OTP in C#</strong>.</p>



<pre class="wp-block-code"><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %&gt;

&lt;!DOCTYPE html&gt;

&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head runat="server"&gt;
        &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"/&gt;
  &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"&gt;&lt;/script&gt;


    &lt;style type="text/css"&gt;
        @import url(https://fonts.googleapis.com/css?family=Exo:400,500,500italic,400italic,600,600italic,700,700italic,800,800italic,300,300italic);

        body {
  padding-top: 250px;
	/*The below background is just to add some color, you can set this to anything*/
  background: url(http://www.magic4walls.com/wp-content/uploads/2014/01/texture-blue-fonchik-simple-dark-colors-glow-background.jpg) no-repeat;
}

.login-form{width:390px;}
.login-title{font-family: 'Exo', sans-serif;text-align:center;color: white;}
.login-userinput{margin-bottom: 10px;}
.login-button{margin-top:10px;}
.login-options{margin-bottom:0px;}
.login-forgot{float: right;}
    &lt;/style&gt;
&lt;script type="text/javascript"&gt;
    window.onload = function () { $("#showPassword").hide(); }

    $("#txtPassword").on('change', function () {
        if ($("#txtPassword").val()) {
            $("#showPassword").show();
        }
        else {
            $("#showPassword").hide();
        }
    });

    $(".reveal").on('click', function () {
        var $pwd = $("#txtPassword");
        if ($pwd.attr('type') === 'password') {
            $pwd.attr('type', 'text');
        }
        else {
            $pwd.attr('type', 'password');
        }
    });
&lt;/script&gt;

    &lt;title&gt;
        Send OTP
    &lt;/title&gt;

    &lt;/head&gt;
&lt;body&gt;
   &lt;form runat="server"&gt;
       &lt;asp:ScriptManager ID="ScriptManager1" runat="server"&gt;&lt;/asp:ScriptManager&gt;
    &lt;div class="container login-form"&gt;
	&lt;h2 class="login-title"&gt;- Please Login -&lt;/h2&gt;
	&lt;div class="panel panel-default"&gt;

		&lt;div class="panel-body"&gt;
		
				&lt;div class="input-group login-userinput"&gt;
					&lt;span class="input-group-addon"&gt;&lt;span class="glyphicon glyphicon-user"&gt;&lt;/span&gt;&lt;/span&gt;
                    &lt;asp:TextBox ID="txtUser" class="form-control" runat="server" placeholder="Username"&gt;&lt;/asp:TextBox&gt;
				&lt;/div&gt;
				&lt;div class="input-group"&gt;
					&lt;span class="input-group-addon"&gt;&lt;span class="glyphicon glyphicon-lock"&gt;&lt;/span&gt;&lt;/span&gt;
                     &lt;asp:TextBox ID="txtPassword" runat="server" class="form-control" name="password" placeholder="Password"&gt;&lt;/asp:TextBox&gt;
					&lt;span id="showPassword" class="input-group-btn"&gt;
            &lt;button class="btn btn-default reveal" type="button"&gt;&lt;i class="glyphicon glyphicon-eye-open"&gt;&lt;/i&gt;&lt;/button&gt;
          &lt;/span&gt;  
				&lt;/div&gt;				
                &lt;asp:Button ID="Btnsubmit" class="btn btn-primary btn-block login-button" runat="server" Text="Login" OnClick="Btnsubmit_Click" /&gt;
				&lt;div class="checkbox login-options"&gt;
					&lt;label&gt;&lt;input type="checkbox"/&gt; Remember Me&lt;/label&gt;
					&lt;a href="#" class="login-forgot"&gt;Forgot Username/Passwor&lt;/a&gt;
				&lt;/div&gt;		
				
		        &lt;asp:Label ID="lblMsg" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;
				
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/div&gt;
        &lt;div class="modal fade" id="send_OTP" role="dialog"&gt;
            &lt;div class="modal-dialog"&gt;
                &lt;div class="modal-content"&gt;
                    &lt;div class="modal-header text-center"&gt;
                        &lt;a class="btn pull-right" data-dismiss="modal"&gt;&lt;span&gt;&amp;times;&lt;/span&gt;&lt;/a&gt;
                        &lt;h3 class="register_header"&gt;&lt;strong&gt;Please enter phone number to receive the code &lt;/strong&gt;&lt;/h3&gt;

                    &lt;/div&gt;
                    &lt;div class="modal-body"&gt;
                        &lt;asp:TextBox ID="txtPhone" CssClass="form-control"  runat="server"&gt;&lt;/asp:TextBox&gt;
                    &lt;/div&gt;
                    &lt;div class="modal-footer"&gt;                     
                        &lt;asp:Button ID="btnSendOTP" class="btn btn-success" UseSubmitBehavior="false" data-dismiss="modal" runat="server" Text="Send OTP" OnClick="btnSendOTP_Click" /&gt;                      
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;

       &lt;div class="modal fade" id="Receive_OTP" role="dialog"&gt;
            &lt;div class="modal-dialog"&gt;
                &lt;div class="modal-content"&gt;
                    &lt;div class="modal-header text-center"&gt;
                        &lt;a class="btn pull-right" data-dismiss="modal"&gt;&lt;span&gt;&amp;times;&lt;/span&gt;&lt;/a&gt;
                        &lt;h3 class="register_header"&gt;&lt;strong&gt;Please enter the OTP(One Time Password) sent to your registered mobile #:974xxxx5968 &lt;/strong&gt;&lt;/h3&gt;
                        &lt;h4&gt;This OTP will expire in 5 minutes.&lt;/h4&gt;

                    &lt;/div&gt;
                    &lt;div class="modal-body"&gt;
                        &lt;asp:TextBox ID="txtOTP" CssClass="form-control" placeholder="One Time Password" runat="server"&gt;&lt;/asp:TextBox&gt;
                    &lt;/div&gt;
                    &lt;div class="modal-footer"&gt;                     
                        &lt;asp:Button ID="verifyOTP" class="btn btn-success" UseSubmitBehavior="false" data-dismiss="modal" runat="server" Text="Validate OTP" OnClick="ValidateOTP_Click"/&gt;
                        &lt;asp:HyperLink ID="HyperLink1" runat="server"&gt;If you have not receive your OTP then click here&lt;/asp:HyperLink&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>



<p class="wp-block-paragraph"><strong>Step 8:</strong> Here is the code for .CS page. Here I have hardcoded a few things please ignore it while you use this code in your application.</p>



<pre class="wp-block-code"><code>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings&#91;"conStr"].ConnectionString);
    DataTable dt = new DataTable();
    SqlCommand cmd;
    SqlDataAdapter adp = new SqlDataAdapter();
    string randomNumber;
    string Cust_No = "12345";
    string Uname = "Rswain";
    string Mobile_no = "50965968";
    HttpCookie myCookie;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            lblMsg.Visible = false;
            txtPhone.Text = string.Format("974 XXXX") + Mobile_no.Substring(Mobile_no.Length - 4, 4);
        }
    }

    public void InsertOTPinDB()
    {
        string query = "INSERT INTO OTPhistroytbl (id,Customer_No,User_Id,OTP,ctime_Stamp,status) VALUES (@id,@Customer_No,@User_Id,@OTP,@ctime_Stamp,@status) ";
        cmd = new SqlCommand(query, con);
        con.Open();
        cmd.Parameters.AddWithValue("@id", 2);
        cmd.Parameters.AddWithValue("@Customer_No", Cust_No.ToString());
        cmd.Parameters.AddWithValue("@User_Id", Uname);
        cmd.Parameters.AddWithValue("@OTP", randomNumber);
        cmd.Parameters.AddWithValue("@ctime_Stamp", System.DateTime.Now.ToString());
        cmd.Parameters.AddWithValue("@status", "1");
        cmd.ExecuteNonQuery();
        con.Close();
    }
    protected void Btnsubmit_Click(object sender, EventArgs e)
    {
        lblMsg.Visible = true;
        if (txtUser.Text == "")
        {
            lblMsg.Text = "Enter UserName";
        }
        else if (txtPassword.Text == "")
        {
            lblMsg.Text = "Enter Password";
        }
        else
        {
            try
            {
                lblMsg.Visible = false;
                adp = new SqlDataAdapter("SELECT COUNT(*) FROM Login_Check_Sp WHERE username='" + txtUser.Text + "' AND pwd='" + txtPassword.Text + "'", con);
                adp.Fill(dt);
                if (dt.Rows&#91;0]&#91;0].ToString() == "1")
                {
                    HttpCookie userCookie = new HttpCookie("myCookie");
                    userCookie.Values.Add("customerID", Cust_No.ToString());
                    userCookie.Expires = DateTime.Now.AddHours(24);
                    Response.Cookies.Add(userCookie);
                    myCookie = Request.Cookies&#91;"myCookie"];
                    if (myCookie == null)
                    {
                        // No cookie found or cookie expired. :(
                        ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "&lt;script&gt;$('#send_OTP').modal('show');&lt;/script&gt;", false);

                    }

                    // Verify the cookie value
                    if (!string.IsNullOrEmpty(myCookie.Values&#91;"customerID"]))  // userId is found
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "&lt;script&gt;$('#send_OTP').modal('show');&lt;/script&gt;", false);
                        string userId = myCookie.Values&#91;"customerID"].ToString();

                        String result;
                        String name = txtOTP.Text;
                        string apiKey = "DrXhf8CYfmQ-NcAXvBPyPySQXYmDwfBlnBNBJPt7dQ";
                        string numbers = Mobile_no.ToString();
                        Random rnd = new Random();
                        randomNumber = (rnd.Next(100000, 999999)).ToString();

                        string message = "Hey " + name + "your otp is " + randomNumber;
                        string send = "enjoysharepoint";

                        String url = "https://api.txtlocal.com/send/?apikey=" + apiKey + "&amp;numbers=" + numbers + "&amp;message=" + message + "&amp;sender=" + send;
                        //refer to parameters to complete correct url string

                        StreamWriter myWriter = null;
                        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);

                        objRequest.Method = "POST";
                        objRequest.ContentLength = Encoding.UTF8.GetByteCount(url);
                        objRequest.ContentType = "application/x-www-form-urlencoded";
                        try
                        {
                            myWriter = new StreamWriter(objRequest.GetRequestStream());
                            myWriter.Write(url);
                            InsertOTPinDB();
                        }
                        catch (Exception eX)
                        {
                            lblMsg.Text = eX.Message;
                        }
                        finally
                        {
                            myWriter.Close();
                        }
                        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
                        using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
                        {
                            result = sr.ReadToEnd();
                            // Close and clean up the StreamReader
                            sr.Close();
                        }
                        lblMsg.Text = result;
                    }

                    if (Request.Cookies&#91;"customerID"] != null)
                    {
                        // This will delete the cookie userId
                        Response.Cookies&#91;"customerID"].Expires = DateTime.Now.AddDays(-1);
                        lblMsg.Text = "logined successfully";
                    }
                }
                else
                {
                    lblMsg.Text = "Wrong Username/Password";
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! following error occured : " + ex.Message.ToString() + "');", true);
                // Response.Write("Oops!! following error occured: " +ex.Message.ToString());           
            }
            finally
            {
                dt.Clear();
                dt.Dispose();
                adp.Dispose();
            }
        }
    }
    protected void btnSendOTP_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "&lt;script&gt;$('#Receive_OTP').modal('show');&lt;/script&gt;", false);
    }

    protected void ValidateOTP_Click(object sender, EventArgs e)
    {
        lblMsg.Visible = true;
        adp = new SqlDataAdapter("SELECT ctime_Stamp FROM OTPhistroytbl WHERE OTP='" + txtOTP.Text + "'", con);
        adp.Fill(dt);
        DateTime OtpCrtDate = Convert.ToDateTime(dt.Rows&#91;0]&#91;0].ToString());

        if (txtOTP.Text != randomNumber)
        {
            TimeSpan timeSub = DateTime.Now - OtpCrtDate;
            if (timeSub.TotalMinutes &lt; 300)
            {
                cmd = new SqlCommand("update OTPhistroytbl set status='0' where OTP='" + txtOTP.Text + "'", con);
                con.Open();
                cmd.ExecuteNonQuery();
                lblMsg.Text = "logined successfully";
                con.Close();
            }
            else
            {
                lblMsg.Text = "Sorry but your OTP is very old. Get a new one";
            }
        }
        else
        {

            lblMsg.Text = "Sorry, Your OTP is Invalid. Try again, please.";
        }
    }
}</code></pre>



<p class="wp-block-paragraph"><strong>Note:</strong> For sending <strong>OTP </strong>to mobile, It may not be work for you because this key doesn&#8217;t work for you. You have to generate your own key to sending OTP to your mobile or you can use this OTP while sending in an email instead of sending as SMS in mobile.</p>



<p class="wp-block-paragraph"><strong>Step 9: </strong> Please look into my OTP result in a SQL database which is shown below. Here Id, Customer_no, and User_Id should populate dynamically as I have hardcoded here.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="876" height="375" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/generate-otp-in-c.png" alt="generate otp in c#" class="wp-image-60" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/generate-otp-in-c.png 876w, https://aspdotnethelp.com/wp-content/uploads/2023/04/generate-otp-in-c-300x128.png 300w, https://aspdotnethelp.com/wp-content/uploads/2023/04/generate-otp-in-c-768x329.png 768w" sizes="auto, (max-width: 876px) 100vw, 876px" /><figcaption class="wp-element-caption">generate otp in c#</figcaption></figure>
</div>


<p class="wp-block-paragraph">Please try with your end and let me know if anyone facing any problems.</p>



<p class="wp-block-paragraph">You may like the following asp.net tutorials:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/gridview-in-asp-net/">Gridview in asp.net</a></li>



<li><a href="https://aspdotnethelp.com/how-to-create-a-guid-in-c-net/">How to create a GUID in C#.Net</a></li>



<li><a href="https://aspdotnethelp.com/create-a-soap-api-request-with-username-token-in-net/">How to create a SOAP API request with Username Token in .Net</a></li>



<li><a href="https://aspdotnethelp.com/asp-net-control-naming-conventions/">ASP.NET Control Naming Conventions</a></li>
</ul>



<p class="wp-block-paragraph">Hope this asp.net tutorial explains, how to <strong>generate otp in asp.net using c#.net</strong>. The article solves the below queries:</p>



<ul class="wp-block-list">
<li>How to send otp on mobile in asp.net c#</li>



<li>c# otp generator</li>



<li>otp generation and verification in c#</li>



<li>generate otp in c#</li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://aspdotnethelp.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Bijay Kumar is a renowned software engineer, accomplished author, and distinguished <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="nofollow noopener" target="_blank">Microsoft Most Valuable Professional</a> (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. <a href="https://aspdotnethelp.com/about/" rel="nofollow noopener">Read more&#8230;</a></p>
</div></div><div class="saboxplugin-web "><a href="https://aspdotnethelp.com" target="_self">aspdotnethelp.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Youtube" target="_self" href="https://www.youtube.com/c/enjoysharepoint?sub_confirmation=1" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-youtube" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 576 512"><path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Gridview in asp.net</title>
		<link>https://aspdotnethelp.com/gridview-in-asp-net/</link>
		
		<dc:creator><![CDATA[Bijay]]></dc:creator>
		<pubDate>Mon, 24 Apr 2023 08:34:53 +0000</pubDate>
				<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Gridview in asp.net]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=49</guid>

					<description><![CDATA[This asp.net tutorial explains, gridview in asp.net. How to bind gridview using data reader in asp.net. How to add Eval for a hyperlink in gridview in asp.net? And, how to apply color in gridview rows based dynamically. Then we will discuss how to export gridview data to excel sheet in Asp.net? And, how to export ... <a title="Gridview in asp.net" class="read-more" href="https://aspdotnethelp.com/gridview-in-asp-net/" aria-label="Read more about Gridview in asp.net">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This asp.net tutorial explains, <strong>gridview in asp.net</strong>. How to <strong>bind gridview using data reader in asp.net</strong>. How to <strong>add Eval for a hyperlink in gridview in asp.net</strong>? And, how to <strong>apply color in gridview rows</strong> based dynamically.</p>



<p class="wp-block-paragraph">Then we will discuss how to <strong>export gridview data to excel sheet in Asp.net</strong>? And, how to export gridview to word in asp.net c#.net. We will also discuss how to display a confirmation message in gridview for delete in Asp.net. We will also see, how to send or pass girdview row value to the next page using a hyperlink in asp.net.</p>



<h2 class="wp-block-heading">Gridview in asp.net</h2>



<p class="wp-block-paragraph"><strong>Gridview </strong>is a control in asp.net which displays data in a tabular format. Gridview control displays the values of a data source in a table where each column represents a field and each row represents a record in asp.net. The asp.net GridView control enables you to select, sort, and edit these items.</p>



<p class="wp-block-paragraph">There are different ways we can bind data to gridview in asp.net.</p>



<h2 class="wp-block-heading">Bind gridview using datareader in asp.net</h2>



<p class="wp-block-paragraph">Now, we will see how to bind <a rel="noreferrer noopener" aria-label="gridview (opens in a new tab)" class="rank-math-link" href="https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.gridview?view=netframework-4.8" target="_blank">gridview</a> using data reader in asp.net.</p>



<p class="wp-block-paragraph">Below is the full code to bind gridview using a data reader in Asp.Net. Here we have used a stored procedure to retrieve data from the database:</p>



<p class="wp-block-paragraph"><strong>Stored Procedure:</strong></p>



<pre class="wp-block-code"><code>CREATE PROCEDURE Select_Employees

AS
BEGIN
Select * from Employees
END
GO</code></pre>



<p class="wp-block-paragraph">HTML Code:</p>



<pre class="wp-block-code"><code>&lt;asp:GridView ID="GridView1" runat="server" &gt;
&lt;/asp:GridView&gt;</code></pre>



<p class="wp-block-paragraph"><strong>.cs code:</strong></p>



<pre class="wp-block-code"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
string conn = "Data Source=localhost;database=sample;Integrated Security=true";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridview();
}
}

private void bindGridview()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("Select_Employees", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
}
catch (Exception ex)
{
}
finally
{
con.Close();
}
}
}</code></pre>



<p class="wp-block-paragraph">But we can not implement paging in gridview with data reader in asp.net.</p>



<h2 class="wp-block-heading">Bind GridView Using Dataset in Asp.Net</h2>



<p class="wp-block-paragraph">Now, we will see how to bind gridview using dataset in asp.net.</p>



<pre class="wp-block-code"><code>&lt;asp:GridView ID="GridView1" runat="server" &gt;
&lt;/asp:GridView&gt;</code></pre>



<p class="wp-block-paragraph">Below is the C#.Net code to bind gridview using dataset in asp.net.</p>



<pre class="wp-block-code"><code>SqlConnection con = new SqlConnection(@"Data Source=localhost;database=sample;Integrated Security=true");  
SqlCommand cmd = new SqlCommand("select * from Employees", con);  
SqlDataAdapter da = new SqlDataAdapter(cmd);  
DataSet ds = new DataSet();  
da.Fill(ds);  
GridView1.DataSource = ds;  
GridView1.DataBind();  </code></pre>



<h2 class="wp-block-heading">How to add Eval for hyperlink in gridview in asp.net?</h2>



<p class="wp-block-paragraph">Now, we will see how to add Eval property into hyperlink field in gridview in Asp.Net.</p>



<p class="wp-block-paragraph">In this scenario, we will see how a user can navigate to a different page with a query string parameter. In the below code it will see a list of usernames which are binding from the database. Then whenever a user clicks on a particular username, then it will navigate to a UserDetails page with taking UserID as a query string parameter.</p>



<pre class="wp-block-code"><code>&lt;asp:TemplateField HeaderText="Name"&gt;

&lt;ItemTemplate&gt;
&lt;asp:HyperLink ID="hylMachineNum" runat="server" NavigateUrl='&lt;%# "~/UserDetails.aspx?UserID=" + Eval("UserID")%&gt;' Text='&lt;%#Eval("UserName")%&gt;'&gt;
&lt;/asp:HyperLink&gt;
&lt;/ItemTemplate&gt;
&lt;/asp:TemplateField&gt;</code></pre>



<p class="wp-block-paragraph">Here the Text value is coming from the Eval property by the following syntax.</p>



<pre class="wp-block-code"><code>Text='&lt;%#Eval("UserName")%&gt;'</code></pre>



<p class="wp-block-paragraph">And the NavigateURL property is coming from the below property:</p>



<pre class="wp-block-code"><code>NavigateUrl='&lt;%# "~/UserDetails.aspx?UserID=" + Eval("UserID")%&gt;'</code></pre>



<h2 class="wp-block-heading">Apply color in gridview rows based dynamically</h2>



<p class="wp-block-paragraph">Now, we will see how to fill colors in gridview based on some conditions and values in asp.net.</p>



<p class="wp-block-paragraph">Say for an example: if a gridview has different departments in different locations. Need to color the gridview values based on the locations and display the top scorers of the winner’s department wise. </p>



<p class="wp-block-paragraph">Add OnRowDataBound EVENT for the gridview and the find</p>



<pre class="wp-block-code"><code>protected void GvLeaderBorad_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
if (e.Row.RowType == DataControlRowType.DataRow)
            {
  Label lblNett = e.Row.FindControl("lbl_Net") as Label;
                if (lblNett.Text == Locations.Chennai.ToString())
                {
                    e.Row.Cells&#91;0].BackColor = System.Drawing.Color.DarkGreen;
                }
}
}</code></pre>



<p class="wp-block-paragraph">When the color code is fetched from label placed inside the row . It will be applied to the entire row. Thus in code itself when we bind the grid. Provide row color in the label and fetch the color code from it.</p>



<p class="wp-block-paragraph">Apply the color code(Html hex code ex: #fffff ) to the gridview row.</p>



<h2 class="wp-block-heading">Export gridview data to excel sheet in Asp.net</h2>



<p class="wp-block-paragraph">Now, we will see how to export gridview data to excel sheet in asp.net.</p>



<p class="wp-block-paragraph">Below is the full code to export gridview data to excel sheet in Asp.net.</p>



<pre class="wp-block-code"><code>protected void btnExport_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = GetDataForGridView();
string attachment = attachment = "attachment; filename=MyExcelSheetName_" + DateTime.Now.ToString() + ".xls";
if (ds.Tables.Count &gt; 0)
{
DataTable dt = ds.Tables&#91;0];
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
//This will give you the number of columns present in gridview
for (int coulumns = 0; coulumns &lt; GridView1.Columns.Count; coulumns++)
{
Response.Write(tab + GridView1.Columns&#91;coulumns].HeaderText);
tab = "\t";
}
Response.Write("\n");

//Here we will visit each row of datatable and bind the corresponding column data.
foreach (DataRow dr in dt.Rows)
{
tab = "";
Response.Write(tab + dr&#91;"ColumnName1"].ToString());
tab = "\t";
Response.Write(tab + dr&#91;"ColumnName2"].ToString());
tab = "\t";
Response.Write(tab + dr&#91;"ColumnName3"].ToString());
tab = "\t";
Response.Write("\n");
}
Response.End();
}
}</code></pre>



<h2 class="wp-block-heading">Export gridview to word in asp.net c#</h2>



<p class="wp-block-paragraph">Now, we will see how we can download or export gridview data to word document in asp.net using c#.net. Here I have developed an asp.net website where we have used a gridview to bind the data from SQL server table and then we have a button, on the button click we are exporting the data to word format.</p>



<p class="wp-block-paragraph">Below is the .aspx code.</p>



<pre class="wp-block-code"><code>&lt;asp:GridView ID="GridView1" runat="server"&gt;&lt;/asp:GridView&gt;&lt;br /&gt;
&lt;asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="btnDownload_Click" /&gt;</code></pre>



<p class="wp-block-paragraph"><strong>.aspx.cs code:</strong></p>



<p class="wp-block-paragraph">Below is the .cs code.</p>



<pre class="wp-block-code"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;

namespace EnjoySharePointBackup
{
public partial class _Default : Page
{

private SqlConnection con;
private SqlCommand com;
private string constr, query;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindgrid();

}
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
private void connection()
{
string constr = "Data Source=YourDataSource;database=EnjoySharePoint;User ID=User1;Password=**********;";
con = new SqlConnection(constr);
con.Open();

}
protected void btnDownload_Click(object sender, EventArgs e)
{
ExportGridToword();
}
private void Bindgrid()
{
connection();
query = "select * from jobmaster where JobID"+ TextBox1.Text;
com = new SqlCommand(query, con);
SqlDataReader dr = com.ExecuteReader();

GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();

}

private void ExportGridToword()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "EnjoySharePoint" + DateTime.Now + ".doc";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/msword";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
}
}</code></pre>



<p class="wp-block-paragraph">This way we can export gridview data to word in asp.net using c#.net.</p>



<h2 class="wp-block-heading">Show confirmation message in gridview for delete in Asp.net</h2>



<p class="wp-block-paragraph">Now, we will see how to show a confirmation message while deleting a record from the gridview in asp.net. Like it should first as us whether you want to delete the record and then if the user clicks on yes then it should delete the record.</p>



<p class="wp-block-paragraph">There are different ways to show confirmation message in gridview for delete in Asp.net.</p>



<p class="wp-block-paragraph"><strong>1st Approach:</strong></p>



<p class="wp-block-paragraph">You can directly write in the OnClientClick event of the LinkButton like below:</p>



<pre class="wp-block-code"><code>&lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"&gt;
&lt;Columns&gt;
&lt;asp:TemplateField&gt;
&lt;ItemTemplate&gt;
&lt;asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='&lt;%#Eval("UserID") %&gt;'
CommandName="Delete" OnClientClick="return confirm(‘Are you sure you want to delete this record?');"&gt;Delete&lt;/asp:LinkButton&gt;
&lt;/ItemTemplate&gt;
&lt;/asp:TemplateField&gt;
&lt;/Columns&gt;
&lt;/asp:GridView&gt;</code></pre>



<p class="wp-block-paragraph"><strong>2nd Approach:</strong></p>



<p class="wp-block-paragraph">You can write a javascript function and call that function in the OnClientClick event like below:</p>



<pre class="wp-block-code"><code>&lt;head runat="server"&gt;
&lt;title&gt;Show confirmation message in gridview for delete in Asp.net&lt;/title&gt;
&lt;script type="text/javascript"&gt;
function DeleteRecord() {
return confirm("Are you sure you want to delete this record?");
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form id="form1" runat="server"&gt;
&lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"&gt;
&lt;Columns&gt;
&lt;asp:TemplateField&gt;
&lt;ItemTemplate&gt;
&lt;asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='&lt;%#Eval("UserID") %&gt;'
CommandName="Delete" OnClientClick="return DeleteRecord();"&gt;Delete&lt;/asp:LinkButton&gt;
&lt;/ItemTemplate&gt;
&lt;/asp:TemplateField&gt;
&lt;/Columns&gt;
&lt;/asp:GridView&gt;
&lt;/form&gt;
&lt;/body&gt;</code></pre>



<p class="wp-block-paragraph">This way we can display confirmation message in gridview for delete in Asp.net.</p>



<h2 class="wp-block-heading">Send GridView row data to the next page using Hyperlink in Asp.Net</h2>



<p class="wp-block-paragraph">Now, we will see how to send or pass girdview row value to the next page using a hyperlink in asp.net. </p>



<p class="wp-block-paragraph">Follow the below steps:</p>



<p class="wp-block-paragraph">Add hyperlink column in the gridview control. And set the data fields to navigate to the next page in the DataNavigateUrlFields property of the hyperlink field.</p>



<p class="wp-block-paragraph">Then Pass Query String value in DataNavigateUrlFormatString property of the hyperlink field.</p>



<p class="wp-block-paragraph">Retrieve data in the 2nd page using Request.QueryString.</p>



<p class="wp-block-paragraph"><strong>Source page of Default.aspx:</strong></p>



<pre class="wp-block-code"><code>&lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="False" DataSourceID="SqlDataSource1"&gt;

&lt;Columns&gt;
&lt;asp:HyperLinkField DataNavigateUrlFields="empid,empname,empadd" DataNavigateUrlFormatString="Default2.aspx?empid={0}&amp;empname={1}&amp;empadd={2}" Text= “sendData" /&gt;
&lt;asp:BoundField DataField ="empid" HeaderText="empid" SortExpression="empid" /&gt;
&lt;asp:BoundField DataField="empname" HeaderText="empname" SortExpression="empname" /&gt;
&lt;asp:BoundField DataField="empadd" HeaderText="empadd" SortExpression="empadd" /&gt;
&lt;/Columns&gt;
&lt;/asp:GridView&gt;

&lt;asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="&lt;%$ ConnectionStrings:abithaConnectionString %&gt;"
SelectCommand="SELECT * FROM &#91;emp]"&gt;&lt;/asp:SqlDataSource&gt;</code></pre>



<p class="wp-block-paragraph"><strong>Source page of Default2.aspx:</strong></p>



<pre class="wp-block-code"><code>EmployeeID:
&lt;asp:Label ID="lblEmpId" runat="server"&gt;&lt;/asp:Label&gt;

EmployeeName:
&lt;asp:Label ID="lblEmpName" runat="server"&gt;&lt;/asp:Label&gt;

EmployeeAddress:
&lt;asp:Label ID="lblEmpAddress" runat="server"&gt;&lt;/asp:Label&gt;</code></pre>



<p class="wp-block-paragraph"><strong>Code behind page of Default2.aspx:</strong></p>



<pre class="wp-block-code"><code>Protected void Page_Load( sender As Object, e As System.EventArgs)
{
String strid ;
String strname;
String stradd;

strid = Request.QueryString(“empid");
strname = Request.QueryString(“empname");
stradd = Request.QueryString(“empadd");

lblEmpId.Text = strid;
lblEmpName.Text = strname;
lblEmpAddress.Text = stradd;
}</code></pre>



<p class="wp-block-paragraph">This way we can send girdview row value to the next page using a hyperlink in asp.net.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="576" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/Gridview-in-asp.net_-1024x576.png" alt="Gridview in asp.net" class="wp-image-50" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/Gridview-in-asp.net_-1024x576.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2023/04/Gridview-in-asp.net_-300x169.png 300w, https://aspdotnethelp.com/wp-content/uploads/2023/04/Gridview-in-asp.net_-768x432.png 768w, https://aspdotnethelp.com/wp-content/uploads/2023/04/Gridview-in-asp.net_.png 1280w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Gridview in asp.net</figcaption></figure>
</div>


<h2 class="wp-block-heading">Implement delete functionality in Gridview in Asp.Net</h2>



<p class="wp-block-paragraph">This gridview example we will discuss how to implement the delete mechanism in grid view in asp.net.</p>



<p class="wp-block-paragraph">if you are showing some users and want to delete one user when someone clicks on the Delete link button inside the gridview.</p>



<p class="wp-block-paragraph">Below is the full code:</p>



<p class="wp-block-paragraph"><strong>Gridview code:</strong></p>



<pre class="wp-block-code"><code>&lt;div&gt;
&lt;asp:GridView ID="GridView1″ runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting"&gt;
&lt;Columns&gt;
&lt;asp:TemplateField HeaderText="User Name"&gt;
&lt;ItemTemplate&gt;
&lt;asp:HyperLink ID="hypUserName" runat="server" Text='&lt;%#Eval("UserName") %&gt;'&gt;&lt;/asp:HyperLink&gt;
&lt;/ItemTemplate&gt;
&lt;/asp:TemplateField&gt;
&lt;asp:TemplateField HeaderText="Email ID"&gt;
&lt;ItemTemplate&gt;
&lt;asp:Label ID="lblEmailID" runat="server" Text='&lt;%#Eval("EmailID") %&gt;'&gt;&lt;/asp:Label&gt;
&lt;/ItemTemplate&gt;
&lt;/asp:TemplateField&gt;
&lt;asp:TemplateField&gt;
&lt;ItemTemplate&gt;
&lt;asp:LinkButton ID="LinkButton1″ runat="server" CommandArgument='&lt;%#Eval("UserID") %&gt;'
CommandName="Delete" OnClientClick="return confirm(‘Are you sure you want to delete this user?');"&gt;Delete&lt;/asp:LinkButton&gt;
&lt;/ItemTemplate&gt;
&lt;/asp:TemplateField&gt;
&lt;/Columns&gt;
&lt;/asp:GridView&gt;
&lt;/div&gt;</code></pre>



<p class="wp-block-paragraph">Here we need to handle the OnRowDeleting and OnRowCommand command event.</p>



<p class="wp-block-paragraph">In the Delete button, we have set the CommandArgument to the UserID which is the ID through which we will write the code to delete the record.</p>



<p class="wp-block-paragraph">We have also set the CommandName as &#8220;Delete&#8221; which you can set anything but you need to check in the OnRowCOmmand event.</p>



<p class="wp-block-paragraph">It will also ask you a confirmation message before deleting the record.</p>



<p class="wp-block-paragraph"><strong>.CS Code:</strong></p>



<pre class="wp-block-code"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int UserID =Convert.ToInt32( e.CommandArgument);
if (e.CommandName == "Delete")
{
//Write your code to delete the user based on the above UserID
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Here no need to write any logic inside.
}

void BindGridView()
{
//Here is the code to Bind the gridview
}
}</code></pre>



<p class="wp-block-paragraph">Hope you will able to <strong>delete the record in the gridview in asp.net</strong>.</p>



<h2 class="wp-block-heading">How to display serial number automatically in GridView in asp.net?</h2>



<p class="wp-block-paragraph">Now, we will see how to display a <strong>serial number column in grid view in asp.net</strong>.</p>



<p class="wp-block-paragraph">The serial number will come as an index, it will start from 1 and will go on increasing 1 value for each row.</p>



<p class="wp-block-paragraph">Here the code to bind a gridview will be the same. The only thing will change is we need to another &lt;ItemTemplate&gt; like below:</p>



<pre class="wp-block-code"><code>&lt;asp:GridView ID="GridView1″ runat="server"&gt;
&lt;Columns&gt;
&lt;asp:TemplateField HeaderText="Serial Number"&gt;
&lt;ItemTemplate&gt;
&lt;%# Container.DataItemIndex + 1 %&gt;
&lt;/ItemTemplate&gt;
&lt;/asp:TemplateField&gt;
&lt;/Columns&gt;
&lt;/asp:GridView&gt;</code></pre>



<p class="wp-block-paragraph">If you will write this code then the serial number column will come in Gridview.</p>



<p class="wp-block-paragraph">You may like the following asp.net tutorials:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/how-to-use-jquery-modal-popup-in-asp-net/">How to use jquery modal popup in asp.net</a></li>



<li><a href="https://aspdotnethelp.com/disable-or-hide-minimize-maximize-and-close-buttons-in-c-net/">Disable or Hide minimize maximize and close buttons in C#.net</a></li>



<li><a href="https://aspdotnethelp.com/implement-log4net-in-asp-net-core-application/">How to Implement Log4Net in ASP.NET Core Application</a></li>



<li><a href="https://aspdotnethelp.com/why-is-net-so-popular-for-web-application-development/">Why is .NET so popular for web application development?</a></li>
</ul>



<p class="wp-block-paragraph">Hope this asp.net tutorial explains <strong>Gridview in asp.net</strong>. Also, we learn how to apply color in gridview rows based dynamically, how to <strong>add Eval for a hyperlink in gridview in asp.net</strong>? Also, we saw how to Bind gridview using datareader in asp.net.</p>



<p class="wp-block-paragraph">Then we discussed, how to <strong>export gridview data to excel sheet in Asp.net</strong> and how to export gridview to word in asp.net c#.net.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://aspdotnethelp.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Bijay Kumar is a renowned software engineer, accomplished author, and distinguished <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="nofollow noopener" target="_blank">Microsoft Most Valuable Professional</a> (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. <a href="https://aspdotnethelp.com/about/" rel="nofollow noopener">Read more&#8230;</a></p>
</div></div><div class="saboxplugin-web "><a href="https://aspdotnethelp.com" target="_self">aspdotnethelp.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Youtube" target="_self" href="https://www.youtube.com/c/enjoysharepoint?sub_confirmation=1" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-youtube" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 576 512"><path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to use jquery modal popup in asp.net</title>
		<link>https://aspdotnethelp.com/how-to-use-jquery-modal-popup-in-asp-net/</link>
		
		<dc:creator><![CDATA[Bijay]]></dc:creator>
		<pubDate>Mon, 24 Apr 2023 07:18:16 +0000</pubDate>
				<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[How to use jquery modal popup in asp.net]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=30</guid>

					<description><![CDATA[In this asp.net tutorial, we will discuss how to use jQuery modal popup in Asp.Net. Here, we will discuss how to display a successful message in a popup to the user. jQuery modal popup Asp.Net To use jQuery modal popup in Asp.Net we need to first add the jQuery reference on the page. And next, ... <a title="How to use jquery modal popup in asp.net" class="read-more" href="https://aspdotnethelp.com/how-to-use-jquery-modal-popup-in-asp-net/" aria-label="Read more about How to use jquery modal popup in asp.net">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this asp.net tutorial, we will discuss how to use <strong>jQuery modal popup in Asp.Net</strong>. Here, we will discuss how to display a successful message in a popup to the user.</p>



<h2 class="wp-block-heading">jQuery modal popup Asp.Net</h2>



<p class="wp-block-paragraph">To use <strong>jQuery modal popup in Asp.Net</strong> we need to first add the jQuery reference on the page.</p>



<p class="wp-block-paragraph">And next, you can create the dialog that will call the dialog box on a button click.</p>



<p class="wp-block-paragraph"><strong>Step 1: </strong>Add the <strong>jQuery </strong>reference on your page or you can take the below reference file.</p>



<pre class="wp-block-code"><code>&lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt;
&lt;script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"&gt;&lt;/script&gt;</code></pre>



<p class="wp-block-paragraph"><strong>Step 2:</strong> Now we will create a method where you will add your dialog with the below option.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="403" height="248" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/How-to-use-jquery-modal-popup-in-asp.net_.png" alt="How to use jquery modal popup in asp.net" class="wp-image-31" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/How-to-use-jquery-modal-popup-in-asp.net_.png 403w, https://aspdotnethelp.com/wp-content/uploads/2023/04/How-to-use-jquery-modal-popup-in-asp.net_-300x185.png 300w" sizes="auto, (max-width: 403px) 100vw, 403px" /><figcaption class="wp-element-caption">jquery modal popup in asp.net</figcaption></figure>
</div>


<pre class="wp-block-code"><code> function showmodalpopup() {
        $("#popupdiv").dialog({
            width: 500,
            height: 250,
            modal: true,
            hide: { effect: 'drop', duration: 250 },
            resizable: false,
            draggable: false,
            position: "center",
            closeOnEscape: true
        });
    };</code></pre>



<p class="wp-block-paragraph"><strong>Step 3:</strong> Next, I added a Div where you can call this dialog using <strong>Div ID</strong>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1024" height="62" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/modal-popup-using-jquery-in-asp.net-c.png" alt="modal popup using jquery in asp.net c#" class="wp-image-32" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/modal-popup-using-jquery-in-asp.net-c.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2023/04/modal-popup-using-jquery-in-asp.net-c-300x18.png 300w, https://aspdotnethelp.com/wp-content/uploads/2023/04/modal-popup-using-jquery-in-asp.net-c-768x47.png 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">modal popup using jquery in asp.net c#</figcaption></figure>
</div>


<pre class="wp-block-code"><code>&lt;div id="popupdiv" style="min-height: 0px;max-height: none;height: 230px;width: 500px!important;background: beige;text-align: center; display:none;" title="Success"&gt;
                     &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;
                           &lt;b class="ResultSuccess"&gt; 
                  &lt;%=GetLocalResourceObject("lbResult") %&gt;&lt;/b&gt;
                     &lt;/div&gt;</code></pre>



<p class="wp-block-paragraph"><strong>Step 4:</strong> Here I have added a few CSS files which you can take as your reference to apply some style in your Popup.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="374" height="289" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/jquery-modal-popup-example-asp.net_.png" alt="jquery modal popup example asp.net" class="wp-image-33" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/jquery-modal-popup-example-asp.net_.png 374w, https://aspdotnethelp.com/wp-content/uploads/2023/04/jquery-modal-popup-example-asp.net_-300x232.png 300w" sizes="auto, (max-width: 374px) 100vw, 374px" /><figcaption class="wp-element-caption">jquery modal popup example</figcaption></figure>
</div>


<pre class="wp-block-code"><code>.ui-dialog-titlebar {
    background-color: #80c342;
    padding: 5px;
    color: white;
    height: 20px;
    font-weight: bold;
    font-size: 13px;
    width: 490px;
}
    .ResultSuccess{
        font-weight: bold;
        font-size: 20px;
    }
   .ui-dialog-titlebar-close {
    visibility: hidden;
    }</code></pre>



<p class="wp-block-paragraph"><strong>Step 5:</strong> Now I am calling this <strong>showmodalpopup()</strong> from server-side after data successfully inserted in the table.</p>



<pre class="wp-block-code"><code> ScriptManager.RegisterStartupScript(this, GetType(), "Success", "showmodalpopup();", true);</code></pre>



<p class="wp-block-paragraph">In my submit button click, I called this method if my record inserted successfully. So once data inserted you will get a popup message like the below screenshot.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="504" height="257" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/jquery-modal-popup-asp.net-c.png" alt="jquery modal popup asp.net c#" class="wp-image-34" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/jquery-modal-popup-asp.net-c.png 504w, https://aspdotnethelp.com/wp-content/uploads/2023/04/jquery-modal-popup-asp.net-c-300x153.png 300w" sizes="auto, (max-width: 504px) 100vw, 504px" /><figcaption class="wp-element-caption">jquery modal popup asp.net</figcaption></figure>
</div>


<p class="wp-block-paragraph">Here you can also add a close button to close the dialog. So you need to add the below code.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="422" height="142" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/jquery-modal-popup-asp.net_.png" alt="jquery modal popup asp.net" class="wp-image-35" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/jquery-modal-popup-asp.net_.png 422w, https://aspdotnethelp.com/wp-content/uploads/2023/04/jquery-modal-popup-asp.net_-300x101.png 300w" sizes="auto, (max-width: 422px) 100vw, 422px" /></figure>
</div>


<pre class="wp-block-code"><code>buttons: {
                Close: function () {
                    $(this).dialog('close');
                }
            }</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="503" height="256" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/Asp.Net-jQuery-modal-popup.png" alt="Asp.Net jQuery modal popup" class="wp-image-36" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/Asp.Net-jQuery-modal-popup.png 503w, https://aspdotnethelp.com/wp-content/uploads/2023/04/Asp.Net-jQuery-modal-popup-300x153.png 300w" sizes="auto, (max-width: 503px) 100vw, 503px" /><figcaption class="wp-element-caption">jquery modal popup asp.net</figcaption></figure>
</div>


<p class="wp-block-paragraph">You may like the following tutorials:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/disable-or-hide-minimize-maximize-and-close-buttons-in-c-net/">Disable or Hide minimize maximize and close buttons in C#.net windows form</a></li>



<li><a href="https://aspdotnethelp.com/how-to-create-a-folder-if-not-exist-in-c-net/">How to create a folder if not exist in C#.Net</a></li>



<li><a href="https://aspdotnethelp.com/why-is-net-so-popular-for-web-application-development/">Why is .NET so popular for web application development?</a></li>



<li></li>
</ul>



<p class="wp-block-paragraph">In this tutorial, we discussed how to use <strong>jQuery modal popup in Asp.Net</strong>.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://aspdotnethelp.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Bijay Kumar is a renowned software engineer, accomplished author, and distinguished <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="nofollow noopener" target="_blank">Microsoft Most Valuable Professional</a> (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. <a href="https://aspdotnethelp.com/about/" rel="nofollow noopener">Read more&#8230;</a></p>
</div></div><div class="saboxplugin-web "><a href="https://aspdotnethelp.com" target="_self">aspdotnethelp.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Youtube" target="_self" href="https://www.youtube.com/c/enjoysharepoint?sub_confirmation=1" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-youtube" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 576 512"><path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Why is .NET so popular for web application development?</title>
		<link>https://aspdotnethelp.com/why-is-net-so-popular-for-web-application-development/</link>
		
		<dc:creator><![CDATA[Bijay]]></dc:creator>
		<pubDate>Mon, 24 Apr 2023 06:50:46 +0000</pubDate>
				<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Why is .NET so popular for web application development]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=15</guid>

					<description><![CDATA[Application development becomes crucial for online business success in today’s world. It allows businesses to present their products, services, and offers effectively to impress customers. The selection of .NET technologies can be a beneficial decision for application development. In this blog, you can get introduced to .NET development and its benefits.&#160; .NET &#8211; An Overview&#160; ... <a title="Why is .NET so popular for web application development?" class="read-more" href="https://aspdotnethelp.com/why-is-net-so-popular-for-web-application-development/" aria-label="Read more about Why is .NET so popular for web application development?">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Application development becomes crucial for online business success in today’s world. It allows businesses to present their products, services, and offers effectively to impress customers. The selection of .NET technologies can be a beneficial decision for application development. In this blog, you can get introduced to .NET development and its benefits.&nbsp;</p>



<h2 class="wp-block-heading">.NET &#8211; An Overview&nbsp;</h2>



<p class="wp-block-paragraph">.NET is a web service offered by Microsoft for the development of software and running it perfectly. The framework works on the basis of two main aspects such as &#8211;&nbsp;</p>



<ul class="wp-block-list">
<li>CLR (Common Language Runtime)</li>



<li>FCL (Framework Class Library)</li>
</ul>



<p class="wp-block-paragraph">CLR works by managing the programs that are already running and handle all related operations. FCL helps by providing different types of reusable codes for applications and keep it running smoothly. .NET development is a great option for multiple industries.&nbsp;</p>



<ul class="wp-block-list">
<li>Gaming&nbsp;</li>



<li>Government&nbsp;</li>



<li>Manufacturing&nbsp;</li>



<li>Internet of Things&nbsp;</li>



<li>Accounting &amp; Finance&nbsp;</li>
</ul>



<p class="wp-block-paragraph">It is used in several other business industries and sectors. Using such a framework will help you in getting compatibility with all Microsoft platforms or servers with ease.&nbsp;</p>



<h2 class="wp-block-heading">Benefits Of Choosing .NET</h2>



<p class="wp-block-paragraph">.NET facilitates a business application development process in several ways such as &#8211; reducing development time and effort, flexibility, and so on. Get explained information here.&nbsp;</p>



<h3 class="wp-block-heading">Code Reuse And Less Coding</h3>



<p class="wp-block-paragraph">While working on this particular framework, the professionals do not need to generate new codes again and again. The system works by eliminating unnecessary coding requirements.</p>



<p class="wp-block-paragraph">Another major factor is the benefit of reusing the code. There are many components and codes available that can be re-used to form a new software. It benefits by saving time and money in business application development.&nbsp;</p>



<h3 class="wp-block-heading">Adaptability&nbsp;</h3>



<p class="wp-block-paragraph">.NET provides complete flexibility while choosing a language for software development. It supports multiple languages like &#8211;&nbsp;</p>



<ul class="wp-block-list">
<li>C#</li>



<li>F#</li>



<li>C++</li>



<li>COBOL</li>



<li>Visual Basics&nbsp;</li>
</ul>



<p class="wp-block-paragraph">There are numerous other languages that can be used with .NET. It is managed and completed by the CLR for keeping all framework related aspects perfect such as &#8211; memory and security.</p>



<p class="wp-block-paragraph">The selection of development language is based on the framework’s requirements that you want to create for business applications.&nbsp;</p>



<h3 class="wp-block-heading">Compatibility&nbsp;</h3>



<p class="wp-block-paragraph">Using this particular framework provides compatibility to run developed software on multiple platforms. Previously, .NET was launched only for Windows.</p>



<p class="wp-block-paragraph">Later, with its demands and other reasons, Microsoft expanded its compatibility, and now it can be used for building applications for multiple platforms. Some are listed below &#8211;&nbsp;</p>



<ul class="wp-block-list">
<li>iOS</li>



<li>Linux&nbsp;</li>



<li>macOS</li>



<li>Apache</li>



<li>Android&nbsp;</li>



<li>Windows&nbsp;</li>
</ul>



<p class="wp-block-paragraph">If you want to develop an application with the .NET framework, then you should collaborate with professionals who can use multiple operating systems. It offers flexibility in accessing project from other OS as well when it is necessary.&nbsp;</p>



<h3 class="wp-block-heading">Community&nbsp;</h3>



<p class="wp-block-paragraph">It becomes one of the most popular frameworks for application development related tasks. It is known for the fully-featured technologies, libraries, and some other tools.</p>



<p class="wp-block-paragraph">All these things make the task of application development easier than before. As a result, today all types of business organizations small, medium, and large are choosing it.&nbsp;</p>



<p class="wp-block-paragraph">With lots of users and experts, there a large .NET community exists on the internet.</p>



<p class="wp-block-paragraph">It means, whenever anyone faces confusion or issues while working with .NET, then they have numerous resources to get help easily, discussion boards, online forums, knowledge sharing websites, and much more.&nbsp;</p>



<h3 class="wp-block-heading">Secure &amp; Reliable&nbsp;</h3>



<p class="wp-block-paragraph">.NET is available with a high-grade security system. It is fully efficient to protect your products and other business-related stuff with ease. Its security system works mainly on two major features, code access security and role-based security.</p>



<p class="wp-block-paragraph">Code access security feature assists in preventing the malicious code or get corrupted by untrusted codes. It works by analyzing the codes and their background before providing any permission or accessibility.&nbsp;</p>



<h3 class="wp-block-heading">Dependable&nbsp;</h3>



<p class="wp-block-paragraph">In the business industry, companies need to update their platforms or applications with the latest features and technologies to impress visitors. It helps them in serving potential customers perfectly.</p>



<p class="wp-block-paragraph">In such a case, the companies want to pick a source that is fully dependable and provide services accordingly. .NET is the fully dependable source and for fulfilling the requirements, it provides updates and various technological advancements timely.&nbsp;</p>



<p class="wp-block-paragraph">Currently, the .NET framework 4.8 version is the latest one and it is also highly recommended. In the case of .NET core, 3.1 and 2.1 versions are available with lifetime support and .NET Core 5.0 version is under-preview.</p>



<p class="wp-block-paragraph">This latest version is in the development stage for now and not accessible for production purposes.&nbsp;</p>



<h3 class="wp-block-heading">No Service Charges&nbsp;</h3>



<p class="wp-block-paragraph">.NET offers services as a free-to-use framework where no one needs to spend money. Choosing this particular technology does not only save money here but also during the development process by saving time.&nbsp;</p>



<p class="wp-block-paragraph">These are some major benefits of using .NET instead of other sources. It helps in improving stats related to the business ROI by reducing overall costing and increasing profit-earning rates.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="576" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/Why-is-.NET-so-popular-for-web-application-development-1024x576.png" alt="Why is .NET so popular for web application development" class="wp-image-16" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/Why-is-.NET-so-popular-for-web-application-development-1024x576.png 1024w, https://aspdotnethelp.com/wp-content/uploads/2023/04/Why-is-.NET-so-popular-for-web-application-development-300x169.png 300w, https://aspdotnethelp.com/wp-content/uploads/2023/04/Why-is-.NET-so-popular-for-web-application-development-768x432.png 768w, https://aspdotnethelp.com/wp-content/uploads/2023/04/Why-is-.NET-so-popular-for-web-application-development.png 1280w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Why is .NET so popular for web application development</figcaption></figure>
</div>


<p class="wp-block-paragraph">You may like the following tutorials:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/implement-log4net-in-asp-net-core-application/">How to Implement Log4Net in ASP.NET Core Application</a></li>



<li><a href="https://aspdotnethelp.com/gridview-in-asp-net/">Gridview in asp.net</a></li>
</ul>



<p class="wp-block-paragraph"><strong>About the author:</strong> Rio is a digital entrepreneur who has a vision of helping businesses by increasing their online presence in terms of Websites, Applications, and SEO. He is the Founder &amp; CEO of <a href="https://www.webomaze.com.au/" target="_blank" rel="noreferrer noopener">Webomaze Pty Ltd</a>, a One-Stop Digital Agency based in Melbourne</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://aspdotnethelp.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Bijay Kumar is a renowned software engineer, accomplished author, and distinguished <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="nofollow noopener" target="_blank">Microsoft Most Valuable Professional</a> (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. <a href="https://aspdotnethelp.com/about/" rel="nofollow noopener">Read more&#8230;</a></p>
</div></div><div class="saboxplugin-web "><a href="https://aspdotnethelp.com" target="_self">aspdotnethelp.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Youtube" target="_self" href="https://www.youtube.com/c/enjoysharepoint?sub_confirmation=1" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-youtube" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 576 512"><path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Implement Log4Net in ASP.NET Core Application</title>
		<link>https://aspdotnethelp.com/implement-log4net-in-asp-net-core-application/</link>
		
		<dc:creator><![CDATA[Bijay]]></dc:creator>
		<pubDate>Mon, 24 Apr 2023 06:43:26 +0000</pubDate>
				<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Implement Log4Net in ASP.NET Core Application]]></category>
		<guid isPermaLink="false">https://aspdotnethelp.com/?p=11</guid>

					<description><![CDATA[In this asp.net tutorial, we will discuss how to implement Log4Net in ASP.NET Core Application. Step by step I will explain how to use Log4Net in the Asp.Net core application. ASP.NET core is an open-source, cross-platform, and modular framework for building modern and high-performance applications. .NET Core SDK is a lightweight SDK that includes a ... <a title="How to Implement Log4Net in ASP.NET Core Application" class="read-more" href="https://aspdotnethelp.com/implement-log4net-in-asp-net-core-application/" aria-label="Read more about How to Implement Log4Net in ASP.NET Core Application">Read more &#62;&#62;</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this asp.net tutorial, we will discuss how to <strong>implement Log4Net in ASP.NET Core Application</strong>. Step by step I will explain how to use Log4Net in the Asp.Net core application.</p>



<p class="wp-block-paragraph">ASP.NET core is an open-source, cross-platform, and modular framework for building modern and high-performance applications. <strong>.NET Core SDK</strong> is a lightweight SDK that includes a minimum set of features required to build an application. We can install other features from NuGet packages.</p>



<p class="wp-block-paragraph">Also check, Steps to archive log files using NLog with ASP.NET Core.</p>



<p class="wp-block-paragraph">.NET Core provides programming patterns such as dependency injection, logging, and app configuration. For logging, it includes Microsoft.Extension.Logging package. It will store the logs for display. In this blog, we will learn about Log4Net logging in Asp.net Core.</p>



<h2 class="wp-block-heading">What is Logging?</h2>



<p class="wp-block-paragraph">Logging is a modern and one of the in-built <a aria-label=" (opens in a new tab)" href="https://www.ifourtechnolab.com/blog/new-features-of-asp-net-core-for-modern-web-and-cloud-applications-development" target="_blank" rel="noreferrer noopener" class="rank-math-link">features in ASP.NET Core</a> application for detecting issues. ASP.NET Core supports a wide variety of logging providers. You can plug in your own frameworks like Log4Net, Elmah, and NLog. Microsoft.Extension.Logging namespace provides supports for simple logging with just a few lines of code.</p>



<p class="wp-block-paragraph">For ASP.NET Core 1.x, you need to include the dependencies explicitly for your project and these dependencies are built-in for ASP.NET Core 2.x.</p>



<p class="wp-block-paragraph">Built-in classes and interface in Microsoft.Extension.Logging namespace as follow:<strong></strong></p>



<ul class="wp-block-list">
<li>ILogger</li>



<li>ILoggerFactory</li>



<li>LoggerFactory</li>



<li>ILoggerProvider</li>
</ul>



<p class="wp-block-paragraph"><strong>ILoggerFactory:</strong></p>



<p class="wp-block-paragraph">ILoggerFactory interface creates an ILogger instance and also adds an ILoggerProvider instance. In Asp.net Core includes a built-in LoggerFactory class that implements the ILoggerFactory interface.</p>



<pre class="wp-block-code"><code>using Microsoft.Extensions.Logging;

namespace Log4NetExample.Log
{
    interface ILoggerFactory : IDisposable
    {
        ILogger CreateLog(string name);
        void LogProvider(ILoggerProvider provider);
    }
}
</code></pre>



<p class="wp-block-paragraph">We can use this interface for creating ILogger instance and add ILoggerProvider instance.</p>



<p class="wp-block-paragraph"><strong>ILoggerProvider:</strong></p>



<p class="wp-block-paragraph">ILoggerProvider creates a suitable ILogger instance and manage it.<strong> </strong>We can create our own custom logging provider by implementing ILoggerProvider interface.</p>



<pre class="wp-block-code"><code>using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Log4NetExample.Log
{
    interface ILoggerProvider : IDisposable
    {
        ILogger CreateLog(string name);
    }
}
</code></pre>



<p class="wp-block-paragraph"><strong>ILogger:</strong></p>



<p class="wp-block-paragraph">For logging, ILogger interface includes the methods to store it. There are many extension methods for logging which make it easy.</p>



<pre class="wp-block-code"><code>using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Log4NetExample.Log
{
    interface ILogger
    {
        void Log&lt;TState&gt;(LogLevel logLvl, EventId evntId, TState state, Exception         exception, Func&lt;TState, Exception, string&gt; formatter);
        bool IsEnabled(LogLevel logLvl);
        IDisposable BeginScope&lt;TState&gt;(TState state);
    }
}
</code></pre>



<p class="wp-block-paragraph">In ILogger, there are 3 methods.</p>



<ul class="wp-block-list">
<li>BeginScope: &#8211; It initiates the logical operation scope.</li>



<li>IsEnabled: &#8211; It checks if the log level is enabled or not.</li>
</ul>



<p class="wp-block-paragraph"><strong>Logging Providers: &#8211;</strong></p>



<p class="wp-block-paragraph">For store and display logs logging providers use a certain medium such as console level, debug level, and event log etc. Microsoft provides an extension or namespace for various logging providers from NuGet package.</p>



<p class="wp-block-paragraph">Microsoft also team up with the third parties logging framework such as NLog, Serilog, Log4Net, elmah and others.</p>



<h2 class="wp-block-heading">Basic Configuration Example</h2>



<p class="wp-block-paragraph">Let’s take example using Log4Net.<strong></strong></p>



<p class="wp-block-paragraph"><strong>Step-1: Install Log4Net</strong></p>



<p class="wp-block-paragraph">PM&gt; Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore -Version 2.1.0</p>



<p class="wp-block-paragraph"><strong>Step-2: Update Start up file</strong></p>



<p class="wp-block-paragraph">Register Log4Net middleware into the startup file configure section.</p>



<pre class="wp-block-code"><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
     {
           logger.AddLog4Net();
      }
</code></pre>



<p class="wp-block-paragraph"><strong>Step 3: Add Log.config File</strong></p>



<p class="wp-block-paragraph">Add our own custom .config file as illustrates below.</p>



<p class="wp-block-paragraph"><strong>Rolling File Appender:</strong></p>



<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; 
&lt;log4net&gt;
  &lt;appender name="RollingLogFileAppender"    type="log4net.Appender.RollingFileAppender"&gt;
    &lt;lockingmodel type="log4net.Appender.FileAppender+MinimalLock"&gt;
      &lt;file value="logs/"&gt;
        &lt;datepattern value="dd-MM-yyyy hh.'txt'"&gt;
          &lt;staticlogfilename value="false"&gt;
            &lt;appendtofile value="true"&gt;
              &lt;rollingstyle value="Composite"&gt;
                &lt;maxsizerollbackups value="2"&gt;
                  &lt;maximumfilesize value="1GB"&gt;
                    &lt;layout type="log4net.Layout.PatternLayout"&gt;
                      &lt;conversionpattern value="%level  %message  %date"&gt;
                      &lt;/conversionpattern&gt;
                    &lt;/layout&gt;
                  &lt;/maximumfilesize&gt;
                &lt;/maxsizerollbackups&gt;
              &lt;/rollingstyle&gt;
            &lt;/appendtofile&gt;
          &lt;/staticlogfilename&gt;
        &lt;/datepattern&gt;
      &lt;/file&gt;
    &lt;/lockingmodel&gt;
  &lt;/appender&gt;
  &lt;root&gt;
    &lt;level value="ALL"&gt;
      &lt;appender-ref ref="RollingLogFileAppender"&gt;
      &lt;/appender-ref&gt;
    &lt;/level&gt;
  &lt;/root&gt;
&lt;/log4net&gt;
</code></pre>



<p class="wp-block-paragraph"><strong>Debug Level:</strong></p>



<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;log4net&gt;
  &lt;appender name="DebugAppender" type="log4net.Appender.DebugAppender" &gt;
    &lt;layout type="log4net.Layout.PatternLayout"&gt;
      &lt;conversionPattern value="%date &#91;%thread] %-5level %logger -%message%newline" /&gt;
    &lt;/layout&gt;
  &lt;/appender&gt;
  &lt;root&gt;
    &lt;level value="ALL"/&gt;
    &lt;appender-ref ref="DebugAppender" /&gt;
  &lt;/root&gt;
&lt;/log4net&gt;
</code></pre>



<p class="wp-block-paragraph">We can define log level and Appender-ref into root element. Root element is necessary in the config file.</p>



<p class="wp-block-paragraph">We have taken here the RollingLogAppender but there are also other types such as <strong>FileAppender</strong>, <strong>ConsoleAppender</strong>. This is the basic configuration in the Asp.net Core application. We can add custom configuration using Log4Net Providers as illustrates below.</p>



<h2 class="wp-block-heading">Custom Configuration Using Log4NetProviders</h2>



<p class="wp-block-paragraph"><strong>Step 1: appsettings file</strong> Install the package in your Asp.net Core application and add Log4Net in the appsettings.json file.</p>



<pre class="wp-block-code"><code>{
  "Log4NetExample": {
    "Name": "Test",
    "LoggerRepository": "Real",
    "OverrideCriticalLevelWith": "Fatal",
    "Watch": false,
    "UseWebOrAppConfig": false,
    "PropertyOverrides": &#91;
      {
        "XPath": "/log4net/appender&#91;@name='RollingFile']/file",
        "Attributes": {
          "Value": "overridedFileName.log"
        }
      },
      {
        "XPath": "/log4net/appender&#91;@name='RollingFile']/maximumFileSize",
        "Attributes": {
          "Value": "200MB"
        }
      },
      {
        "XPath": "/log4net/appender&#91;@name='RollingFile']/file"
      }
    ]
  }
}
</code></pre>



<p class="wp-block-paragraph"><strong>Step 2: Place appsetting in program.cs file</strong></p>



<p class="wp-block-paragraph">Add appsetting.json file in configuration builder method as below. For that, we need to install the Microsoft.Extension.Configuration.Json package.</p>



<pre class="wp-block-code"><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Log4Net
{
    public class Program
    {
        public static void Main(string&#91;] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string&#91;] args)
        {
            var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

            return WebHost.CreateDefaultBuilder(args)
                .UseConfiguration(config)
                .UseStartup&lt;Startup&gt;();
        }            
    }
}
</code></pre>



<p class="wp-block-paragraph"><strong>Step 3: Add log4Net in startup file</strong></p>



<p class="wp-block-paragraph">Add Log4Net to startup file and configure it.</p>



<pre class="wp-block-code"><code>var loggingOptions = this.Configuration.GetSection("Log4NetCore")
                                               .Get&lt;Log4NetProviderOptions&gt;();
            logger. AddLog4Net ();
</code></pre>



<p class="wp-block-paragraph">Complete Startup file as shown below:</p>



<pre class="wp-block-code"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Log4Net
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure&lt;CookiePolicyOptions&gt;(options =&gt;
            {
                options.CheckConsentNeeded = context =&gt; true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
        {
            var loggingOptions = this.Configuration.GetSection("Log4NetExample")
                                               .Get&lt;Log4NetProviderOptions&gt;();
            logger.AddLog4Net();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =&gt;
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
</code></pre>



<p class="wp-block-paragraph">You have seen the Log4NetProviderOptions in Configuration.GetSection method. There are some properties that we have described below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="850" height="500" src="https://aspdotnethelp.com/wp-content/uploads/2023/04/How-to-Implement-Log4Net-in-ASP-NET-Core-Application.jpg" alt="Implement Log4Net in ASP.NET Core Application" class="wp-image-13" srcset="https://aspdotnethelp.com/wp-content/uploads/2023/04/How-to-Implement-Log4Net-in-ASP-NET-Core-Application.jpg 850w, https://aspdotnethelp.com/wp-content/uploads/2023/04/How-to-Implement-Log4Net-in-ASP-NET-Core-Application-300x176.jpg 300w, https://aspdotnethelp.com/wp-content/uploads/2023/04/How-to-Implement-Log4Net-in-ASP-NET-Core-Application-768x452.jpg 768w" sizes="auto, (max-width: 850px) 100vw, 850px" /><figcaption class="wp-element-caption">Implement Log4Net in ASP.NET Core Application</figcaption></figure>
</div>


<h2 class="wp-block-heading">Properties of Log4NetProviderOptions</h2>



<ul class="wp-block-list">
<li><strong>UseWebOrAppConfig</strong> &#8211; Boolean value that indicate the Log4Net Configuration Section is in the app.config file or in web.config file and its default value is false.&nbsp;&nbsp; </li>



<li><strong>ExternalConfigurationSetup</strong> – This setup indicates that the Log4Net library has been configured outside the extension using XmlConfigurator and its default value is false.</li>



<li><strong>Watch </strong>– This property indicates that the Log4Net.config file will be opened in watch mode and likewise its default value is false.</li>



<li><strong>PropertyOverrides</strong> – During Log4Net initialization it allows to replacement of defined value.</li>
</ul>



<p class="wp-block-paragraph">You may like the following tutorials:</p>



<ul class="wp-block-list">
<li><a href="https://aspdotnethelp.com/disable-or-hide-minimize-maximize-and-close-buttons-in-c-net/">Disable or Hide minimize maximize and close buttons in C#.net windows form</a></li>



<li><a href="https://aspdotnethelp.com/how-to-create-a-folder-if-not-exist-in-c-net/">How to create a folder if not exist in C#.Net</a></li>



<li><a href="https://aspdotnethelp.com/why-is-net-so-popular-for-web-application-development/">Why is .NET so popular for web application development?</a></li>



<li><a href="https://aspdotnethelp.com/how-to-use-jquery-modal-popup-in-asp-net/">How to use jquery modal popup in asp.net</a></li>
</ul>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">Logging API works with other logging providers. Logging providers display to store the log in console level, debug level, an event log, and other types of the medium. All logging providers reside in Microsoft.Extension.Logging namespace. Such as Logging.Console, Logging.Debug, Logging.EventLog, and others. In this blog, we have seen the basic configuration and custom configuration. Also, we have created log.config using the rolling appender and debug level.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://aspdotnethelp.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Bijay Kumar is a renowned software engineer, accomplished author, and distinguished <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="nofollow noopener" target="_blank">Microsoft Most Valuable Professional</a> (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. <a href="https://aspdotnethelp.com/about/" rel="nofollow noopener">Read more&#8230;</a></p>
</div></div><div class="saboxplugin-web "><a href="https://aspdotnethelp.com" target="_self">aspdotnethelp.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Youtube" target="_self" href="https://www.youtube.com/c/enjoysharepoint?sub_confirmation=1" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-youtube" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 576 512"><path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: aspdotnethelp.com @ 2026-09-20 06:15:46 by W3 Total Cache
-->