Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

10/08/2021

Conditional Formatting in Asp .Net Web Form Gridview

 

<asp:TemplateField HeaderText="Status" SortExpression="Status">
     <EditItemTemplate>
        <asp:Label ID="lblStatus" runat="server" Text='<%# Eval("Status") %>'></asp:Label>
     </EditItemTemplate>
     <ItemTemplate>
        <asp:Label ID="lblStatus" runat="server" Text='<%# Bind("Status") %>' ForeColor='<%# ((string)Eval("Status")).ToLower().Equals("open") ? System.Drawing.Color.Green : System.Drawing.Color.Red %>'></asp:Label>
     </ItemTemplate>
 </asp:TemplateField>

7/20/2021

C# Regular Expression - Windows Form Application (Username Validation)

 

C# Regular Expression - Windows Form Application (Username Validation)
C# Regular Expression - Windows Form Application (Username Validation)


   private void txtUsername_TextChanged(object sender, EventArgs e)
        {
            if (IsValidUsername(txtUsername.Text))
            {
                lblMsg.ForeColor = System.Drawing.Color.Green;
                lblMsg.Text = "Valid Username";
            }
            else
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = "Invalid Username!";
            }
        }
        public static bool IsValidUsername(string username)
        {
            //Username starts with a letter, allow letter or number, length between 7 to 12.
            string pattern;
            pattern = @"^[a-zA-Z][a-zA-Z0-9]{6,11}$";
            Regex regex = new Regex(pattern);
            return regex.IsMatch(username);
        }

12/14/2019

How To Display Selected CheckedListBox Items In TextBox Separated By Comma In C#

how to display selected checkedlistbox items in textbox separated by comma in c#
how to display selected checkedlistbox items in textbox separated by comma in c#


private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string values = "";
            foreach (object item in checkedListBox1.CheckedItems)
            {
                if (values == "")
                    values = item.ToString();
                else values += "," + item.ToString();

            }
            textBox1.Text = values;
        }

6/30/2019

Stopwatch C# windows form

Stopwatch
Stopwatch Design Foorm

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace StopwatchProject
{
    public partial class frmStopwatch : Form
    {
        private Stopwatch mainStopwatch;
        private Stopwatch smallStopwatch; // New stopwatch for small timer  
        private Timer mainTimer;
        private Timer smallTimer; // New timer for small stopwatch  
        private int lapCount;
        private TimeSpan lastLapTime;
        public frmStopwatch()
        {
            InitializeComponent();
            mainStopwatch = new Stopwatch();
            smallStopwatch = new Stopwatch(); // Initialize small stopwatch  
            mainTimer = new Timer();
            smallTimer = new Timer(); // Initialize small timer  
            mainTimer.Interval = 100; // Update every 100ms  
            smallTimer.Interval = 100; // Update every 100ms for small timer  
            mainTimer.Tick += MainTimer_Tick;
            smallTimer.Tick += SmallTimer_Tick; // Event for small timer  
            lblTime.Text = "00:00:00.00"; // Initial time for main stopwatch  
            lblSmallTime.Text = "00:00:00.00"; // Initial time for small stopwatch  
            lapCount = 0; // Initialize lap count  
            lblLapCount.Text = "Lap Count: 0"; // Initialize lap count display  
            lastLapTime = TimeSpan.Zero; // Initialize last lap time 

            // Set up DataGridView columns  
            dataGridViewLaps.Columns.Add("LapNumber", "Lap");
            dataGridViewLaps.Columns.Add("LapTime", "Lap Times");
            dataGridViewLaps.Columns.Add("OverallTime", "Overall Time");
            dataGridViewLaps.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dataGridViewLaps.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dataGridViewLaps.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            dataGridViewLaps.MultiSelect = false;
            dataGridViewLaps.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
            dataGridViewLaps.AllowUserToResizeRows = false;
            
        }
        private void MainTimer_Tick(object sender, EventArgs e)
        {
            lblTime.Text = FormatTime(mainStopwatch.Elapsed);
        }

        private void SmallTimer_Tick(object sender, EventArgs e)
        {
            lblSmallTime.Text = FormatTime(smallStopwatch.Elapsed); // Update small stopwatch display  
        }
        private string FormatTime(TimeSpan timeSpan)
        {
            return string.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                timeSpan.Hours,
                timeSpan.Minutes,
                timeSpan.Seconds,
                timeSpan.Milliseconds / 10);
        }

        private void btnStartStop_Click(object sender, EventArgs e)
        {
            if (mainStopwatch.IsRunning)
            {
                mainStopwatch.Stop();
                mainTimer.Stop();
                smallStopwatch.Stop();
                smallTimer.Stop();
                btnStartStop.Text = "Start";
            }
            else
            {
                mainStopwatch.Start();
                mainTimer.Start();
                smallStopwatch.Start();
                smallTimer.Start();
                btnStartStop.Text = "Stop";
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            mainStopwatch.Reset();
            lblTime.Text = "00:00:00.00";
            dataGridViewLaps.Rows.Clear(); // Clear the DataGridView
            lapCount = 0; // Reset lap count  
            lblLapCount.Text = "Lap Count: 0"; // Update lap count display  
            btnStartStop.Text = "Start";
            mainTimer.Stop();
            lastLapTime = TimeSpan.Zero; // Reset last lap time  

            // Reset small stopwatch  
            smallStopwatch.Reset();
            lblSmallTime.Text = "00:00:00.00"; // Reset small stopwatch display  
            smallTimer.Stop(); // Stop small timer   
            lblSmallTime.Visible = false;
        }

        private void btnLap_Click(object sender, EventArgs e)
        {
            if (mainStopwatch.IsRunning)
            {
                lapCount++; // Increment lap count  
                TimeSpan currentLapTime = mainStopwatch.Elapsed - lastLapTime; // Calculate lap time  
                lastLapTime = mainStopwatch.Elapsed; // Update last lap time  
                string lapTime = FormatTime(currentLapTime); // Get the formatted lap time  
                string overallTime = FormatTime(mainStopwatch.Elapsed); // Get the overall time  

                // Add a new row to the DataGridView  
                dataGridViewLaps.Rows.Insert(0, lapCount, lapTime, overallTime);

                dataGridViewLaps.ClearSelection();

                lblLapCount.Text = $"Lap Count: {lapCount}"; // Update lap count display  

                // Reset and start the small stopwatch  
                smallStopwatch.Reset();
                smallStopwatch.Start();
                smallTimer.Start(); // Start small timer  
                lblSmallTime.Visible=true;
            }
        }
    }
}

2/01/2016

C# User Defined RandomStringGenerator()


public partial class Signup : System.Web.UI.Page
{
   private string GenAuthCode(string username)
    {
        RandomStringGenerator myrsg = new RandomStringGenerator();
        return myrsg.NextString(20);
    }
}
public class RandomStringGenerator
{
    private Random r;
    const string Uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const string Lowercase = "abcdefghijklmnopqrstuvwxyz";
    const string Numbers = "0123456789";
    const string Symbols = @"~`!@#$%^&()-_=+<>?:,./\[]{}'";
    public RandomStringGenerator()
    {
        r = new Random();
    }
    public RandomStringGenerator(int seed)
    {
        r = new Random(seed);
    }
    public virtual string NextString(int Length)
    {
        return NextString(Length, true, true, true, true);
    }
    public virtual string NextString(int Length, bool lowerCase, bool upperCase, bool numbers, bool symbols)
    {
        char[] charArray = new char[Length];
        string charpool = string.Empty;

        //Build character pool
        if (lowerCase)
            charpool += lowerCase;
        if (upperCase)
            charpool += upperCase;
        if (numbers)
            charpool += numbers;
        if (symbols)
            charpool += symbols;

        //Build the output character array
        for (int i = 0; i < charArray.Length; i++)
        {
            //Pick the randim integer in the character pool
            int index = r.Next(0, charpool.Length);

            //Set it to the output character array
            charArray[i] = charpool[index];
        }
        return new string(charArray);

    }
}

9/10/2015

C# Console Application (Bank)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bank
{
    class Errors:Exception
    {
        public Errors(string ErrorMsg)
            : base(ErrorMsg)
        {

        }

    }
    class Accounts
    {
        public int[] index;
        public string Acc_no = "", C_name = "", C_add = "";
        public double Balance = 0;
        int Age;
        public Accounts() { }
        public Accounts(String Acc_no, string C_name,int Age, String C_add, double Balance)
        {
            //int[] index,
            //this.index = index;
            this.Acc_no = Acc_no;
            this.C_name = C_name;
            this.C_add = C_add;
            this.Balance=Balance;
        }

        public int Create_Acc()
        {
            //for (int i = 0; i < index.Length;i++ )
            //{

            //}
            try
            {
                Console.Write("Enter The Account Number:\t");
                Acc_no = Console.ReadLine();
                if (Acc_no == null)
                    throw new Errors("You must enter the Account number!");
                
                Console.Write("Enter The Customer Name:\t");
                C_name = Console.ReadLine();
                if (C_name == null)
                    throw new Errors("You must enter the Account number!");
                
                Console.Write("Age:\t\t\t\t");
                Age = int.Parse(Console.ReadLine());
                if (Age <=0)
                    throw new Errors("You must enter the Account number!");
                
                Console.Write("Enter The Address:\t\t");
                C_add = Console.ReadLine();
                if (C_add == null)
                    throw new Errors("You must enter the Account number!");
                
                Console.Write("Deposite amount:\t\t");
                Balance = double.Parse(Console.ReadLine());
                if (Balance <= 0)
                    throw new Errors("You must enter the Account number!");
            }
            catch(Errors e)
            {
                Console.Write(e.Message);
            }
            
            return 1;

        }

        public void Acc_Availability(string Acc_num)
        {
            if (Acc_no.Equals(Acc_num))
            {
                Console.WriteLine("-----------------------------****************-----------------------------");
                Console.WriteLine("Account Number:\t"+Acc_no);
                Console.WriteLine("Name:\t\t"+C_name);
                Console.WriteLine("Age:\t\t" + Age);
                Console.WriteLine("Address:\t" + C_add);
                Console.WriteLine("Balance: \t$" + Balance);
                Console.WriteLine("-----------------------------****************-----------------------------");
            }
            else
            {
                Console.WriteLine("Account does not exist!");
            }
        }
        public void Deposite(string Acc_num)
        {
            try
            {


                if (Acc_no.Equals(Acc_num))
                {
                    Console.Write("Enter the amount:\t\t");
                    int Amount = int.Parse(Console.ReadLine());
                    if (Amount <= 0)
                        throw new Errors("Amount must be larger than $0");
                    else
                        this.Balance = Balance + Amount;

                    Console.WriteLine("-----------------------------****************-----------------------------");
                    Console.WriteLine("Balance is:  $" + Balance);
                    Console.WriteLine("-----------------------------****************-----------------------------");
                }
                else
                {
                    Console.WriteLine("Account does not exist!");
                }
            }
            catch(Errors e)
            {
                Console.BackgroundColor = ConsoleColor.White;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Message);
                Console.BackgroundColor = ConsoleColor.Black;
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
        public void Withdraw(string Acc_num)
        {
            if (Acc_no.Equals(Acc_num))
            {
                Console.Write("Enter the amount:\t\t");
                int Amount = int.Parse(Console.ReadLine());
                if (Balance == 0)
                {
                    Console.WriteLine("Insufficient balance");

                }
                else if (Amount > Balance)
                {
                    Console.WriteLine("Insufficient balance");
                }
                else
                {
                    Balance = Balance - Amount;
                    Console.WriteLine("Balance: $"+Balance);
                }
            }
            else
            {
                Console.WriteLine("Account does not exist!");
            }
        }
        public void Balenquiry()
        {
            Console.WriteLine("Your baance is: " + Balance);
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            //char ch;
            int result;
            String Acc_num,ch;
            //double depositeamount;
            //double withdrawamount;

            Accounts Acc = new Accounts();
            //try
            //{

           
                for (; ; )
                {
                    Console.WriteLine("----------------------------------------------------------------------");
                    Console.WriteLine("1.New Acoount\t2.Enquiry\t3.Deposit\t4.Withdraw\t5.Exit");
                    Console.WriteLine("----------------------------------------------------------------------");
                    ch = Console.ReadLine();
                    
                    switch (ch)
                    {
                        case "1": 
                            
                            result=Acc.Create_Acc();
                            if(result==1)
                            {
                                Console.WriteLine("Account number \"{0}\" Created Successfuly", Acc.Acc_no);
                            }
                            else
                            {
                                Console.WriteLine("Account could not be created! Try again.");
                            }
                            
                            break;

                        case "2":
                            
                            Console.Write("Enter the Account Number:\t");
                            Acc_num=Console.ReadLine();
                            Acc.Acc_Availability(Acc_num);
                            break;

                        case "3":
                            
                            Console.Write("Enter the Account Number:\t");
                            Acc_num=Console.ReadLine();
                            Acc.Deposite(Acc_num);
                            break;

                        case "4":
                            
                            Console.Write("Enter The Customer Account Number:  ");
                            Acc_num = Console.ReadLine();
                            Acc.Withdraw(Acc_num);
                            break;
                        
                        case "5": 
                            
                            System.Environment.Exit(0);
                            break;

                        default:
                            
                            Console.WriteLine("invalid choice!");
                            break;
                    }
                }
             }
            //catch(Errors e)
            //{
            //    Console.WriteLine(e.Message);
            //}
            //}
             
        
    }
}

6/01/2015

Asp .Net C# (ADO .NET)

SqlDataReader
SqlDataReader


ExceuteNonQuery(Insert,Update,Delete)
ExceuteNonQuery(Insert,Update,Delete)


ExceuteNonQuery (Insert)
ExceuteNonQuery (Insert)


ExceuteReader (1)
ExceuteReader (1)


ExceuteReader (2)
ExceuteReader (2)


ExecuteScalar
ExecuteScalar

1/04/2015

C# Dictionary

using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;
using System.Windows.Forms;  
using System.Data.OleDb;
namespace KDictionary  
{
  public partial class Dic : Form
{
  private OleDbConnection cn;
  private OleDbDataReader reader;
  private OleDbCommand com;
  private DataSet rs;
  private OleDbDataAdapter ad;
      public Dic()
  {
  InitializeComponent();
  }
    private void Dic_Resize(object sender, EventArgs e)
  {
  //Adjust listbox and textbox heights when the form resizes
  //Dic dictionary = new Dic();
  if (this.WindowState == FormWindowState.Maximized)
  {
  Lstterms.Height = this.Height;  
        Txtresult.Height = this.Height;
  Txtresult.Width = this.Width ;
  }
}   
 private void Dic_Load(object sender, EventArgs e)
  {
  myconnect();
  this.Resize+= new EventHandler(Dic_Resize);
  this.FormClosed += new FormClosedEventHandler(Dic_FormClosed);
   }
 
       private void myconnect()
        {
  try
  {
   //connect to database
  rs = new DataSet();
  cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +   Application.StartupPath + "\\data.mdb;");
  cn.Open();
  ad = new OleDbDataAdapter("SELECT * FROM Tblterms ORDER BY Enterms", cn);
  ad.Fill(rs, "Tblterms");
  com = new OleDbCommand("SELECT Enterms FROM Tblterms ORDER BY Enterms", cn);
  reader = com.ExecuteReader();
  //clear list  
        Lstterms.Items.Clear();
  //clear txtresult
  Txtresult.Text = "";
  while (reader.Read())  {
  Lstterms.Items.Add(reader[0].ToString());
  } 
        } 
 catch (Exception ex)
        {
        }
  Txtbox.Focus();
       }
  private void Txtbox_TextChanged(object sender, EventArgs e)  
        {
  int i;
  DataRow dr;
  try  { 
 for (i = 0; i <= Lstterms.Items.Count - 1; i++)
  { 
  if (Txtbox.Text.Trim().ToUpper() == Lstterms.Items[i].ToString().ToUpper().Substring(0,   Txtbox.TextLength))
  { 
 //Select matched term  
        Lstterms.SelectedIndex = i;
  //Display translation  
        dr = rs.Tables[0].Rows[i];
  Txtresult.Clear();
  Txtresult.Text = dr[1].ToString().Trim();
  highlight(); 
 break;
  } 
 } 
 }  
       catch (Exception ex)
       {
       } 
      }    
       private void Lstterms_SelectedIndexChanged(object sender, EventArgs e)
  {
  DataRow dr;
  dr = rs.Tables[0].Rows[Lstterms.SelectedIndex];
  Txtresult.Clear(); //clear result
  Txtresult.Text =dr[1].ToString().Trim ();
  highlight(); 
 }  
       private void highlight()  
       {    
         try  {
   char[] c = Txtresult.Text.ToString().ToCharArray();  //coloring v.,a., and n.
  int i; 
 for (i = 1; i <= Txtresult.Text.ToString().Length - 2; i++)
  { 
 if ((c[i] == '.' && c[i - 1] == 'v') || (c[i] == '.' && c[1 - 1] == 'a') ||   (c[i] == '.' && c[i - 1] == 'n'))  
//If (((c[i] == ".") && (c[i - 1] == "v")) || ((c[i] == ".") && (c[i - 1] ==   "a")) || ((c[i] == ".") && (c[i - 1] =="n"))) 
 {
  Txtresult.SelectionStart = i - 1;
  Txtresult.SelectionLength = 2;
  Txtresult.SelectionColor = Color.Red; 
   } 
   } 
 //coloring adj., adv. 
 for (i = 3; i <= Txtresult.Text.ToString().Length - 1; i++)
  { 
if ((c[i] == '.' && c[i - 1] == 'j' && c[i - 2] == 'd') || (c[i] == '.' &&   c[i - 1] == 'g' && c[i - 2] == 'i') || (c[i] == '.' && c[i - 1] == 'v' && c[i   - 2] == 'd'))
  {  
Txtresult.SelectionStart = i - 3;
  Txtresult.SelectionLength = 4;
  Txtresult.SelectionColor = Color.Red;
  }
    }
  //coloring Khmer character
    for (i = 0; i <= Txtresult.Text.ToString().Length - 1; i++) 
 { 
   if ((int)c[i] > 127)
  {  
       //int ix = (int)c[i];  
       //MessageBox.Show("Hello"+ix);
  Txtresult.SelectionStart = i;
  Txtresult.SelectionLength = 1;
  Txtresult.SelectionColor = Color.Black; 
 } 
 } 
     } 
 catch (Exception ex) { } 
 } 
 private void closeToolStripMenuItem_Click(object sender, EventArgs e)
  { 
  Close();
   }  
  private void menuStrip1_ItemClicked(object sender,ToolStripItemClickedEventArgs e) 
 {
 
 } 
 private void Dic_FormClosed(object sender,EventArgs e) 
 {  
         cn.Close();  
         cn = null;  
         com = null;  
         reader = null;  
         ad = null;  
         rs = null; 
 } 
  }
  }  

9/18/2014

Date and Time Format Strings in C#

Date and Time Format Strings in C#
Date and Time Format Strings in C#


private void dateTimePicker1_ValueChanged(object sender, EventArgs e)  
     {  
       label15.Text = dateTimePicker1.Value.ToString("d");  
       label16.Text = dateTimePicker1.Value.ToString("D");  
       label17.Text = dateTimePicker1.Value.ToString("f");  
       label18.Text = dateTimePicker1.Value.ToString("F");  
       label19.Text = dateTimePicker1.Value.ToString("g");  
       label20.Text = dateTimePicker1.Value.ToString("G");  
       label21.Text = dateTimePicker1.Value.ToString("m");  
       label22.Text = dateTimePicker1.Value.ToString("r");  
       label23.Text = dateTimePicker1.Value.ToString("s");  
       label24.Text = dateTimePicker1.Value.ToString("t");  
       label25.Text = dateTimePicker1.Value.ToString("T");  
       label26.Text = dateTimePicker1.Value.ToString("u");  
       label27.Text = dateTimePicker1.Value.ToString("U");  
       label28.Text = dateTimePicker1.Value.ToString("y");  
     }   

7/10/2014

Increment the value of Qty if row with the same data already exists in DataGridView

Increment the value of Qty if row with the same data already exists in DataGridView
Increment the value of Qty if row with the same data already exists in DataGridView


private void btn_Add_Click(object sender, EventArgs e)  
     {  
       //Boolean value to check if the DataGridView has the same value.  
       bool Found = false;  
       double total = Convert.ToDouble(txt_Price.Text) * 1;  
       if (dataGridView1.Rows.Count > 0)  
       {  
         //Check if the product Name exists with the same Price  
         foreach (DataGridViewRow row in dataGridView1.Rows)  
         {  
           if (Convert.ToString(row.Cells[0].Value) == txt_Name.Text && Convert.ToString(row.Cells[2].Value) == txt_Price.Text)  
           {  
             //Update the Quantity of the found row  
             row.Cells[1].Value = Convert.ToString(1 + Convert.ToInt16(row.Cells[1].Value));  
             row.Cells[3].Value = Convert.ToDouble(row.Cells[1].Value) * Convert.ToDouble(row.Cells[2].Value);  
             Found = true;  
           }  
         }  
         if (!Found)  
         {  
           //Add the row to DataGridView if data not present  
           dataGridView1.Rows.Add( txt_Name.Text,1, txt_Price.Text,total);  
         }  
       }  
       else  
       {  
         //Add the first row to DataGridView if there is no row  
         dataGridView1.Rows.Add( txt_Name.Text, 1, txt_Price.Text,total);  
       }  
     }