This Code Can Use To Change The Design and Customize The DataGridView
private void SetUpDataGridView()
{
this.Controls.Add(dataGridView1);
dataGridView1.ColumnCount = 5;
DataGridViewCellStyle style =
dataGridView1.ColumnHeadersDefaultCellStyle;
style.BackColor = Color.Navy;
style.ForeColor = Color.White;
style.Font = new Font(dataGridView1.Font, FontStyle.Bold);
dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
dataGridView1.Name = "dataGridView1";
dataGridView1.Location = new Point(8, 8);
dataGridView1.Size = new Size(500, 300);
dataGridView1.AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
dataGridView1.ColumnHeadersBorderStyle =
DataGridViewHeaderBorderStyle.Raised;
dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.Single;
dataGridView1.GridColor = SystemColors.ActiveBorder;
dataGridView1.RowHeadersVisible = false;
dataGridView1.Columns[0].Name = "Release Date";
dataGridView1.Columns[1].Name = "Track";
dataGridView1.Columns[1].DefaultCellStyle.Alignment =
DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[2].Name = "Title";
dataGridView1.Columns[3].Name = "Artist";
dataGridView1.Columns[4].Name = "Album";
// Make the font italic for row four.
dataGridView1.Columns[4].DefaultCellStyle.Font = new Font(DataGridView.DefaultFont, FontStyle.Italic);
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.BackgroundColor = Color.Honeydew;
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);
dataGridView1.CellParsing += new DataGridViewCellParsingEventHandler(dataGridView1_CellParsing);
addNewRowButton.Click += new EventHandler(addNewRowButton_Click);
deleteRowButton.Click += new EventHandler(deleteRowButton_Click);
ledgerStyleButton.Click += new EventHandler(ledgerStyleButton_Click);
dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
}
Apr 9, 2014
Feb 19, 2014
Get The English Text For A Number
This Example Shows How To Get The English Text For A Number.This Can Be Used To Convert A Numeric Currency To English Sentence.
By Passing A Number To This Method You Can Get The Text For The Number You Passed
public static string ConvertMoneyToText(string value)//---Convert Currency To Word---
{
value = value.Replace(",", "").Replace("$", "");
int decimalCount = 0;
int Val = value.Length - 1;
for (int x = 0; x <= Val; x++)
{
char Val2 = value[x];
if (Val2.ToString() == ".")
{
decimalCount++;
if (decimalCount > 1)
{
throw new ArgumentException("Only monetary values are accepted");
}
}
Val2 = value[x];
char Valtemp = value[x];
if (!(char.IsDigit(value[x]) | (Val2.ToString() == ".")) & !((x == 0) & (Valtemp.ToString() == "-")))
{
throw new ArgumentException("Only monetary values are accepted");
}
}
string returnValue = "";
string[] parts;
if (value.Contains("."))
parts = value.Split(new char[] { '.' });
else
parts = (value + ".00").Split(new char[] { '.' });
parts[1] = new string((parts[1] + "00").Substring(0, 2).ToCharArray());
bool IsNegative = parts[0].Contains("-");
if (parts[0].Replace("-", "").Length > 0x12)
{
throw new ArgumentException("Maximum value is $999,999,999,999,999,999.99");
}
if (IsNegative)
{
parts[0] = parts[0].Replace("-", "");
returnValue = returnValue + "Minus ";
}
if (parts[0].Length > 15)
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(0x12, '0').Substring(0, 3)) + "Quadrillion ";
if (parts[0].PadLeft(0x12, '0').Substring(3, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(0x12, '0').Substring(3, 3)) + "Trillion ";
}
if (parts[0].PadLeft(0x12, '0').Substring(6, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(0x12, '0').Substring(6, 3)) + "Billion ";
}
if (parts[0].PadLeft(0x12, '0').Substring(9, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(0x12, '0').Substring(9, 3)) + "Million ";
}
if (parts[0].PadLeft(0x12, '0').Substring(12, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(0x12, '0').Substring(12, 3)) + "Thousand ";
}
}
else if (parts[0].Length > 12)
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(15, '0').Substring(0, 3)) + "Trillion ";
if (parts[0].PadLeft(15, '0').Substring(3, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(15, '0').Substring(3, 3)) + "Billion ";
}
if (parts[0].PadLeft(15, '0').Substring(6, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(15, '0').Substring(6, 3)) + "Million ";
}
if (parts[0].PadLeft(15, '0').Substring(9, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(15, '0').Substring(9, 3)) + "Thousand ";
}
}
else if (parts[0].Length > 9)
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(12, '0').Substring(0, 3)) + "Billion ";
if (parts[0].PadLeft(12, '0').Substring(3, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(12, '0').Substring(3, 3)) + "Million ";
}
if (parts[0].PadLeft(12, '0').Substring(3, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(12, '0').Substring(6, 3)) + "Thousand ";
}
}
else if (parts[0].Length > 6)
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(9, '0').Substring(0, 3)) + "Million ";
if (parts[0].PadLeft(9, '0').Substring(0, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(9, '0').Substring(3, 3)) + "Thousand ";
}
}
else if (parts[0].Length > 3)
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(6, '0').Substring(0, 3)) + "Thousand ";
}
string hundreds = parts[0].PadLeft(3, '0');
int tempInt = 0;
hundreds = hundreds.Substring(hundreds.Length - 3, 3);
if (int.TryParse(hundreds, out tempInt) == true)
{
returnValue = returnValue + HundredsText(hundreds) + "Rupee";
if (int.Parse(hundreds) != 1)
{
returnValue = returnValue + "s";
}
if (int.Parse(parts[1]) != 0)
{
returnValue = returnValue + " and ";
}
}
if ((parts.Length == 2) && (int.Parse(parts[1]) != 0))
{
returnValue = returnValue + HundredsText(parts[1].PadLeft(3, '0')) + "Cent";
if (int.Parse(parts[1]) != 1)
{
returnValue = returnValue + "s";
}
}
return returnValue;
}
private static string HundredsText(string value)
{
char Val_1;
char Val_2;
string returnValue = "";
bool IsSingleDigit = true;
char Val = value[0];
if (int.Parse(Val.ToString()) != 0)
{
Val_1 = value[0];
returnValue = returnValue + Ones[int.Parse(Val_1.ToString()) - 1] + " Hundred ";
IsSingleDigit = false;
}
Val_1 = value[1];
if (int.Parse(Val_1.ToString()) > 1)
{
Val = value[1];
returnValue = returnValue + Tens[int.Parse(Val.ToString()) - 1] + " ";
Val_1 = value[2];
if (int.Parse(Val_1.ToString()) != 0)
{
Val = value[2];
returnValue = returnValue + Ones[int.Parse(Val.ToString()) - 1] + " ";
}
return returnValue;
}
Val_1 = value[1];
if (int.Parse(Val_1.ToString()) == 1)
{
Val = value[1];
Val_2 = value[2];
return (returnValue + Ones[int.Parse(Val.ToString() + Val_2.ToString()) - 1] + " ");
}
Val_2 = value[2];
if (int.Parse(Val_2.ToString()) == 0)
{
return returnValue;
}
if (!IsSingleDigit)
{
returnValue = returnValue + "and ";
}
Val_2 = value[2];
return (returnValue + Ones[int.Parse(Val_2.ToString()) - 1] + " ");
}
static string[] Tens = new string[] {
"Ten",
"Twenty",
"Thirty",
"Forty",
"Fifty",
"Sixty",
"Seventy",
"Eighty",
"Ninety" };
static string[] Ones = new string[] {
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten",
"Eleven",
"Twelve",
"Thirteen",
"Fourteen",
"Fifteen",
"Sixteen",
"Seventeen",
"Eighteen",
"Nineteen"};
By Passing A Number To This Method You Can Get The Text For The Number You Passed
public static string ConvertMoneyToText(string value)//---Convert Currency To Word---
{
value = value.Replace(",", "").Replace("$", "");
int decimalCount = 0;
int Val = value.Length - 1;
for (int x = 0; x <= Val; x++)
{
char Val2 = value[x];
if (Val2.ToString() == ".")
{
decimalCount++;
if (decimalCount > 1)
{
throw new ArgumentException("Only monetary values are accepted");
}
}
Val2 = value[x];
char Valtemp = value[x];
if (!(char.IsDigit(value[x]) | (Val2.ToString() == ".")) & !((x == 0) & (Valtemp.ToString() == "-")))
{
throw new ArgumentException("Only monetary values are accepted");
}
}
string returnValue = "";
string[] parts;
if (value.Contains("."))
parts = value.Split(new char[] { '.' });
else
parts = (value + ".00").Split(new char[] { '.' });
parts[1] = new string((parts[1] + "00").Substring(0, 2).ToCharArray());
bool IsNegative = parts[0].Contains("-");
if (parts[0].Replace("-", "").Length > 0x12)
{
throw new ArgumentException("Maximum value is $999,999,999,999,999,999.99");
}
if (IsNegative)
{
parts[0] = parts[0].Replace("-", "");
returnValue = returnValue + "Minus ";
}
if (parts[0].Length > 15)
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(0x12, '0').Substring(0, 3)) + "Quadrillion ";
if (parts[0].PadLeft(0x12, '0').Substring(3, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(0x12, '0').Substring(3, 3)) + "Trillion ";
}
if (parts[0].PadLeft(0x12, '0').Substring(6, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(0x12, '0').Substring(6, 3)) + "Billion ";
}
if (parts[0].PadLeft(0x12, '0').Substring(9, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(0x12, '0').Substring(9, 3)) + "Million ";
}
if (parts[0].PadLeft(0x12, '0').Substring(12, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(0x12, '0').Substring(12, 3)) + "Thousand ";
}
}
else if (parts[0].Length > 12)
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(15, '0').Substring(0, 3)) + "Trillion ";
if (parts[0].PadLeft(15, '0').Substring(3, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(15, '0').Substring(3, 3)) + "Billion ";
}
if (parts[0].PadLeft(15, '0').Substring(6, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(15, '0').Substring(6, 3)) + "Million ";
}
if (parts[0].PadLeft(15, '0').Substring(9, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(15, '0').Substring(9, 3)) + "Thousand ";
}
}
else if (parts[0].Length > 9)
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(12, '0').Substring(0, 3)) + "Billion ";
if (parts[0].PadLeft(12, '0').Substring(3, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(12, '0').Substring(3, 3)) + "Million ";
}
if (parts[0].PadLeft(12, '0').Substring(3, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(12, '0').Substring(6, 3)) + "Thousand ";
}
}
else if (parts[0].Length > 6)
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(9, '0').Substring(0, 3)) + "Million ";
if (parts[0].PadLeft(9, '0').Substring(0, 3) != "000")
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(9, '0').Substring(3, 3)) + "Thousand ";
}
}
else if (parts[0].Length > 3)
{
returnValue = returnValue + HundredsText(parts[0].PadLeft(6, '0').Substring(0, 3)) + "Thousand ";
}
string hundreds = parts[0].PadLeft(3, '0');
int tempInt = 0;
hundreds = hundreds.Substring(hundreds.Length - 3, 3);
if (int.TryParse(hundreds, out tempInt) == true)
{
returnValue = returnValue + HundredsText(hundreds) + "Rupee";
if (int.Parse(hundreds) != 1)
{
returnValue = returnValue + "s";
}
if (int.Parse(parts[1]) != 0)
{
returnValue = returnValue + " and ";
}
}
if ((parts.Length == 2) && (int.Parse(parts[1]) != 0))
{
returnValue = returnValue + HundredsText(parts[1].PadLeft(3, '0')) + "Cent";
if (int.Parse(parts[1]) != 1)
{
returnValue = returnValue + "s";
}
}
return returnValue;
}
private static string HundredsText(string value)
{
char Val_1;
char Val_2;
string returnValue = "";
bool IsSingleDigit = true;
char Val = value[0];
if (int.Parse(Val.ToString()) != 0)
{
Val_1 = value[0];
returnValue = returnValue + Ones[int.Parse(Val_1.ToString()) - 1] + " Hundred ";
IsSingleDigit = false;
}
Val_1 = value[1];
if (int.Parse(Val_1.ToString()) > 1)
{
Val = value[1];
returnValue = returnValue + Tens[int.Parse(Val.ToString()) - 1] + " ";
Val_1 = value[2];
if (int.Parse(Val_1.ToString()) != 0)
{
Val = value[2];
returnValue = returnValue + Ones[int.Parse(Val.ToString()) - 1] + " ";
}
return returnValue;
}
Val_1 = value[1];
if (int.Parse(Val_1.ToString()) == 1)
{
Val = value[1];
Val_2 = value[2];
return (returnValue + Ones[int.Parse(Val.ToString() + Val_2.ToString()) - 1] + " ");
}
Val_2 = value[2];
if (int.Parse(Val_2.ToString()) == 0)
{
return returnValue;
}
if (!IsSingleDigit)
{
returnValue = returnValue + "and ";
}
Val_2 = value[2];
return (returnValue + Ones[int.Parse(Val_2.ToString()) - 1] + " ");
}
static string[] Tens = new string[] {
"Ten",
"Twenty",
"Thirty",
"Forty",
"Fifty",
"Sixty",
"Seventy",
"Eighty",
"Ninety" };
static string[] Ones = new string[] {
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten",
"Eleven",
"Twelve",
"Thirteen",
"Fourteen",
"Fifteen",
"Sixteen",
"Seventeen",
"Eighteen",
"Nineteen"};
Feb 7, 2014
Finding The Date of Birth Using NIC No and The Logic Behind The NIC No
In this blog post Ill explain you the logic behind the Sri Lankan National Identity Card (NIC). Sri Lanka now has Old NIC No Format as well as a New NIC Format.
First of will see, how this NIC No is constructed. Lets take a simple example.
OLD 901912350V
NEW 199019102350
Old Format
New Format
But when calculating the month and date, you have to consider two things.
1. For all the years February month has 29 days.
2. For women's this three digits will start from 500. That means for women's this three digits has an additional 500.
Lets consider our example again. In my case its 191. So my birth month is July and date is 9th. So my birthday day is 1990-07-09. As I was mentioning above lets say a women born on the same day as our example. Then first five digits of her NIC No will be "90691" as per the old format and "1990691" as per the new format.
Before moving to particular programming language lets see the logical writing of the code.
First of all you need to verify the NIC No. So we need to do few validations.
Now lets come to the interesting part. Lets calculate this birth day using a simple HTML + jQuery program.
Lets try this code in browser.
Hope you got what you are looking for.
First of will see, how this NIC No is constructed. Lets take a simple example.
OLD 901912350V
NEW 199019102350
Old Format
- Old NIC Format consist of 9 numeric letters followed with alphabetic character.
- Only first five digits contains the date of birth logic.
- First two digits represents the born year. As you can see in the above example its "90". That means birth year is 1990.
- Then next three numeric digits represent the no of days to your birthday date from January 1.
New Format
- New NIC Format consist of 12 numeric letters only.
- Only first 7 digits contains the date of birth logic.
- First four digits represents the born year. As you can see in the above example its "1990". That means birth year is 1990.
- Then next three numeric digits represent the no of days to your birthday date from January 1.
1. For all the years February month has 29 days.
2. For women's this three digits will start from 500. That means for women's this three digits has an additional 500.
Lets consider our example again. In my case its 191. So my birth month is July and date is 9th. So my birthday day is 1990-07-09. As I was mentioning above lets say a women born on the same day as our example. Then first five digits of her NIC No will be "90691" as per the old format and "1990691" as per the new format.
Before moving to particular programming language lets see the logical writing of the code.
First of all you need to verify the NIC No. So we need to do few validations.
- Length of the NIC No : To support both the new and old format it should be either 10 or 12 Characters long.
- If character length is 10, that means its old format. So first nine digits has to be numeric, followed by an alphabetic letter.
- Range : If old format, three digits after first two digits has be in the range of either 1 to 366 or 501 to 866. If new format range same for the three digits after first four digits
Now lets come to the interesting part. Lets calculate this birth day using a simple HTML + jQuery program.
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 127 128 129 130 | <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <title>Easy Code Stuff - NIC Birth Day Finder</title> <script> $(document).ready(function () { $("#find").click(function () { //Clear Existing Details $("#error").html(""); $("#gender").html(""); $("#year").html(""); $("#month").html(""); $("#day").html(""); var NICNo = $("#nic").val(); var dayText = 0; var year = ""; var month = ""; var day = ""; var gender = ""; if (NICNo.length != 10 && NICNo.length != 12) { $("#error").html("Invalid NIC NO"); } else if (NICNo.length == 10 && !$.isNumeric(NICNo.substr(0, 9))) { $("#error").html("Invalid NIC NO"); } else { // Year if (NICNo.length == 10) { year = "19" + NICNo.substr(0, 2); dayText = parseInt(NICNo.substr(2, 3)); } else { year = NICNo.substr(0, 4); dayText = parseInt(NICNo.substr(4, 3)); } // Gender if (dayText > 500) { gender = "Female"; dayText = dayText - 500; } else { gender = "Male"; } // Day Digit Validation if (dayText < 1 && dayText > 366) { $("#error").html("Invalid NIC NO"); } else { //Month if (dayText > 335) { day = dayText - 335; month = "December"; } else if (dayText > 305) { day = dayText - 305; month = "November"; } else if (dayText > 274) { day = dayText - 274; month = "October"; } else if (dayText > 244) { day = dayText - 244; month = "September"; } else if (dayText > 213) { day = dayText - 213; month = "Auguest"; } else if (dayText > 182) { day = dayText - 182; month = "July"; } else if (dayText > 152) { day = dayText - 152; month = "June"; } else if (dayText > 121) { day = dayText - 121; month = "May"; } else if (dayText > 91) { day = dayText - 91; month = "April"; } else if (dayText > 60) { day = dayText - 60; month = "March"; } else if (dayText < 32) { month = "January"; day = dayText; } else if (dayText > 31) { day = dayText - 31; month = "Febuary"; } // Show Details $("#gender").html("Gender : " + gender); $("#year").html("Year : " + year); $("#month").html("Month : " + month); $("#day").html("Day :" + day); } } }); }); </script> </head> <body> <center> <p style="color: #000;">NIC Birth Day Finder</p> <p style="color: #000;">Both New & Old Format</p> <input type="text" id="nic" /> <button id="find">Find</button> <br/> <br/> <p id="error" style="color: red;"></p> <p id="gender" style="color: #000;"></p> <p id="year" style="color: #000;"></p> <p id="month" style="color: #000;"></p> <p id="day" style="color: #000;"></p> </center> </body> </html> |
Lets try this code in browser.
Hope you got what you are looking for.
Feb 4, 2014
Changing Form Data From Another Form
This Example Shows How To Access Data Of Form From Another Form.
By Using This Method You Can Call A Method Or You Can Set Text To TextBox Also.
Normally After Creating A Sub Class You May Have To Access The Parent Class Text Field In Order To Set Or Get The Text To It.Following Example Shows How To Do This.
In My Example I'm Assuming I've Two Forms Called MyForm1 and MyForm2.
MyForm1 Opens The MyForm2.
MyForm1 Have Two Text Fields Called txtInvoiceNo, txtFullName
First Of All Create The Two Forms As Above.
Then We Have To Make The Form1 As Parent Class In Form2.
In Order To Do That We Have To Pass The Form2 Object That Created In Form1(Simply The Form2 Object To Show The Form2)
In Your Form1 You Can Open The Form2 By Clicking A Button Or Any Other Event.Use Following Codes To Do That.Paste The Following Codes In The Event You Are Going To Open The Form2 in Form1.
MyForm2 formMyForm2 = new MyForm2();
formMyForm2.Show();
formMyForm2.RegisterParent(this);//This Code Unit Help To Access This Form From A Object
Add The Following Code Lines Inside The Form2.This Has A MyForm1 Class Object and A Method To Get The Parent Class Object.
private MyForm1 _parent;
internal void RegisterParent(MyForm1 form)
{
this._parent = form;
}
Now You Can Set Your Values From MyForm2 to MyForm1
I'm Using A Button Click Example To Show It.
private void btnAdd_Click(object sender, EventArgs e)
{
//Adding Values To MyForm1
_parent.txtInvoiceNo.Text = "Your Set Code Goes Here";
_parent.txtFullName.Text = "Your Set Code Goes Here";
}
By Using This Method You Can Call A Method Or You Can Set Text To TextBox Also.
Normally After Creating A Sub Class You May Have To Access The Parent Class Text Field In Order To Set Or Get The Text To It.Following Example Shows How To Do This.
In My Example I'm Assuming I've Two Forms Called MyForm1 and MyForm2.
MyForm1 Opens The MyForm2.
MyForm1 Have Two Text Fields Called txtInvoiceNo, txtFullName
First Of All Create The Two Forms As Above.
Then We Have To Make The Form1 As Parent Class In Form2.
In Order To Do That We Have To Pass The Form2 Object That Created In Form1(Simply The Form2 Object To Show The Form2)
In Your Form1 You Can Open The Form2 By Clicking A Button Or Any Other Event.Use Following Codes To Do That.Paste The Following Codes In The Event You Are Going To Open The Form2 in Form1.
MyForm2 formMyForm2 = new MyForm2();
formMyForm2.Show();
formMyForm2.RegisterParent(this);//This Code Unit Help To Access This Form From A Object
Add The Following Code Lines Inside The Form2.This Has A MyForm1 Class Object and A Method To Get The Parent Class Object.
private MyForm1 _parent;
internal void RegisterParent(MyForm1 form)
{
this._parent = form;
}
Now You Can Set Your Values From MyForm2 to MyForm1
I'm Using A Button Click Example To Show It.
private void btnAdd_Click(object sender, EventArgs e)
{
//Adding Values To MyForm1
_parent.txtInvoiceNo.Text = "Your Set Code Goes Here";
_parent.txtFullName.Text = "Your Set Code Goes Here";
}
Change Form Events From Another Form(Hide,Close,Show)
When Ever You Want To Do Any Events Like Hide,Close,Show Of A Form From Another Form You Can Use Following Code.
When Ever Dispose a Object In A Form From Another Form Make Sure All The Child Class Objects Relevant To That Object Are Closed.
for (int index = Application.OpenForms.Count - 1; index >= 0; index--)
{
if (Application.OpenForms[index].Name == "Your Form Name")
{
Application.OpenForms[index].Close();//To Close
}
else if (Application.OpenForms[index].Name == "Your Form Name")
{
Application.OpenForms[index].Hide();//To Hide
}
else if (Application.OpenForms[index].Name == "Your Form Name")
{
Application.OpenForms[index].Show();//To Show
}
}
When Ever Dispose a Object In A Form From Another Form Make Sure All The Child Class Objects Relevant To That Object Are Closed.
for (int index = Application.OpenForms.Count - 1; index >= 0; index--)
{
if (Application.OpenForms[index].Name == "Your Form Name")
{
Application.OpenForms[index].Close();//To Close
}
else if (Application.OpenForms[index].Name == "Your Form Name")
{
Application.OpenForms[index].Hide();//To Hide
}
else if (Application.OpenForms[index].Name == "Your Form Name")
{
Application.OpenForms[index].Show();//To Show
}
}
Jan 14, 2014
Insert DataGridView Values In C# To A SqlServer Database Table
This Program Helps You To Insert Data Grid View Values To A Database.
In My Example I'm Considering A Data Grid View With Three Columns Named As ItemNo , ItemName, Qty.In My Example I Wanted To Insert All The DataGridView Rows To A Table Called Items Which Has ItemNo, ItemName, Qty Fields.Insertion Must Happened After Clicking The Save Button.
Make Sure Data Types In The Data Grid View Are Similar To The Data Types In The Database Table.
First Create A New Project and Add A DataGridView and A Button To It.Make Sure Your Data Grid View Id As MyDataGridView and Button Id As Save.Then Add Three Columns To That.You Can Add Columns To The DataGridView From Either Properties Window or from Code.
Before Doing The Codes Make Sure You Have The Sql Server Class As Follows.
(if you have any problem in SQL Connection refer to following post
http://easycodestuff.blogspot.com/2014/01/secure-best-sql-server-connection-for-c.html)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
namespace DataGridViewExample
{
class DBConnection
{
string strconnection = "Server=localhost;Uid=root;Pwd=;Database=yourdatabase;";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter sqlda = new SqlDataAdapter();
DataTable dt = new DataTable();
public void connect()
{
sqlcon = new SqlConnection(strconnection);
sqlcon.Open();
}
public void disconnect()
{
if (sqlcon.State == ConnectionState.Open)
{
sqlcon.Close();
sqlcon.Dispose();
}
}
public DataTable ReadData(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
sqlda = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
sqlda.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
return dt;
}
public void QryCommand(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
}
}
}
Make Sure Your Form Class Start With Following Code Lines.
namespace DataGridViewExample
{
class test {
private string query = "";
DBConnection connection = new DBConnection();
DataTable dt = new DataTable();
Finally You Have To Do Is Reading All The Rows Of The Data Grid View Thorough A Loop and Calling The Insert Query Inside The Same Loop.Following Code Unit Will Help You That.
private void BtnSave_Click(object sender, EventArgs e)//Save Button
{
for (int i = 0; i < MyDataGridView.RowCount; i++) // Run Until End Of MyDataGridView
{
query = "INSERT INTO Items(ItemNo,ItemName,Qty) VALUES('" +
MyDataGridView.Rows[i].Cells[0].Value.ToString() + "','" +
MyDataGridView.Rows[i].Cells[1].Value.ToString() + "','" +
MyDataGridView.Rows[i].Cells[2].Value.ToString() + "')";
connection.connect();
connection.QryCommand(query);
}
}
In My Example I'm Considering A Data Grid View With Three Columns Named As ItemNo , ItemName, Qty.In My Example I Wanted To Insert All The DataGridView Rows To A Table Called Items Which Has ItemNo, ItemName, Qty Fields.Insertion Must Happened After Clicking The Save Button.
Make Sure Data Types In The Data Grid View Are Similar To The Data Types In The Database Table.
First Create A New Project and Add A DataGridView and A Button To It.Make Sure Your Data Grid View Id As MyDataGridView and Button Id As Save.Then Add Three Columns To That.You Can Add Columns To The DataGridView From Either Properties Window or from Code.
Before Doing The Codes Make Sure You Have The Sql Server Class As Follows.
(if you have any problem in SQL Connection refer to following post
http://easycodestuff.blogspot.com/2014/01/secure-best-sql-server-connection-for-c.html)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
namespace DataGridViewExample
{
class DBConnection
{
string strconnection = "Server=localhost;Uid=root;Pwd=;Database=yourdatabase;";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter sqlda = new SqlDataAdapter();
DataTable dt = new DataTable();
public void connect()
{
sqlcon = new SqlConnection(strconnection);
sqlcon.Open();
}
public void disconnect()
{
if (sqlcon.State == ConnectionState.Open)
{
sqlcon.Close();
sqlcon.Dispose();
}
}
public DataTable ReadData(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
sqlda = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
sqlda.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
return dt;
}
public void QryCommand(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
}
}
}
Make Sure Your Form Class Start With Following Code Lines.
namespace DataGridViewExample
{
class test {
private string query = "";
DBConnection connection = new DBConnection();
DataTable dt = new DataTable();
Finally You Have To Do Is Reading All The Rows Of The Data Grid View Thorough A Loop and Calling The Insert Query Inside The Same Loop.Following Code Unit Will Help You That.
private void BtnSave_Click(object sender, EventArgs e)//Save Button
{
for (int i = 0; i < MyDataGridView.RowCount; i++) // Run Until End Of MyDataGridView
{
query = "INSERT INTO Items(ItemNo,ItemName,Qty) VALUES('" +
MyDataGridView.Rows[i].Cells[0].Value.ToString() + "','" +
MyDataGridView.Rows[i].Cells[1].Value.ToString() + "','" +
MyDataGridView.Rows[i].Cells[2].Value.ToString() + "')";
connection.connect();
connection.QryCommand(query);
}
}
Jan 10, 2014
C# How to Convert a String to a Number
decimal - ToDecimal(stringvariable)
float - ToSingle(stringvariable)
double - ToDouble(stringvariable)
int - ToInt(stringvariable)
string stringvalriable="1001";
int intvariable = Convert.ToInt(stringvariable);
float - ToSingle(stringvariable)
double - ToDouble(stringvariable)
int - ToInt(stringvariable)
string stringvalriable="1001";
int intvariable = Convert.ToInt(stringvariable);
Jan 9, 2014
C# Load Data Into Data Grid On ComboBox Select Changed
private void COMBOBOXNAME_SelectedIndexChanged(object sender, EventArgs e)
{
string Selecteditem = COMBOBOXNAME.Items[COMBOBOXNAME.SelectedIndex].ToString();
string ConnectionString = @"Server=localhost;Database=dbname;Trusted_Connection=True";
SqlConnection con = new SqlConnection(ConnectionString);
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex )
{
MessageBox.Show(ex.Message);
}
SqlCommand command = con.CreateCommand()
command.CommandText = "SELECT * from Test";
int iCount =0;
SqlDataReader reader = command.ExecuteReader();
DGName.Rows.Clear();
while (reader.Read())
{
DGName.Rows.Add();
DGName.Rows[iCount].Cells[0].Value = iCount + 1; // row number will be added
DGName.Rows[iCount].Cells[1].Value = reader["DBColumnName"].ToString();
DGName.[iCount].Cells[2].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[3].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[4].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[5].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[6].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[7].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[8].Value = reader["DBColumnName"].ToString();
iCount++;
}
reader.Close();
con.Close();
}
//DGName : Wnter Your Data Grid Name
//iCount : Counts The Rows
//COMBOBOXNAME : Enter Your ComboBoxName
{
string Selecteditem = COMBOBOXNAME.Items[COMBOBOXNAME.SelectedIndex].ToString();
string ConnectionString = @"Server=localhost;Database=dbname;Trusted_Connection=True";
SqlConnection con = new SqlConnection(ConnectionString);
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex )
{
MessageBox.Show(ex.Message);
}
SqlCommand command = con.CreateCommand()
command.CommandText = "SELECT * from Test";
int iCount =0;
SqlDataReader reader = command.ExecuteReader();
DGName.Rows.Clear();
while (reader.Read())
{
DGName.Rows.Add();
DGName.Rows[iCount].Cells[0].Value = iCount + 1; // row number will be added
DGName.Rows[iCount].Cells[1].Value = reader["DBColumnName"].ToString();
DGName.[iCount].Cells[2].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[3].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[4].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[5].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[6].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[7].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[8].Value = reader["DBColumnName"].ToString();
iCount++;
}
reader.Close();
con.Close();
}
//DGName : Wnter Your Data Grid Name
//iCount : Counts The Rows
//COMBOBOXNAME : Enter Your ComboBoxName
Subscribe to:
Posts (Atom)
JWT Token Decode Using Jquery
When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...
-
In this blog post Ill explain you the logic behind the Sri Lankan National Identity Card (NIC). Sri Lanka now has Old NIC No Format as well ...
-
In This Article I Will Demonstrate You To Create A Simple Chat Program Using Java Remote Method Invocation(RMI). Following Program Supports ...
-
In a windows form application sometimes you may want to import a excel file to a data grid view. In this blog post Ill demonstrate to you gu...