The best resource for .NET Developers. This blog guides about .NET (C#.NET, ASP.NET, ASP.NET MVC, SQL Server, ADO.NET), AngularJS, JSON, HTML, JavaScript, jQuery, CSS, Bootstrap, DotNetNuke, and .NET interview questions. This blog teaches everything about the .NET. Here you can find bunch of tutorials, Tips and tricks, code samples and examples.
Monday, 25 August 2014
SQL Server - Remove or Truncate or Subtract hours, minutes, seconds and milliseconds from sql datetime
Tuesday, 22 July 2014
SQL Server 2005/2008 - Working with datetime Data Type (DATENAME, DATEPART, DATEDIFF, DATEADD, ISDATE, CONVERT)
When we are working with any programming language we need to work on the datetime. Every geographic location has different need of the date formats. Developer needs to take care of the datetime formats. The following statements are the most useful and common DateTime functions which are useful in SQL Server 2005/2008. I am giving with some example sql queries with the outputs.
Working With SQL datetime Data Type
SELECT
GETDATE(), -- 2014-07-23 00:48:46.663
CURRENT_TIMESTAMP, -- 2014-07-23 00:48:46.663
GETUTCDATE(), -- 2014-07-22 19:18:46.663
DAY(GETDATE()) , -- 23
MONTH(GETDATE()) , -- 7
YEAR(GETDATE()) -- 2014
--DATENAME
SELECT
DATENAME(year, getdate()) -- 2014
,DATENAME(month, getdate()) -- July
,DATENAME(day, getdate()) -- 23
,DATENAME(dayofyear, getdate()) -- 204
,DATENAME(weekday, getdate()) -- Wednesday
,DATENAME(hour, getdate()) -- 0
,DATENAME(minute, getdate()) -- 53
,DATENAME(second, getdate()) -- 57
,DATENAME(millisecond, getdate()) -- 140
--DATEPART
SELECT
DATEPART(year, getdate()) -- 2014
,DATEPART(month, getdate()) -- 7
,DATEPART(day, getdate()) -- 23
,DATEPART(dayofyear, getdate()) -- 204
,DATEPART(weekday, getdate()) -- 4
,DATEPART(hour, getdate()) -- 0
,DATEPART(minute, getdate()) -- 53
,DATEPART(second, getdate()) -- 57
,DATEPART(millisecond, getdate()) -- 140
-- DATEDIFF
DECLARE
@startdate DATETIME
SET
@startdate = '2014-08-15
10:10:10.100'
DECLARE
@enddate DATETIME
SET
@enddate = '2014-08-20
20:20:20.200';
SELECT
DATEDIFF(year,
@startdate, @enddate)
, -- 0
DATEDIFF(month,
@startdate, @enddate)
, -- 0
DATEDIFF(hour, @startdate, @enddate) , -- 130
DATEDIFF(minute, @startdate, @enddate) , -- 7810
DATEDIFF(second, @startdate, @enddate) , --468610
DATEDIFF(millisecond, @startdate, @enddate) --468610100
-- DATEADD
DECLARE
@datetime datetime
SET
@datetime = '2014-01-01
01:01:01.110'
SELECT DATEADD(quarter,4,@datetime) -- 2015-01-01
01:01:01.110
SELECT DATEADD(month,13,@datetime) -- 2015-02-01 01:01:01.110
SELECT DATEADD(dayofyear,365,@datetime) -- 2015-01-01
01:01:01.110
SELECT DATEADD(day,365,@datetime) -- 2015-01-01 01:01:01.110
SELECT DATEADD(week,5,@datetime)-- 2014-02-05 01:01:01.110
SELECT DATEADD(weekday,31,@datetime) -- 2014-02-01
01:01:01.110
SELECT DATEADD(hour,23,@datetime) -- 2014-01-02
00:01:01.110
SELECT DATEADD(minute,59,@datetime) -- 2014-01-01
02:00:01.110
SELECT DATEADD(second,59,@datetime) -- 2014-01-01
01:02:00.110
SELECT DATEADD(millisecond,1,@datetime) -- 2014-01-01
01:01:01.110
--ISDATE
SELECT ISDATE('2014-12-30 01:01:01.001') -- 1
SELECT ISDATE('12-30-2014 01:01:01.001') -- 1
SELECT ISDATE('30-12-2014 01:01:01.001') -- 0
SELECT ISDATE('2014/12/30 01:01:01.001') -- 1
SELECT ISDATE('12/30/2014 01:01:01.001') -- 1
SELECT ISDATE('30/12/2014 01:01:01.001') -- 0
SELECT ISDATE(NULL) -- 0
SELECT ISDATE('') -- 0
SELECT ISDATE('SRINU') -- 0
-- CONVERT
DECLARE
@INPUTDATE DATETIME
SET
@INPUTDATE='2014-12-30
12:59:59'
SELECT CONVERT(VARCHAR(10), @INPUTDATE, 105) , '[dd-mm-yyyy]'
--
30-12-2014 [dd-mm-yyyy]
SELECT CONVERT(VARCHAR(10), @INPUTDATE, 110), '[mm-dd-yyyy]'
--
12-30-2014 [mm-dd-yyyy]
SELECT CONVERT(VARCHAR(10), @INPUTDATE , 120), '[yyyy-mm-dd]'
--
2014-12-30 [YYYY-MM-DD]
SELECT CONVERT(VARCHAR(10), @INPUTDATE, 103) ,' [dd/mm/yyyy]'
--
30/12/2014 [dd/mm/yyyy]
SELECT CONVERT(VARCHAR(10), @INPUTDATE, 101) ,'[mm/dd/yyyy]'
--
12/30/2014 [mm/dd/yyyy]
SELECT CONVERT(VARCHAR(10), @INPUTDATE, 111) ,'[yyyy/mm/dd]'
--
2014/12/30 [yyyy/mm/dd]
SELECT CONVERT(VARCHAR(12),@INPUTDATE, 102),'[yyyy.mm.dd]'
--
2014.12.30 [yyyy.mm.dd]
SELECT CONVERT(VARCHAR(12),@INPUTDATE, 104),'[dd.mm.yyyy]'
--
30.12.2014 [dd.mm.yyyy]
SELECT CONVERT(VARCHAR(12), @INPUTDATE, 107) ,'[mmm dd, yyyy]'
-- Dec 30,
2014 [mmm dd, yyyy]
SELECT CONVERT(VARCHAR(8), @INPUTDATE, 108) , '[HH:mm:ss]'
-- 12:59:59 [HH:mm:ss]
SELECT CONVERT(VARCHAR(12), @INPUTDATE, 114) 'HH:mm:ss:fff'
-- 12:59:59:000
[HH:mm:ss:fff]Thursday, 5 June 2014
C#.NET - How to assign null value to DateTime / Working with nullable DateTime / Assigning null value to DateTime / Setting DateTime to null
DateTime is a value type. If you try to assign null value to DateTime it will throw compile time error "Cannot convert null to System.DateTime because it is a non-nullable value type."
DateTime has the default value that is equal to the DateTime.MinValue. You can assign this to DateTime.
In C# 2.0, Microsoft introduced "Nullable Types" using the nullable operator (?). It will allow you to assign the null values to the value types. So we can assgin a null value to the DateTime by making it as Nullable Type.
Sunday, 25 May 2014
CSS - Style Sheet Media Types
There are different media types defined in the CSS-2 specifications.
Media Type | Description |
---|---|
all | Used for all media type devices |
aural | Used for speech and sound synthesizers |
braille | Used for braille tactile feedback devices |
embossed | Used for paged braille printers |
Used for printers | |
projection | Used for projected presentations, like slides |
screen | Used for computer screens |
tty | Used for media using a fixed-pitch character grid, like teletypes and terminals |
tv | Used for television-type devices |
We can define media types in different ways
1. External Style Sheet associated with single media type.
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
<link rel="stylesheet" type="text/css" href="print.css" media="print,handheld" />
<style type="text/css" media="print, handheld"> @import "print.css"; </style>
<style type="text/css" media="print"> h1 { font-size:16px; color:Green; } </style>
<style type="text/css" media="print,handheld"> h1 { font-size:16px; color:Green; } </style>
<style type="text/css"> @media print { h1 { font-size:16px; color:Black; } } @media screen { h1 { font-size:18px; color:Green; } } @media screen, print { h1 { font-size:1.5; color:Blue; } } </style>
Tuesday, 29 April 2014
C#.NET - How to delete XML Node from XML file step by step
We have an XmlDocument class in System.Xml namespace. With the help of XmlDocument class data members and member functions we can delete node from the Xml Document.
To delete an Xml node from the Xml Document go through the following step by step procedure.
1. First create an Xml File with some sample employees as follows.
Xml File
<?xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee>
<ID>SE01</ID>
<Name>Srinubabu</Name>
<Address>Hyderabad</Address>
</Employee>
<Employee>
<ID>SE02</ID>
<Name>Gajendra</Name>
<Address>Pune</Address>
</Employee>
<Employee>
<ID>SE03</ID>
<Name>Prafulla</Name>
<Address>Gurgon</Address>
</Employee>
<Employee>
<ID>SE02</ID>
<Name>Satheesh</Name>
<Address>Chennai</Address>
</Employee>
</Employees>
Note: Please go through the code and comments in the following code you will easily understand the process of deleting the node from Xml Document.
Delete-node-from-xml.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Delete-node-from-xml.aspx.cs"
Inherits="Delete_node_from_xml" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
Employee ID:
<asp:TextBox ID="txtEmployeeID" runat="server" />
<asp:Button ID="btnDeleteEmployee" Text="Delete Employee" runat="server" OnClick="btnDeleteEmployee_Click" /><br />
<br />
<asp:Label ID="lblStatus" ForeColor="Red" Font-Size="13" Text="" runat="server" />
</form>
</body>
</html>
Delete-node-from-xml.aspx.cs
using System;
using System.Xml;
public partial class Delete_node_from_xml : System.Web.UI.Page
{
protected void btnDeleteEmployee_Click(object sender, EventArgs e)
{
var filePath = @"C:\Users\manduvalkuritis\Desktop\Srinubabu\XMLManipulations\Employees.xml";
DeleteEmployeeByEmployeeID(filePath, txtEmployeeID.Text.Trim());
}
private void DeleteEmployeeByEmployeeID(string xmlFilePath, string employeeID)
{
// Initialize a new instance of the XmlDocument.
var xdoc = new XmlDocument();
xdoc.Load(xmlFilePath);
// Get the root XmlElement of the document.
XmlNode rootNode = xdoc.DocumentElement;
// Select a list of Xml nodes matching with employee ID
XmlNodeList nodes = rootNode.SelectNodes("Employee");
bool isEmployeeFound = false;
// Go throug each and every element
foreach (XmlNode item in nodes)
{
// Find the Xml node with the given employee ID
if (item.SelectSingleNode("ID").InnerText == employeeID)
{
isEmployeeFound = true;
// Delete the employee node from the xml document.;
rootNode.RemoveChild(item);
}
}
if (isEmployeeFound)
{
lblStatus.Text = "Emloyee Deleted Successfully.";
}
else
{
lblStatus.Text = "Emloyee doesn't found please enter correct employee id.";
}
// Finally save the xml file.
xdoc.Save(xmlFilePath);
}
}
Xml File
<?xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee>
<ID>SE02</ID>
<Name>Gajendra</Name>
<Address>Pune</Address>
</Employee>
<Employee>
<ID>SE03</ID>
<Name>Prafulla</Name>
<Address>Gurgon</Address>
</Employee>
<Employee>
<ID>SE02</ID>
<Name>Satheesh</Name>
<Address>Chennai</Address>
</Employee>
</Employees>
Thank you....
Monday, 7 April 2014
C#.NET - Programming code to generate pyramid or triangle with '*' character
Here I created one class in Console Application. Save this as a *.cs file and run it within your Console Application.
C# code to generate pyramid with characters
using System;
using System.Text;
class PrintPyramid
{
static void Main()
{
// Ask for the number to generate pyramid.
Console.Write("Please enter number to generate triangle: ");
// Get the input value.
var noOfRows = Convert.ToInt64(Console.ReadLine());
// Generate pyramid with the given value.
GenerateTriangle(noOfRows, '*');
// Wait for the response from command line.
Console.ReadLine();
}
// Method to generate pyramid
private static void GenerateTriangle(long noOfRows, char charForTriangle)
{
// Create an instance of type StringBuilder to store spaces.
var sbSpaces = new StringBuilder();
// Add Spaces to the StringBuilder.
for (int spaces = 1; spaces < noOfRows; spaces++)
{
sbSpaces.Append(" ");
}
// Take initial row value as 1.
var noPrint = 1;
for (long number = 1; number <= noOfRows; number++)
{
// Print spaces first.
Console.Write(sbSpaces);
// Print 'X' in a single line to generate proper pyramid.
for (long i = 1; i <= noPrint; i++)
{
Console.Write(charForTriangle);
}
// After printing one line come to second line.
Console.WriteLine();
// Increment noPrint value to add more 'X' to line.
noPrint += 2;
// Each time remove one space from StringBuilder to generate pyramid.
if (sbSpaces.Length > 0)
sbSpaces.Remove(0, 1);
}
}
}
Friday, 4 April 2014
C#.NET Program to generate Prime Numbers
A number which is greater than 1 and divisible by 1 or itself is called prime number.
2 is an even prime number because it is evenly divisible by itself and divisible by 1.
All even numbers are not prime numbers. If the last digit of the number contains 0 2 4 6 8 then the number divisible by 2 thus the number is not a prime number.
Ex: First few prime numbers are 2, 3, 5, 7, 11, 13 ..........
Here I am posting a code snippet how to generate Prime Numbers.
C# Prime Numbers Generator
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class PrimeNumbers
{
static void Main()
{
Console.Write("Please enter a number to generate prime numbers: ");
var ipVal = Convert.ToInt64(Console.ReadLine());
var primeNumbers = GetPrimeNumbersUpTo(ipVal);
PrintPrimeNumbers(primeNumbers, ipVal);
Console.ReadLine();
}
private static void PrintPrimeNumbers(List<long> primeNumbers, long range)
{
Console.WriteLine();
Console.WriteLine("Prime numbers between 2 to " + range);
foreach (long item in primeNumbers)
{
Console.WriteLine(item);
}
}
private static List<long> GetPrimeNumbersUpTo(long ipVal)
{
var primeList = new List<long>();
for (long value = 2; value <= ipVal; value++)
{
if (IsPrimeNumber(value))
{
primeList.Add(value);
}
}
return primeList;
}
private static bool IsPrimeNumber(long inputValue)
{
if (inputValue == 0 || inputValue == 1)
{
return false;
}
if (inputValue == 2)
{
return true;
}
var roundedVal = (long)Math.Round(Math.Sqrt(inputValue));
for (long i = 2; i <= roundedVal; i++)
{
if (inputValue % i == 0)
{
return false;
}
}
return true;
}
}
}
C#.NET program to check whether a given number is prime number or not.
A number which is greater than 1 and divisible by 1 or itself is called prime number.
2 is an even prime number because it is evenly divisible by itself and divisible by 1.
All even numbers are not prime numbers. If the last digit of the number contains 0 2 4 6 8 then the number divisible by 2 thus the number is not a prime number.
Ex: First few prime numbers are 2, 3, 5, 7, 11, 13 ..........
Here I am posting a code snippet to find whether a given number is prime number or not.
C# Program For Prime Number
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
Console.Write("Please enter number to check prime or not: ");
long inputValue = Convert.ToInt32(Console.ReadLine());
if (IsPrimeNumber(inputValue))
{
Console.WriteLine(inputValue + " is prime number");
}
else
{
Console.WriteLine(inputValue + " is not prime number");
}
Console.ReadLine();
}
private static bool IsPrimeNumber(long inputValue)
{
if (inputValue == 0 ||inputValue == 1)
{
return false;
}
if (inputValue == 2)
{
return true;
}
var roundedVal = (long)Math.Round(Math.Sqrt(inputValue));
for (long i = 2; i <= roundedVal; i++)
{
if (inputValue % i == 0)
{
return false;
}
}
return true;
}
}
}
Thursday, 3 April 2014
C#.NET, ASP.NET - Generate non repeated random numbers in C#.NET within the range with the help of Random class.
In this article I will show you how to generate a non repeated random number in between specified range step by step with the explination of code in C#.NET with the help of ASP.NET page.
First please have a look at the complete script page and code behind file.
Generate-Random-Number.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Generate-Random-Number.aspx.cs" Inherits="Scripts_MAR_RandomNumber" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
table tr td:first-child
{
width: 45px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
Enter Number:
<table class="auto-style1">
<tr>
<td>From:</td>
<td>
<asp:TextBox ID="txtFrom" MaxLength="4" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>To:</td>
<td>
<asp:TextBox ID="txtTo" MaxLength="4" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="btnGenerate_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblStatus" runat="server" ForeColor="Red" Text=""></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:TextBox ID="txtRandomNumbers" TextMode="MultiLine" runat="server" Height="113px" Width="434px"></asp:TextBox>
</td>
</tr>
</table>
</form>
</body>
</html>
Generate-Random-Number.aspx.cs
using System;
using System.Collections.Generic;
using System.Text;
public partial class Scripts_MAR_RandomNumber : System.Web.UI.Page
{
protected void btnGenerate_Click(object sender, EventArgs e)
{
// Check the From and To fields have a valid numeric numbers.
if (IsValidForm())
{
// Generate Random Numbers.
var randomNumers = GenerateRandomNumbers(Convert.ToInt32(txtFrom.Text), Convert.ToInt32(txtTo.Text));
// Write random numbers to TextBox.
PrintRandomNumbers(randomNumers);
}
}
// Method to write non repeated random numbers to the TextBox.
private void PrintRandomNumbers(List<int> randomNumers)
{
// Create a StringBuilder to hold the random numbers.
var sbNumbers = new StringBuilder();
foreach (var number in randomNumers)
{
// Add random numbers from List to StringBuilder.
sbNumbers.Append(number + ", ");
}
// Write random numbers from StringBuilder to TextBox
txtRandomNumbers.Text = sbNumbers.ToString();
}
// Method to generate non repeat random numbers.
private List<int> GenerateRandomNumbers(int minValue, int maxValue)
{
// Create an instance of Random class.
var randGenerator = new Random();
// Create an instance of List<int> to store random numbers.
var randValues = new List<int>();
int randNum = 0;
for (int value = minValue; value <= maxValue; value++)
{
// Generate a new random number between range (Min, Max).
randNum = randGenerator.Next(minValue, maxValue + 1);
// Check if the new generated random number is existed in List.
while (randValues.Contains(randNum))
{
// If the the number exists generate new random number with in the range (Min, Max).
randNum = randGenerator.Next(minValue, maxValue + 1);
}
// Add non repeated random number to the List
randValues.Add(randNum);
}
// Return non repeated random numbers List.
return randValues;
}
// Method to check the values are entered in the From field and To field are numeric are not.
private bool IsValidForm()
{
var validForm = true;
int value = 0;
// Check From value is empty or not.
if (string.IsNullOrWhiteSpace(txtFrom.Text))
{
validForm = false;
lblStatus.Text = "Please enter From value.";
}
else
// Check From value is integer or not.
if (!int.TryParse(txtFrom.Text, out value))
{
validForm = false;
lblStatus.Text = "Please enter valid numeric value in From field.";
}
else
// Check From value is negative or not.
if (Convert.ToInt32(txtFrom.Text) < 0)
{
validForm = false;
lblStatus.Text = "Please enter positive value in From field.";
}
// If the value entered in From field is valid then check for To value.
if (validForm)
{
// Check To value is empty or not.
if (string.IsNullOrWhiteSpace(txtTo.Text))
{
validForm = false;
lblStatus.Text = "Please enter To value.";
}
else
// Check To value is integer or not
if (!int.TryParse(txtTo.Text, out value))
{
validForm = false;
lblStatus.Text = "Please enter valid numeric value in To field.";
}
else
// Check To value is negative or not
if (Convert.ToInt32(txtTo.Text) < 0)
{
validForm = false;
lblStatus.Text = "Please enter positive value in To field.";
}
}
// If both From and To fields are integers then check for "From value < To value"
if (validForm)
{
if (Convert.ToInt32(txtFrom.Text) >= Convert.ToInt32(txtTo.Text))
{
validForm = false;
lblStatus.Text = "From value should be less than To value.";
}
}
if (validForm)
{
if (Convert.ToInt32(txtTo.Text) < Convert.ToInt32(txtFrom.Text))
{
validForm = false;
lblStatus.Text = "To value should be greater than From value.";
}
}
// Return the form is valid or invalid.
return validForm;
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
// Check the From and To fields have a valid numeric numbers.
if (IsValidForm())
{
// Generate Random Numbers.
var randomNumers = GenerateRandomNumbers(Convert.ToInt32(txtFrom.Text), Convert.ToInt32(txtTo.Text));
// Write random numbers to TextBox.
PrintRandomNumbers(randomNumers);
}
}
- Check From value is integer or not.
- Check From value is negative or not.
- If the value entered in From field is valid then check for To value.
- Check To value is empty or not.
- Check To value is negative or not
- If both From and To fields are integers then check for "From value < To value"
- Return the form is valid or invalid.
// Method to check the values are entered in the From field and To field are numeric are not.
private bool IsValidForm()
{
var validForm = true;
int value = 0;
// Check From value is empty or not.
if (string.IsNullOrWhiteSpace(txtFrom.Text))
{
validForm = false;
lblStatus.Text = "Please enter From value.";
}
else
// Check From value is integer or not.
if (!int.TryParse(txtFrom.Text, out value))
{
validForm = false;
lblStatus.Text = "Please enter valid numeric value in From field.";
}
else
// Check From value is negative or not.
if (Convert.ToInt32(txtFrom.Text) < 0)
{
validForm = false;
lblStatus.Text = "Please enter positive value in From field.";
}
// If the value entered in From field is valid then check for To value.
if (validForm)
{
// Check To value is empty or not.
if (string.IsNullOrWhiteSpace(txtTo.Text))
{
validForm = false;
lblStatus.Text = "Please enter To value.";
}
else
// Check To value is integer or not
if (!int.TryParse(txtTo.Text, out value))
{
validForm = false;
lblStatus.Text = "Please enter valid numeric value in To field.";
}
else
// Check To value is negative or not
if (Convert.ToInt32(txtTo.Text) < 0)
{
validForm = false;
lblStatus.Text = "Please enter positive value in To field.";
}
}
// If both From and To fields are integers then check for "From value < To value"
if (validForm)
{
if (Convert.ToInt32(txtFrom.Text) >= Convert.ToInt32(txtTo.Text))
{
validForm = false;
lblStatus.Text = "From value should be less than To value.";
}
}
if (validForm)
{
if (Convert.ToInt32(txtTo.Text) < Convert.ToInt32(txtFrom.Text))
{
validForm = false;
lblStatus.Text = "To value should be greater than From value.";
}
}
// Return the form is valid or invalid.
return validForm;
}
- Create an instance of Random class.
- Create an instance of List<int> to store random numbers.
- Generate a new random number between range (Min, Max).
- Check if the new generated random number is existed in List.
- If the the number exists generate new random number with in the range (Min, Max).
- Add non repeated random number to the List
- Return non repeated random numbers List.
// Method to generate non repeat random numbers.
private List<int> GenerateRandomNumbers(int minValue, int maxValue)
{
// Create an instance of Random class.
var randGenerator = new Random();
// Create an instance of List<int> to store random numbers.
var randValues = new List<int>();
int randNum = 0;
for (int value = minValue; value <= maxValue; value++)
{
// Generate a new random number between range (Min, Max).
randNum = randGenerator.Next(minValue, maxValue + 1);
// Check if the new generated random number is existed in List.
while (randValues.Contains(randNum))
{
// If the the number exists generate new random number with in the range (Min, Max).
randNum = randGenerator.Next(minValue, maxValue + 1);
}
// Add non repeated random number to the List
randValues.Add(randNum);
}
// Return non repeated random numbers List.
return randValues;
}
- Create a StringBuilder to hold the random numbers.
- Add random numbers from List to StringBuilder.
- Write random numbers from StringBuilder to TextBox
// Method to write non repeated random numbers to the TextBox.
private void PrintRandomNumbers(List<int> randomNumers)
{
// Create a StringBuilder to hold the random numbers.
var sbNumbers = new StringBuilder();
foreach (var number in randomNumers)
{
// Add random numbers from List to StringBuilder.
sbNumbers.Append(number + ", ");
}
// Write random numbers from StringBuilder to TextBox
txtRandomNumbers.Text = sbNumbers.ToString();
}
From: 1
To: 10
From: 1
To: 100
Output:
Subscribe to:
Posts (Atom)