C#.Net [Tips & FAQ]
Blog Archive
My Links
- C# Snippets: 1
- C# Snippets: 2
- XMLFOX - CSHARP SAMPLES
- Q: Export your Crystal Report data to PDF
- Q: To create a Excel report wihtout using Excel object model Ex
- Q: Using C#, How to Save,Update Data to and from XML with out using the sql server database
- Q: upload excel to SQL using C#.net,VS2005
- Q: Export DataTable to Excel using c# with Formatting Styles
- Q: Crystal report in c# .Net
- Q: Import excel into Sql server 2005 Table
- Q: READ, UPDATE & DELETE XML FILE USING X-PATH
- Q: Export Data from Listview to Excel
- Q: About GridView Data To Excel C#
- Q: Simple way to convert excel sheet to sql table
- Q: How to send data from c# file(.cs) to xslt file
- Q: How to Export and import data from sqlserver to excel sheet in vb.net
- Q: Migration of data from access to excel and vice versa
- Q: How to insert the data from excel to Database in .Net?
- Q: How can we create excel sheet in c# using data grid
- Q: DateTime Value Manipulation
- Q: create an array from a txt file
- Q: HowtoOepnandReadanExcelSpreadsheetinaListViewin.NET
- Q: How to fill data to excel
- Q: Reading Image from Excel file using C# .Net
- C# / CSharp Tutorial
- stackoverflow.com/questions
- General .NET Projects
- Sample .NET Projects with source code
- CSharpArticles
- PHPManual
- phpmanual/en/install.windows
- ProtoPage
Tuesday, December 14, 2010
Mathematical Functions in .NET
Math.Abs() Returns the absolute value.
Math.Abs(-10) returns 10.
Math.Ceiling() Returns an integer that is greater than or equal to a number.
Math.Ceiling(5.333) returns 6.
Fix() Returns the integer portion of a number.
Fix(5.3333) returns 5.
Math.Floor() Returns an integer that is less than or equal to a number.
Fix(5.3333) returns 5.
Int() Returns the integer portion of a number.
Int(5.3333) returns 5.
Math.Max() Returns the larger of two numbers.
Math.Max(5,7) returns 7.
Math.Min() Returns the smaller of two numbers.
Math.Min(5,7) returns 5.
Math.Pow() Returns a number raised to a power.
Math.Pow(12,2) returns 144.
Rnd() Returns a random number between 0 and 1. Used in conjunction with Randomizestatement to initialize the random number generator.
Math.Round() Rounds a number to a specified number of decimal places. Rounds up on .5.
Math.Round(1.1234567,5) returns 1.12346.
Math.Sign() Returns the sign of a number. Returns -1 if negative and 1 if positive.
Math.Sign(-5) returns -1.
Math.Sqrt() Returns the square root of a positive number.
Math.Sqrt(144) returns 12.
String Functions in .NET
Several built-in string functions used to perform string manipulations
Function in ASP.NET
Asc() Returns the character code of the first character of a string.
Asc("A") returns 65.
Chr() Returns the display character of a character code.
Chr(65) returns "A".
GetChar() Returns the character at a specified position in a string, counting from 1.
GetChar("This is a string", 7) returns "s".
InStr() Returns the starting position in a string of a substring, counting from 1.
InStr("This is a string", "string") returns 11.
InStrRev() Returns the starting position in a string of a substring, searching from the end of the string.
InStr("This is a string", "string") returns 11.
LCase() Returns the lower-case conversion of a string.
LCase("THIS IS A STRING") returns "this is a string".
Left() Returns the left-most specified number of characters of a string.
Left("This is a string", 4) returns "This".
Len() Returns the length of a string.
Len("This is a string") returns 16.
LTrim() Removes any leading spaces from a string.
LTrim(" This is a string") returns "This is a string".
Mid() Returns a substring from a string, specified as the starting position (counting from 1) and the number of characters.
Mid("This is a string", 6, 4) returns "is a".
Replace() Replaces all occurences of a substring in a string.
Replace("This is a string", " s", " longer s") returns "This are a longer string" (replaces an "s" preceded by a blank space).
Right() Returns the right-most specified number of characters of a string.
Right("This is a string", 6) returns "string".
RTrim() Removes any trailing spaces from a string.
RTrim("This is a string ") returns "This is a string".
Str() Returns the string equivalent of a number.
Str(100) returns "100".
Space() Fills a string with a given number of spaces.
"This" & Space(5) & "string" returns "This string".
StrComp() Compares two strings. Return values are 0 (strings are equal), 1 (first string has the greater value), or -1 (second string has the greater value) based on sorting sequence.
StrComp("This is a string", "This string") returns -1.
StrReverse() Reverses the characters in a string.
StrReverse("This is a string") returns "gnirts a si sihT".
Trim() Removes any leading and trailing spaces from a string.
Trim(" This is a string ") returns "This is a string".
UCase() Returns the upper-case conversion of a string.
UCase("This is a string") returns "THIS IS A STRING".
Val() Converts a numeric expression to a number.
Val( (1 + 2 + 3)^2 ) returns 36.
Tips for Stored Procedures Optimization
Use stored procedures instead of heavy-duty queries.
Include the SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a Transact-SQL statement.
*****************************************************************
Call stored procedure using its fully qualified name.
*****************************************************************
Consider returning the integer value as an RETURN statement instead of an integer value as part of a recordset.
Don't use the prefix "sp_" in the stored procedure name if you need to create a stored procedure to run in a database other than the master database.
Using temporary tables inside stored procedure reduces the chance to reuse the execution plan.
Using DDL statements inside stored procedure reduces the chance to reuse the execution plan.
Tuesday, November 23, 2010
Create/Remove Controls In/From a Containers like GroupBox Dynamically
PROBLEM: The problem getting with "foreach" & "for
If u wana see my code:
-----------------------------------------------------------------------------------------------
public void RemoveCtrls()
{
//MessageBox.Show(gb_DataBox.Controls.Count.ToString());
//foreach (Control ctrl in gb_DataBox.Controls)
//{
//if (!(ctrl is Button))//(ctrl.GetType() == typeof(Button)) //(((Button)ctrl).Text != "Next")
//{
// MessageBox.Show(ctrl.GetType().Name + " : " + ctrl.Name.ToString());
// gb_DataBox.Controls.Remove(ctrl);
// ctrl.Dispose();
//}
// }
int c = gb_DataBox.Controls.Count;
//for (int i = 1; i < i =" c">= 0; i--)
{
if (!(gb_DataBox.Controls[i] is Button))
{
//if (gb_DataBox.Controls[i].GetType().ToString())//.EndsWith(".ctl1"))
MessageBox.Show(gb_DataBox.Controls[i].GetType().Name + " : " + gb_DataBox.Controls[i].Name.ToString());
gb_DataBox.Controls.Remove(gb_DataBox.Controls[i]);
}
}
}
private void btn_ConnectDB_Click(object sender, EventArgs e)
{
//Make Default values
y = 20;
gb_DataBox.Height = 100;//50;
RemoveCtrls();
//cn = new SqlConnection("Data Source=.;Initial Catalog=master;User ID=sa;Password=123");
query = txtQuery.Text;
try
{
cmd = new SqlCommand(query, cn);
if (cn.State == ConnectionState.Open)
cn.Close();
cn.Open();
dr = cmd.ExecuteReader();
lb = new Label[dr.FieldCount];
txt = new TextBox[dr.FieldCount];
for (int i = 0; i < lb.Length; i++)
{
lb[i] = new Label();
txt[i] = new TextBox();
lb[i].Text = dr.GetName(i);
lb[i].Name = dr.GetName(i);
txt[i].Name = dr.GetName(i);
lb[i].Location = new Point(100, y + 3);
txt[i].Location = new Point(200, y);
//MessageBox.Show(lb[i].Text.ToString());
//MessageBox.Show(txt[i].Name.ToString());
gb_DataBox.Controls.Add(lb[i]);
gb_DataBox.Controls.Add(txt[i]);
y += 30;
gb_DataBox.Height += txt[i].Height;// +3;
this.Height = groupBox2.Height + gb_QueryBox.Height + gb_DataBox.Height + 100;
//this.AutoScroll = true;
int c = gb_DataBox.Controls.Count;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
cn.Close();
}
btn_Next.Enabled = true;
}
private void btn_Next_Click(object sender, EventArgs e)
{
if (dr.Read())
{
for (int i = 0; i < lb.Length; i++)
txt[i].Text = dr.GetValue(i).ToString(); //dr[i].ToString();
}
else
{
MessageBox.Show("No More Records..");
cn.Close();
btn_Next.Enabled = false;
}
}
------------------------------------------------------------------------------------------------
Wednesday, September 8, 2010
DELEGATES AND EVENTS
delegate void Procedure();
class DelegateDemo
{
static void Method1()
{
Console.WriteLine("Method 1");
}
static void Method2()
{
Console.WriteLine("Method 2");
}
void Method3()
{
Console.WriteLine("Method 3");
}
static void Main()
{
Procedure someProcs = null;
someProcs += new Procedure(DelegateDemo.Method1);
someProcs += new Procedure(DelegateDemo.Method2);
DelegateDemo demo = new DelegateDemo();
someProcs += new Procedure(demo.Method3);
someProcs();
}
}
This statement is a complete abstraction. It does not result in executable code that does any work. It merely declares a delegate type called Procedure which takes no arguments and returns nothing. Next, in the Main() method, the statement Procedure someProcs = null; instantiates a delegate. Something concrete has now been created.
add two static methods to the delegate instance. (Note: the class name could have been left off of DelegateDemo.Method1 and DelegateDemo.Method2 because the statement is occurring in the DelegateDemo class.)
The statement someProcs += new Procedure(demo.Method3); adds a non-static method to the delegate instance.
Methods that have been added to a delegate instance can be removed with the -= operator:
someProcess -= DelegateDemo.Method1;
Note that if a delegate declaration specifies a return type and multiple methods are added to a delegate instance, then an invocation of the delegate instance returns the return value of the last method referenced. The return values of the other methods cannot be retrieved (unless explicitly stored somewhere in addition to being returned).
Events
delegate void ButtonClickedHandler();
class Button
{
public event ButtonClickedHandler ButtonClicked;
public void SimulateClick()
{
if (ButtonClicked != null)
{
ButtonClicked();
}
}
...
}
A method in another class can then subscribe to the event by adding one of its methods to the event delegate:
Button b = new Button();
b.ButtonClicked += MyHandler;
Even though the event is declared public, it cannot be directly fired anywhere except in the class containing the event.
Events are used extensively in GUI programming and in the System.Windows.Forms namespace.
Difference Between ToString() vs Convert.ToString() vs (string) cast
ToString() raise exception when the object is null
So in the case of object.ToString(), if object is null, it raise NullReferenceException.
Convert.ToString() return string.Empty in case of null object
(string) cast assign the object in case of null
So in case of MyObject o = (string)NullObject;
The StringBuilder and String classes provide ways to perform string manipulation. If your program requires many manipulations, then the StringBuilder class will likely be more efficient than using the String class. The String class provides an immutable object, which means that once the value of the string instance is set, it cannot be changed. Even though it appears that the application is changing the value of the string instance, it is actually returning a new instance of the String class in memory. For this reason, the StringBuilder class will likely cause less overhead in your application. This set of samples shows some basic manipulation using both the StringBuilder and String classes.
Contents:
The following examples will show how to use the StringBuilder class to append, insert, and replace text within a StringBuilder instance. It will also show how to use the String class to copy, split, and find a substring within a given String instance.
The self-extracting archive contains all source code for this set of samples. The file contains the following directories:
• Code: Contains subfolders for all the samples (see descriptions below):
• BuilderAppend
• BuilderInsert
• BuilderReplace
• StringCopy
• StringSplit
• StringSubstring
• Doc: Contains all documentation, including descriptions of samples, installation instructions, and information on how to use the sample application.
• Misc: Contains any additional files required to run the sample application.
How to Use
Run the self-extracting archive to install the sample files. All of the examples here are separate console applications that can be opened in Visual Studio.NET and run accordingly.
Description
StringBuilder.Append
The Append method takes the specified argument and appends it to the end of the existing value held in a StringBuilder object. This example is a console application that asks the user to input his/her name. The application takes the name entered by the user and appends it to the greeting that is held in the StringBuilder object Greeting. The Append method of the StringBuilder class has 19 overloads. This example uses the Append method of the String object to append Name to the Greeting. The StringBuilder Greeting is initialized with no value, and the value Good Morning is appended to the string representation. Next, the name the user enters is appended to this greeting with the code:
StringBuilder.Insert
The Insert method takes a specified argument and inserts the value at the specified location within the existing value of the StringBuilder object. This example is a console application similar to the Append example. The application takes the name entered by the user and inserts it at the specified location. The Insert method has 18 overloads. This example uses the Insert method of the String object to insert the name you enter after the words "Good Morning" and before the "!" with the following code:
The first argument is an integer value representing the location within the string to insert the value. The second argument is the value to insert into the existing string. If the integer value supplied is greater than the length of the string value contained within the StringBuilder object (for example, if the value 35 is entered here), an exception of type System.ArgumentOutOfRangeException will occur.
StringBuilder.Replace
The Replace method searches the existing string value and replaces all instances of the value with another specified value. This example builds on the Insert example by asking the user to also enter a nickname into the application. If the user has entered a name and a nickname, then the application will replace the original name with the nickname in the StringBuilder Greeting object with the following code:
String.Copy
The Copy method of the String class creates a new instance of a string with the same value as the string being copied. In this example the user enters some text, and that value is placed into a string object named inputText. The application copies this value into the new object named copiedText and appends some additional text in the following code:
string copiedText = string.Copy(myText);
copiedText+=" more text";
Notice that the Copy method is a static method of the String class and therefore is called using the class name and not the instance name.
String.Split and String.Join
The Split method identifies a substring within the specified string delimited by one or more characters. The substring values are placed into a string array. In this example, the string instance textOriginal contains the value "Value 1, Value 2, Value 3". The application calls the Split method and initializes the textarray string array with the following code:
The example then loops through all of the values in the array and writes them to the screen.
The Join method of the String class concatenates a specified character string within values of a string array and produces a single string. In this example, the textarray string array is re-joined using a ":" with the following code:
Notice that the Join method is a static method of the String class and therefore is called using the class name and not the instance name.
String.Substring
The Substring method returns a string representation from a specified start point. This method has two overloads where one method also accepts a length argument. In this example, a string is extracted from the original string instance beginning at the 4th character and having a length of 3.