How to read XML from a file by using Visual C#

 

View products that this article applies to.

This article was previously published under Q307548

On This Page

Expand all | Collapse all

SUMMARY

This article describes how to use the XmlTextReader class to read Extensible Mar…

This article describes how to use the XmlTextReader class to read Extensible Markup Language (XML) from a file. XmlTextReader provides direct parsing and tokenizing of XML and implements the XML 1.0 specification as well as the namespaces in the XML specification from the World Wide Web Consortium (W3C). This article provides fast, tokenized stream access to XML rather than using an object model such as the XML Document Object Model (DOM).

Back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:

  • Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET

This article assumes that you are familiar with the following topics:

  • XML terminology
  • Creating and reading an XML file

Back to the top

How to read XML from a file

This example uses a file named Books.xml. You can create your own Books.xml file or use the sample file that is included with the .NET Software Development Kit (SDK) QuickStarts in the following folder:

\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Samples\QuickStart\Howto\Samples\Xml\Transformxml\Cs

You must copy Books.xml to the \Bin\Debug folder, which is located under the folder in which you create this project. Books.xml is also available for download. See to the “References” section for the download location.

  1. Start Visual Studio 2005 or Visual Studio .NET.
  2. Create a new Visual C# Console Application. You proceed directly to the “Complete code listing” section or continue through these steps to build the application.
  3. Make sure that the project contains a reference to the System.Xml.dll assembly.
  4. Specify the using directive on the System.Xml namespace so that you are not required to qualify XmlTextReader declarations later in your code. You must use the using directive before any other declarations.

5. using System.Xml;

  1. Create an instance of an XmlTextReader object, and populate it with the XML file. Typically, the XmlTextReader class is used if you need to access the XML as raw data without the overhead of a DOM; thus, the XmlTextReader class provides a faster mechanism for reading XML. The XmlTextReader class has different constructors to specify the location of the XML data. The following code creates an instance of the XmlTextReader class and loads the Books.xml file. Add the following code to the Main procedure of Class1.

7. XmlTextReader reader = new XmlTextReader (“books.xml”);

  1. Read through the XML. (Note that this step demonstrates an outer “while” loop, and the next two steps demonstrate how to use that loop to read the XML.) After you create the XmlTextReader object, use the Read method to read the XML data. The Read method continues to move through the XML file sequentially until it reaches the end of the file, at which point the Read method returns a value of “False.”

9. while (reader.Read())

10. {

  1. 11.     // Do some work here on the data.
  2. 12.         Console.WriteLine(reader.Name);

13. }

14. Console.ReadLine();

  1. Inspect the nodes. To process the XML data, each record has a node type that can be determined from the NodeType property. The Name and Value properties return the node name (the element and attribute names) and the node value (the node text) of the current node (or record). The NodeType enumeration determines the node type. The following sample code displays the name of the elements and the document type. Note that this sample ignores element attributes.

16. while (reader.Read())

17. {

  1. 18.     switch (reader.NodeType)
  2. 19.     {
  3. 20.         case XmlNodeType.Element: // The node is an element.
  4. 21.             Console.Write(“<” + reader.Name);
  5. 22.    Console.WriteLine(“>”);
  6. 23.             break;
  7. 24.   case XmlNodeType.Text: //Display the text in each element.
  8. 25.             Console.WriteLine (reader.Value);
  9. 26.             break;
  10. 27.   case XmlNodeType. EndElement: //Display the end of the element.
  11. 28.             Console.Write(“</” + reader.Name);
  12. 29.    Console.WriteLine(“>”);
  13. 30.             break;
  14. 31.     }

32. }

  1. Inspect the attributes. Element node types can include a list of attribute nodes that are associated with them. The MovetoNextAttribute method moves sequentially through each attribute in the element. Use the HasAttributes property to test whether the node has any attributes. The AttributeCount property returns the number of attributes for the current node.

34. while (reader.Read())

35. {

  1. 36.        switch (reader.NodeType)
  2. 37.        {
  3. 38.            case XmlNodeType.Element: // The node is an element.
  4. 39.                Console.Write(“<” + reader.Name);
  5. 40.
  6. 41.                while (reader.MoveToNextAttribute()) // Read the attributes.
  7. 42.                    Console.Write(” ” + reader.Name + “='” + reader.Value + “‘”);
  8. 43.       Console.WriteLine(“>”);
  9. 44.                break;
  10. 45.      case XmlNodeType.Text: //Display the text in each element.
  11. 46.                Console.WriteLine (reader.Value);
  12. 47.                break;
  13. 48.      case XmlNodeType. EndElement: //Display the end of the element.
  14. 49.                Console.Write(“</” + reader.Name);
  15. 50.       Console.WriteLine(“>”);
  16. 51.                break;
  17. 52.        }
  18. 53.    }
  1. Save and close your project.

Back to the top

Complete code listing

using System;

using System.Xml;

 

namespace ReadXMLfromFile

{

/// <summary>

/// Summary description for Class1.

/// </summary>

class Class1

{

static void Main(string[] args)

{

XmlTextReader reader = new XmlTextReader (“books.xml”);

while (reader.Read())

{

switch (reader.NodeType)

{

case XmlNodeType.Element: // The node is an element.

Console.Write(“<” + reader.Name);

Console.WriteLine(“>”);

break;

case XmlNodeType.Text: //Display the text in each element.

Console.WriteLine (reader.Value);

break;

case XmlNodeType.EndElement: //Display the end of the element.

Console.Write(“</” + reader.Name);

Console.WriteLine(“>”);

break;

}

}

Console.ReadLine();

}

}

}

Back to the top

Sample output

<bookstore>

<book>

<title>

The Autobiography of Benjamin Franklin

</title>

<author>

<first-name>

Benjamin

</first-name>

<last-name>

Franklin

</last-name>

</author>

<price>

8.99

</price>

</book>

<book>

<title>

The Confidence Man

</title>

<author>

<first-name>

Herman

</first-name>

<last-name>

Melville

</last-name>

</author>

<price>

11.99

</price>

</book>

<book>

<title>

The Gorgias

</title>

<author>

<name>

Plato

</name>

</author>

<price>

9.99

</price>

</book>

</bookstore>

Back to the top

Troubleshooting

When you test the code, you may receive the following exception error message: Unhandled Exception: System.Xml.XmlException: Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it.

Additional information: System error. The exception error occurs on the following line of code: While

(reader.Read())

The exception error is caused by an invalid processing instruction. For example, the processing instruction may contain extraneous spaces. The following is an example of an invalid processing instruction:

<?xml version=’1.0′ ?>

This xml tag has a space preceding the ‘<’ bracket. Remove the preceding whitespace to resolve the error.

Back to the top

REFERENCES

The following file is available for download from the Microsoft Download Center:

Collapse this imageExpand this image

 

Download the Books.exe package now. (http://download.microsoft.com/download/xml/utility/1.0.0.1/wxp/en-us/books.exe)

For more information about .NET Framework XML classes and C#, visit the following Microsoft Developer Network (MSDN) Web site:

http://msdn.microsoft.com/en-us/magazine/cc302158.aspx (http://msdn.microsoft.com/en-us/magazine/cc302158.aspx)

For more information about the XmlReader class, visit the following MSDN Web site:

http://msdn2.microsoft.com/en-us/library/system.xml.xmlreader(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/system.xml.xmlreader(vs.71).aspx)

For more information about how to use XmlReader to read XML data, visit the following MSDN Web sites:

http://msdn2.microsoft.com/en-us/library/aa720470(VS.71).aspx (http://msdn2.microsoft.com/en-us/library/aa720470(VS.71).aspx)

http://msdn2.microsoft.com/en-us/library/tfz3cz6w(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/tfz3cz6w(vs.71).aspx)

For more general information about Visual C# .NET or XML in .NET, see the following Usenet newsgroups:

microsoft.public.dotnet.languages.csharp (http://go.microsoft.com/fwlink/?linkid=5217)

microsoft.public.dotnet.xml (http://msdn.microsoft.com/newsgroups/default.aspx?dg=microsoft.public.dotnet.xml&lang=en&cr=US)

 

Advertisements

C# String Functions and Manipulation

 

Trim Function

The trim function has three variations Trim, TrimStart and TrimEnd. The first example show how to use the Trim(). It strips all white spaces from both the start and end of the string.

//STRIPS WHITE SPACES FROM BOTH START + FINSIHE
string Name = ” String Manipulation ” ;
string NewName = Name.Trim();
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show(“[“+ NewName + “]”);

TrimEnd

TrimEnd works in much the same way but u are stripping characters which you specify from the end of the string, the below example first strips the space then the n so the output is String Manipulatio.

//STRIPS CHRS FROM THE END OF THE STRING
string Name = ” String Manipulation ” ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {‘ ‘,’n’};
string NewName = Name.TrimEnd(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show(“[“+ NewName + “]”);

TrimStart

TrimStart is the same as TrimEnd apart from it does it to the start of the string.

//STRIPS CHRS FROM THE START OF THE STRING
string Name = ” String Manipulation ” ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {‘ ‘,’S’};
string NewName = Name.TrimStart(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show(“[“+ NewName + “]”);

Find String within string

Ads by TechClicks

This code shows how to search within a string for a sub string and either returns an index position of the start or a -1 which indicates the string has not been found.

string MainString = “String Manipulation”;
string SearchString = “pul”;
int FirstChr = MainString.IndexOf(SearchString);
//SHOWS START POSITION OF STRING
MessageBox.Show(“Found at : ” + FirstChr );

Replace string in string

Below is an example of replace a string within a string. It replaces the word Manipulatin with the correct spelling of Manipulation.

string MainString “String Manipulatin”;
string CorrectString = MainString.Replace(“Manipulatin”, “Manipulation”);
//SHOW CORRECT STRING
MessageBox.Show(“Correct string is : ” + CorrectString);

Strip specified number of characters from string

This example show how you can strip a number of characters from a specified starting point within the string. The first number is the starting point in the string and the second is the amount of chrs to strip.

string MainString = “S1111tring Manipulation”;
string NewString = MainString.Remove(1,4);

//SHOW OUTPUT
MessageBox.Show(NewSring);

Split string with delimiter

The example below shows how to split the string into seperate parts via a specified dilemeter. The results get put into the Split array and called back via Split[0].

string MainString = “String Manipulation”;
string [] Split = MainString.Split(new Char [] {‘ ‘});
//SHOW RESULT
MessageBox.Show(Convert.ToString(Split[0]));
MessageBox.Show(Convert.ToString(Split[1]));

Convert to title (proper) case

This is a simple extension method to convert a string to Proper Case or Title Case (ie the first character of each word is made upper case).

public static string ToTitleCase(this string title)

{

CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;

TextInfo textInfo = cultureInfo.TextInfo;

return textInfo.ToTitleCase(title);

}

String Concatenation

String concatenation is the act of combining two strings by adding the contents of one string to the end of another. Earlier in this tutorial we considered string operations including using the concatenation operator (+). We used the following example:

string start = “This is a “;

string end = “concatenated string!”;

 

string concat = start + end;    // concat = “This is a concatenated string!”

The String class also provides a method for concatenating strings. The Concat method allows many strings to be passed as arguments. The strings are joined together and a new, concatenated string is returned:

string start = “This is a “;

string end = “concatenated string!”;

 

string concat = string.Concat(start, end);

NB: As with previous string functions, the original strings are unchanged.

Inserting Strings into Strings

The String class provides a method that inserts one string into the middle of another. The Insert method acts upon an existing string variable or literal and requires two parameters. The first is an integer that indicates the position where the second string is to be inserted. This integer counts characters from the left with zero indicating that the insertion will be at the beginning of the string. The second parameter is the string to be inserted.

string template = “Please ask for  on arrival.”;

string tutor = “Lisa”;

 

Console.WriteLine(template.Insert(15, tutor));

 

// Outputs: “Please ask for Lisa on arrival.”

Removing Characters from a String

The Remove method allows characters to be deleted from a string, shortening the string accordingly. There are two overloads available. The first requires a single parameter to indicate the start position for the character removal. The second overload adds a second parameter specifying how many characters to delete. Any further characters are unaffected.

string sample = “The quick brown fox jumps over the lazy dog.”;

 

string result = sample.Remove(16);      // result = “The quick brown ”

result = sample.Remove(16, 24);         // result = “The quick brown dog.”

 

Extracting Text from a String

The String class provides a useful function to extract a piece of text from the middle of a string. This method has two overloads that are very similar to those of the Remove method. However, rather than removing the middle section of the string and keeping the start and end, the Substring method discards the start and end and returns the middle section. The following code illustrates this using the same parameters as the previous example.

string sample = “The quick brown fox jumps over the lazy dog.”;

 

string result = sample.Substring(16);   // result = “fox jumps over the lazy dog.”

result = sample.Substring(16, 24);      // result = “fox jumps over the lazy ”

Search and Replace

All modern word processors and text editors include a search and replace function that permits a specified piece of text to be substituted with a second string. This functionality is provided by the Replace method. The method accepts two parameters. The first is the string to search for and the second is the string to use as a substitute. When executed, all instances of the first string are automatically replaced.

string sample = “The brown fox.”;

 

string result = sample.Replace(“brown”, “red”);   // result = “The red fox.”

Copying Strings

The final simple string manipulation function to be considered in this article is the Copy method. This method creates a copy of an existing string. It provides the same functionality as assigning to a string directly.

string sample = “The brown fox.”;

 

string result = string.Copy(sample);    // result = “The brown fox.”

 

Equality and Inequality Operators

In an earlier part of the C# Fundamentals tutorial we discussed the equality (==) and inequality (!=) relational operators. These operators allow an exact, case-sensitive comparison of two strings. In the case of the equality operator, if the strings match, the resultant Boolean value is true. If they are different the result is false. The inequality operator returns the opposite result, as shown below:

string s1 = "String to compare.";
string s2 = "String to compare.";
string s3 = "String to Compare.";   // Note the capital 'C'
bool result;

result = s1 == s2;                  // result = true
result = s1 == s3;                  // result = false
result = s1 != s2;                  // result = false
result = s1 != s3;                  // result = true

These operators are useful but have limitations. They do not allow you to consider the equality of two strings that match in all but capitalisation or other cultural factors. Nor do they allow you to determine that one string is greater than another. This article explains the methods that are provided to solve these problems.

Relative Comparison  & CompareTo Method

The .NET framework provides a method named CompareTo for many data types, including strings. It allows two values to be compared and returns a result that indicates not only if they are equal but also which is the greater when they are not. The method considers cultural information when comparing strings. For example, Japanese katakana characters can be written in two ways, half-width or full-width. The CompareTo method considers characters written as full-width to be equal to the same half-width characters. The same cultural information is used to determine which string is the greater.

The CompareTo method operates against an existing string. The string that it is to be compared with is passed to a parameter. The method returns an integer indicating the result of the comparison as follows:

Return Value

Meaning

    Zero                                   The strings are equal.
Less than Zero                            The first string is less than the second.
More than Zero            The first is greater than the second or the second string is null.

This can be clarified with an example:

string animal1 = "Cat";
string animal2 = "Dog";
int result;

result = animal1.CompareTo("Cat");          // result is zero
result = animal2.CompareTo("Cat");          // result is greater than zero
result = animal1.CompareTo(animal2);        // result is less than zero

NB: As this method is called against an existing string instance, if the string is null an exception occurs:

string animal = null;
int result;

result = animal.CompareTo("Cat");           // Causes an exception

 

Compare Method

The Compare function is a static method of the string class. It provides similar functionality to CompareTo but allows more options to be specified. As a static member of the string class, both strings are passed as parameters.

string animal1 = "Cat";
string animal2 = "Dog";
int result;

result = String.Compare(animal1, "Cat");    // result is zero
result = String.Compare(animal2, "Cat");    // result is greater than zero
result = String.Compare(animal1, animal2);  // result is less than zero

Null Comparison

The CompareTo method raises an exception if the string that is being tested is null because a null object has no available methods. However, as the Compare method is static, null strings can be compared.

string animal = "Cat";
int result;

result = String.Compare(animal, null);      // result is greater than zero
result = String.Compare(null, animal);      // result is less than zero
result = String.Compare(null, null);        // result is zero

Case Sensitivity

The Compare method allows you to decide whether to perform case-sensitive or case-insensitive comparisons. The differentiation between upper case and lower case lettering is applied according to the user’s language settings. To determine whether to use case-sensitive comparison a third, Boolean parameter is used. If the value is true, character casing is ignored. If false, the effect is the same as not supplying the parameter at all; the test is case-sensitive.

This example assumes UK English settings:

string animal1 = "Cat";
string animal2 = "cat";                             // Note use of lower case
int result;

result = String.Compare(animal1, animal2, true);    // Strings are equal
result = String.Compare(animal1, animal2, false);   // Strings are not equal

The Compare method includes overloaded versions allowing the comparison of strings using further international language settings, as well as options for comparing parts of strings. These are beyond the scope of this tutorial but are worth exploring. More information can be found at the MSDN definition of String.Compare web page.

CompareOrdinal Method

The CompareOrdinal static method allows case-sensitive comparison of two strings. It differs from Compare in that the comparison result is based upon the numeric Unicode values for each character. As the importance of characters in a cultural context can be different to the fixed numeric ordering of Unicode, different results may occur when comparing using this method. This is shown in the following example, which assumes a UK English configuration:

string animal1 = "Cat";
string animal2 = "cat";                             // Note use of lower case
int result;

result = String.Compare(animal1, animal2);      //result is greater than zero
result = String.CompareOrdinal(animal1, animal2); // result is less than zero

Equals Method

The Equals method is included for completeness. It returns a Boolean result indicating if two strings match, similar to the equality operator (==). The method can be used against a string object with a single parameter or as a static member with two parameters for the strings to be compared.

string animal = "Cat";
bool result;

result = animal.Equals("Cat");                      // result = true
result = animal.Equals("cat");                      // result = false
result = String.Equals(animal, "Cat");              // result = true
result = String.Equals(animal, "cat");              // result = false

NET 2.0 IsNullOrEmpty Method

Sometimes it is necessary to check if a string is either empty or is undefined (null). Using .NET 1.1, this would require two tests. The .NET framework 2.0 introduces a new static method, named IsNullOrEmpty, which performs both tests with one statement. The method returns true when the string is empty or null.

string animal1 = "Cat";
string animal2 = "";
string animal3 = null;
bool result;

result = String.IsNullOrEmpty(animal1);             // result = false
result = String.IsNullOrEmpty(animal2);             // result = true
result = String.IsNullOrEmpty(animal3);             // result = true

Retrieving a String’s Length

It is often necessary to check the length of a string, particularly to validate a user’s input. The String class provides a property named Length that gives us this information. The property returns an integer representing the number of characters present.

string animal = "Dog";
int result;

result = animal.Length;                     // result is 3
result = "Elephant".Length;                 // result is 8

NB: The Length property is efficient to execute. When checking if a string is empty, it is more efficient to check for zero length than to compare the string value to String.Empty or “”.

Locating Text Within a String

In an earlier article we examined the Substring method, which allows the extraction of characters from a specified position in a string. The reverse of this is to specify a series of characters and identify the position at which that sub-string appears within a string. This can be achieved with the IndexOf and LastIndexOf methods.

IndexOf takes a parameter containing a string to search for. If this exists within the main string the position of the first occurrence is returned. This position is known as the index and is an integer indicating the number of characters between the start of the string and the found text. If the search term appears at the start of the string the index is zero. Should the sub-string not exist within the main string the method returns -1.

LastIndexOf is similar to IndexOf. However, instead of returning the index of the first occurrence of the search term, LastIndexOf returns the position of the last occurrence.

string phrase = "The quick brown fox jumps over the lazy dog.";
int result;

result = phrase.IndexOf("brown");           // result is 10
result = phrase.LastIndexOf("dog");         // result is 40
result = phrase.IndexOf("green");           // result is -1
result = phrase.LastIndexOf("blue");        // result is -1

Specifying a Limited Search

IndexOf and LastIndexOf can be limited further by specifying a start position for the search. With IndexOf only occurrences of the specified sub-string at or to the right of this position are found. When using LastIndexOf, only matching sub-strings to the left of this position are located.

string phrase = "The quick brown fox jumps over the lazy dog.";
int result;

result = phrase.IndexOf("he");              // result is 1
result = phrase.IndexOf("he", 1);           // result is 1
result = phrase.IndexOf("he", 2);           // result is 32
result = phrase.LastIndexOf("he");          // result is 32
result = phrase.LastIndexOf("he",33);       // result is 32
result = phrase.LastIndexOf("he",32);       // result is 1

The search can be limited further with a third parameter. This parameter is an integer that indicates the maximum number of characters that may be examined. If a match does not exist within the range of characters the result returned is -1.

string phrase = "The quick brown fox jumps over the lazy dog.";
int result;

result = phrase.IndexOf("brown");           // result is 10
result = phrase.IndexOf("brown", 5, 4);     // result is -1
result = phrase.LastIndexOf("fox");         // result is 16
result = phrase.LastIndexOf("he", 25, 5);   // result is -1

Simple Container Tests

IndexOf and LastIndexOf are useful when determining the exact position of search terms within strings. However, sometimes it is enough to simply know that a sub-string exists. The String class provides several methods to perform this test.

StartsWith and EndsWith

StartsWith and EndsWith allow you to determine if a string starts or ends with a specific series of characters. Both methods accept an argument containing the string to match and return a Boolean value indicating the result. These methods are case-sensitive.

string phrase = "The quick brown fox jumps over the lazy dog.";
bool result;

result = phrase.StartsWith("The quick");    // result is true
result = phrase.StartsWith("lazy dog.");    // result is false
result = phrase.EndsWith("lazy dog.");      // result is true
result = phrase.EndsWith("The quick");      // result is false

.NET 2.0 Contains Method

The final string function considered in this article is Contains. Introduced in version 2.0 of the .NET framework, it operates in a similar manner to StartsWith and EndsWith but checks if the specified search term exists at any position within the main string.

string phrase = "The quick brown fox jumps over the lazy dog.";
bool result;

result = phrase.Contains("brown fox");      // result is true
result = phrase.Contains("lazy fox.");      // result is false

 

Windows Forms Example Topics

 

Code: Determining Which Control on a Form is Selected

This example displays the name of the currently selected Windows Forms control in a Label control.

Example

private void DisplayNameOfActiveControl()

{

label1.Text = this.ActiveControl.Name;

}

Compiling the Code

This example requires:

  • A form with a Label control named label1

Code: Adding Items to a ListBox Control

This example adds the contents of a Windows Forms TextBox control to a ListBox control when the TextBox control loses focus.

Example

private void textBox_Leave(object sender, System.EventArgs e)

{

listBox1.Items.Add(((TextBox)sender).Text);

}

Compiling the Code

This example requires:

  • A form with a ListBox control named listBox1 and three TextBox controls named textBox1, textBox2, and textBox3. Set each TextBox’s Leave event handler to textBox_Leave.

Note   This can also be used with a ComboBox control by substituting a ComboBox control named comboBox1 for the ListBox control and changing the code from listBox1 to comboBox1.

Robust Programming

To avoid duplicate entries in the list, you should search for a match before adding the contents of the TextBox to the list. For an example, see Code: Searching for an Item in a ListBox Control

 

 

Code: Searching for an Item in a ListBox Control

This example searches for a string in a Windows Forms ListBox control.

Example

private void button1_Click(object sender, System.EventArgs e)

{

listBox1.Items.Add(“One”);

listBox1.Items.Add(“Two”);

listBox1.Items.Add(“Three”);

 

if (listBox1.FindString(“Two”) != -1)

MessageBox.Show(“Found it!”);

}

Code: Selecting an Item in a ListBox Control

This example selects and highlights an item in a Windows Forms ListBox control.

Example

private void button1_Click(object sender, System.EventArgs e)

{

listBox1.Items.Add(“One”);

listBox1.Items.Add(“Two”);

listBox1.Items.Add(“Three”);

listBox1.SelectedIndex = listBox1.FindString(“Two”);

}

Compiling the Code

This example requires:

  • A form with a ListBox control named listBox1 and a Button control named button1. Set button1’s Click event handler to button1_Click.

Note   This can also be used with a ComboBox control by substituting a ComboBox control named comboBox1 for the ListBox control and changing the code from listBox1 to comboBox1.

Compiling the Code

This example requires:

  • A form with a ListBox control named listBox1 and a Button control named button1. Set button1’s Click event handler to button1_Click.

Note   This can also be used with a ComboBox control by substituting a ComboBox control named comboBox1 for the ListBox control and changing the code from listBox1 to comboBox1.

 

Code: Determining the Selected Item in a ListBox Control

This example determines which item has been selected in a Windows Forms ListBox control.

Example

private void Form1_Load(object sender, System.EventArgs e)

{

listBox1.Items.Add(“One”);

listBox1.Items.Add(“Two”);

listBox1.Items.Add(“Three”);

}

 

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)

{

if ((string)listBox1.SelectedItem == “Two”)

MessageBox.Show((string)listBox1.SelectedItem);

}

Compiling the Code

This example requires:

  • A form named Form1 with a ListBox control named listBox1. Set Form1’s Load event handler to Form1_Load. Set listBox1’s SelectedIndexChanged event handler to listBox1_SelectedIndexChanged.

Note   This can also be used with a ComboBox control by substituting a ComboBox control named comboBox1 for the ListBox control and changing the code from listBox1 to comboBox1.

 

Code: Populating a ListBox Control with an Array of Strings

This example adds an array of strings to a Windows Forms ListBox control.

Example

private void Form1_Load(object sender, System.EventArgs e)

{

string [] myList = new string[4];

 

myList[0] = “One”;

myList[1] = “Two”;

myList[2] = “Three”;

myList[3] = “Four”;

 

listBox1.Items.AddRange(myList);

}

 

Compiling the Code

This example requires:

  • A form named Form1 with a ListBox control named listBox1. Set Form1’s Load event handler to Form1_Load.

Note   This can also be used with a ComboBox control by substituting a ComboBox control named comboBox1 for the ListBox control and changing the code from listBox1 to comboBox1.

Robust Programming

The following conditions may cause an exception:

  • The array contains one or more null values.

Code: Converting the Text in a TextBox Control to an Integer

This example demonstrates two methods of converting text data to integer data.

Example

int anInteger;

anInteger = Convert.ToInt32(textBox1.Text);

anInteger = int.Parse(textBox1.Text);

Code: Determining the Selected Text in a TextBox Control

This example programmatically selects text in a Windows Forms TextBox control and retrieves the selected text.

Example

private void button1_Click(object sender, System.EventArgs e)

{

textBox1.Text = “Hello World”;

textBox1.Select(6, 5);

MessageBox.Show(textBox1.SelectedText);

}

Compiling the Code

This example requires:

  • A form with a TextBox control named textBox1 and a Button control named button1. Set button1’s Click event handler to button1_Click.

Note   This can also be used with a RichTextBox control by substituting a RichTextBox control named richTextBox1 for the TextBox control and changing the code from textBox1 to richTextBox1.

Code: Formatting Characters in Bold in a RichTextBox Control

This example adds the text “This text is in bold.” to an existing RichTextBox control.

Example

richTextBox1.Rtf = @”{\rtf1\ansi This is in \b bold\b0.}”;

Compiling the Code

This example requires:

  • A RichTextBox control named richTextBox1.

Code: Creating a Context Menu and Attaching it to a Control

This example programmatically creates a Windows Forms context menu and associates it with a control.

Example

private void Form1_Load(object sender, System.EventArgs e)

{

System.Windows.Forms.ContextMenu contextMenu1;

contextMenu1 = new System.Windows.Forms.ContextMenu();

System.Windows.Forms.MenuItem menuItem1;

menuItem1 = new System.Windows.Forms.MenuItem();

System.Windows.Forms.MenuItem menuItem2;

menuItem2 = new System.Windows.Forms.MenuItem();

System.Windows.Forms.MenuItem menuItem3;

menuItem3 = new System.Windows.Forms.MenuItem();

 

contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {menuItem1, menuItem2, menuItem3});

menuItem1.Index = 0;

menuItem1.Text = “MenuItem1”;

menuItem2.Index = 1;

menuItem2.Text = “MenuItem2”;

menuItem3.Index = 2;

menuItem3.Text = “MenuItem3”;

 

textBox1.ContextMenu = contextMenu1;

}

Compiling the Code

This example requires:

  • A Windows Form named Form1 and a TextBox control named textBox1. Set Form1’s Load event handler to Form1_Load

Code: Creating a Group of Radio Buttons from a String Array

This example programmatically creates a group of Windows Forms radio buttons and set their Text properties to values from an array of strings.

Example

private void button1_Click(object sender, System.EventArgs e)

{

string [] stringArray = new string[3];

 

stringArray[0] = “Yes”;

stringArray[1] = “No”;

stringArray[2] = “Maybe”;

 

System.Windows.Forms.RadioButton [] radioButtons = new System.Windows.Forms.RadioButton[3];

 

for(int i=0; i<3; ++i)

{

radioButtons[i] = new RadioButton();

radioButtons[i].Text = StringArray[i];

radioButtons[i].Location = new System.Drawing.Point(10, 10+i*20);

this.Controls.Add(radioButtons[i]);

}

}

Compiling the Code

This example requires:

  • A Windows Form with a Button control named button1. Set button1’s Click event handler to button1_Click.

Code: Creating a ToolTip for a Control

This example programmatically creates a ToolTip for a Windows Forms control.

Example

private void Form1_Load(object sender, System.EventArgs e)

{

System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();

ToolTip1.SetToolTip(this.textBox1, “Hello”);

}

Compiling the Code

This example requires:

  • A form named Form1 with a TextBox control named textBox1. Set Form1’s Load event handler to Form1_Load.

Code: Adding a Node to the Selected Node of a TreeView Control

This example adds one node to the selected node of an existing TreeView control.

Example

TreeNode node = treeView1.SelectedNode;

node.Nodes.Add(“New node below selected node”);

Code: Adding Nested Nodes to a TreeView Control

This example adds a first-level node and a second-level node to an existing TreeView control.

Example

TreeNode node = treeView1.Nodes.Add(“Level one node”);

node.Nodes.Add(“Level two node”);

Code: Determining the Selected Node in a TreeView Control

This example sets a reference to the selected node of existing TreeView control.

TreeNode node = treeView1.SelectedNode;

Compiling the Code

This example requires:

  • A TreeView control named treeView1.

Code: Adding Nodes to a TreeView Control

This example adds three first-level nodes to an existing TreeView control.

Example

treeView1.Nodes.Add(“First Node”);

treeView1.Nodes.Add(“Second Node”);

treeView1.Nodes.Add(“Third Node”);

Code: Databinding a DataTable of String Values to a Windows DataGrid Control

This example creates a data table with two columns and two rows and then binds it to an existing DataGrid control.

Example

DataTable dt = new DataTable();

dt.Columns.Add(new DataColumn(“Item”, typeof(string)));

dt.Columns.Add(new DataColumn(“Color”, typeof(string)));

dt.Rows.Add(new string[] {“table”, “brown”});

dt.Rows.Add(new string[] {“chair”, “white”});

dataGrid1.DataSource = dt;

Compiling the Code

This example requires:

  • A DataGrid control named dataGrid1.

Code: Databinding an Array of String Values to a Windows ListBox Control

This example adds three strings to an existing ListBox control.

Example

listBox1.DataSource = new string[] { “one”, “two”, “three” };

Compiling the Code

This example requires:

  • A ListBox control named listBox1.

Code: Determining the Selected Cell in a Windows DataGrid Control

This example sets a reference to the selected cell of an existing DataGrid control.

System.Windows.Forms.DataGridCell selectedCell = dataGrid1.CurrentCell;

Code: Displaying a Web Page from a LinkLabel Control

This example displays a Web page in the default browser when a user clicks a Windows Forms LinkLabel control.

Example

private void Form1_Load(object sender, System.EventArgs e)

{

linkLabel1.Text = “Click here to get more info.”;

linkLabel1.Links.Add(6, 4, “www.microsoft.com”);

}

private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)

{

System.Diagnostics.Process.Start(e.Link.LinkData.ToString());

}

Compiling the Code

This example requires:

  • A form named Form1 with a LinkLabel control named linkLabel1.
  • An active Internet connection.

Code: Displaying an OpenFileDialog Dynamically

 

This example instantiates and displays an OpenFileDialog control.

Example

OpenFileDialog openFile = new OpenFileDialog();

openFile.DefaultExt = “doc”;

// The Filter property requires a search string after the pipe ( | )

openFile.Filter = “Word documents (*.doc)|*.doc”;

openFile.ShowDialog();

if( openFile.FileNames.Length > 0 )

{

foreach( string filename in openFile.FileNames )

{

// Insert code here to process the files.

}

}

Robust Programming

You can use the FileOK event of the OpenFileDialog control to be certain that the user selected a file and clicked the OK button on the dialog box.

Use the CheckFileExists, CheckPathExists, DefaultExtension, Filter, Multiselect, and ValidateNames properties of the OpenFileDialog control to limit run-time errors.

Code: Displaying One Form from Another

 

This example displays a second form from another Windows Form.

Example

 

private void button1_Click(object sender, System.EventArgs e)

{

Form2 frm = new Form2();

frm.Show();

}

Compiling the Code

This example requires:

  • Two Windows Forms named Form1 and Form2. Form1 contains a Button control named button1. Set button1’s Click event handler to button1_Click.

Code: Displaying the Time in a StatusBar Control

 

This example displays the current time in hh:mm format in a StatusBar control.

Example

 

private void timer1_Tick(object sender, System.EventArgs e)

{

statusBar1.Panels[0].Text = DateTime.Now.ToShortTimeString();

}

Compiling the Code

The form must contain a Timer control with Enabled set to True, and a StatusBar with a Panel added to the Panels property and the ShowPanels property set to True.

The code is part of the event handler for the Timer control’s Tick event, as shown.

Robust Programming

The following conditions may cause an exception:

Code: Drawing Graphics on a Windows Form

 

This example draws a circle and a square on a form.

Example

 

System.Drawing.Graphics graphics = this.CreateGraphics();

System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(100, 100, 200, 200);

graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);

graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);

Compiling the Code

This code is to be added to a class that derives from System.Windows.Forms.Form. The this refers to the instance of the form

Code: Getting a Value from Another Form

This example retrieves a value from a text box on a Windows Form and displays it in a text box on another form.

Example

In Form1.cs:

private Form2 otherForm;

private void GetOtherFormTextBox()

{

textBox1.Text = otherForm.TextBox1.Text;

}

In Form2.cs:

 

public TextBox TextBox1

{

get

{

return textBox1;

}

}

Compiling the Code

This example requires:

  • Two forms named Form1 and Form2, each containing a TextBox control named textBox1. Form1 should create an instance of Form2 and assign it to otherForm; GetOtherFormTextBox will  the text in Form2’s textBox1 to Form1’s textBox1

Code: Hiding a DataColumn in a DataGrid Where the DataSource is a DataTable

 

This example hides the “X” column of a DataTable object that is displayed in an existing Windows Forms DataGrid control.

Example

 

private void HideColumnOfDataSet()

{

System.Data.DataTable points = new System.Data.DataTable(“Points”);

points.Columns.Add(new DataColumn(“X”, typeof(int)));

points.Columns.Add(new DataColumn(“Y”, typeof(int)));

points.Rows.Add(new object[]{1, 2});

points.Rows.Add(new object[]{3, 5});

dataGrid1.DataSource = points;

 

DataGridTableStyle tableStyle = new DataGridTableStyle();

tableStyle.MappingName = “Points”;

dataGrid1.TableStyles.Add(tableStyle);

dataGrid1.TableStyles[“Points”].GridColumnStyles[“X”].Width = 0;

}

Compiling the Code

This example requires:

  • A Windows Form with a DataGrid control named dataGrid1.

If the data source is a DataSet object, set the DataMember property of the DataGrid to the table’s name.

DataTable and DataColumn objects in typed datasets also have string-typed names. To find the name of the table, example the table’s Name property. To find the name of the DataColumn, examine the column’s Name property.

Robust Programming

The following conditions may cause an exception:

  • The MappingName property does not match the name of the DataTable (NullReferenceException Class).
  • Retrieving an item from the GridColumnStyles collection before the TableStyle is added to the DataGrid.TableStyles collection. The GridColumnStyles collection is filled when the TableStyle object is added to the TableStyles collection (NullReferenceException Class).
  • A TableStyle added to the DataGrid.TableStyles collection does not have a unique MappingName (ArgumentException Class).
  • The DataSource property of the DataGrid is not set before accessing the GridColumnStyles collection (NullReferenceException Class).

Code: Hiding a DataColumn in a DataGrid Where the DataSource is an Array

 

This example hides the “X” column of a DataGrid that uses an array of Point objects as the data source.

Example

 

private void HideColumnOfArray()

{

System.Drawing.Point [] points = { new Point(1, 2), new Point(3, 5), new Point(5, 6)};

dataGrid1.DataSource = points;

 

DataGridTableStyle tableStyle = new DataGridTableStyle();

tableStyle.MappingName = “Point[]”;

dataGrid1.TableStyles.Add(tableStyle);

dataGrid1.TableStyles[“Point[]”].GridColumnStyles[“X”].Width = 0;

}

Compiling the Code

This example requires:

  • A Windows Form with a DataGrid control named dataGrid1.

The MappingName, a string, is the type of the array with “[]” appended. Thus, if the data source is an array of Point objects, the mapping name is “Point[]”.

Robust Programming

The following conditions may cause an exception:

  • The MappingName property is not property formatted (NullReferenceException Class).
  • Retrieving an item from the GridColumnStyles collection before the TableStyle is added to the DataGrid.TableStyles collection. The GridColumnStyles collection is filled when the TableStyle object is added to the TableStyles collection (NullReferenceException Class).
  • A TableStyle added to the DataGrid.TableStyles collection does not have a unique MappingName (ArgumentException Class).
  • The DataSource property of the DataGrid is not set before accessing the GridColumnStyles collection (NullReferenceException Class).

Code: Hiding a DataColumn in a DataGrid Where the DataSource is an ArrayList

 

This example hides one column of a DataGrid that uses an ArrayList of Point objects as a data source.

Example

 

private void HideColumnOfArrayList()

{

System.Collections.ArrayList list = new System.Collections.ArrayList();

list.AddRange( new Point[]{ new Point(1, 2), new Point(3, 5), new Point(5, 6) } );

dataGrid1.DataSource = list;

DataGridTableStyle tableStyle = new DataGridTableStyle();

tableStyle.MappingName = “ArrayList”;

dataGrid1.TableStyles.Add(tableStyle);

object o = dataGrid1.TableStyles[“ArrayList”];

dataGrid1.TableStyles[“ArrayList”].GridColumnStyles[“X”].Width = 0;

}

Compiling the Code

This example requires:

  • A Windows Form with a DataGrid control named dataGrid1.

When the data source is an ArrayList object, the MappingName is “ArrayList”.

Robust Programming

The following conditions may cause an exception:

  • The MappingName property is not “ArrayList”(NullReferenceException Class).
  • Retrieving an item from the GridColumnStyles collection before the TableStyle is added to the DataGrid.TableStyles collection. The GridColumnStyles collection is filled when the TableStyle object is added to the TableStyles collection (NullReferenceException Class).
  • A TableStyle added to the DataGrid.TableStyles collection does not have a unique MappingName (ArgumentException Class).
  • All the objects in the ArrayList are not of the same type of the first item or a derived type of the first item (TargetInvocationException Class).
  • The DataSource property of the DataGrid is not set before accessing the GridColumnStyles collection (NullReferenceException Class).

Code: Retrieving an Image that is an Embedded Resource

This example retrieves an image that is an embedded resource of the assembly.

Example

System.Reflection.Assembly thisExe;

thisExe = System.Reflection.Assembly.GetExecutingAssembly();

System.IO.Stream file =

thisExe.GetManifestResourceStream(“AssemblyName.ImageFile.jpg”);

this.pictureBox1.Image = Image.FromStream(file);

Compiling the Code

This example requires:

  • A Windows Form with a PictureBox control named pictureBox1.

Add the image file to the project, and set the Build Action property to Embedded Resource in Solution Explorer.

Replace “AssemblyName.ImageFile.jpg” with the name of the resource, as it is known in the assembly. Use the GetManifestResourceNames method of the Assembly object to find the resource name. See Code: Finding the Names of Resources in an Assembly.

Robust Programming

The following conditions may cause an exception:

  • The embedded resource does not exist in the assembly, and the call to GetManifestResourceStream returns Nothing.
  • There may not be an application associated with the file type (the file extension).

Code: Retrieving the Data from the Selected Cell in a Windows DataGrid Control

This example retrieves the selected data in an existing DataGrid control filled with integer values.

Example

System.Windows.Forms.DataGridCell selectedCell = dataGrid1.CurrentCell;

object selectedItem = dataGrid1[selectedCell.RowNumber, selectedCell.ColumnNumber];

int cellValue = Convert.ToInt32(selectedItem);

Compiling the Code

This example requires:

  • A DataGrid control named dataGrid1.

Robust Programming

If the DataGrid is not bound to a data source, or if no cell is selected, then the selected cell is the cell in row 0 and column 0.

The following conditions may cause an exception:

Code: Selecting a Range of Dates in a Calendar Control

This example selects a range of dates in a Windows Forms MonthCalendar control. In this example, when the user selects a date the week is selected.

Example

private void monthCalendar1_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e)

{

DateTime startDate = e.Start;

startDate = startDate.AddDays(-(double)startDate.DayOfWeek);

monthCalendar1.SelectionStart = startDate;

monthCalendar1.SelectionEnd = startDate.AddDays(6);

}

Compiling the Code

This example requires:

  • A Windows Form with a MonthCalendar control named monthCalendar1. Set monthCalendar1’s DateSelected event handler to monthCalendar1_DateSelected.

Code: Changing the Background Color of a Form

This example changes the background color of a Windows Form programmatically.

Example

private void Form1_Click(object sender, System.EventArgs e)

{

this.BackColor = System.Drawing.Color.DarkBlue;

}

Compiling the Code

This example requires:

  • A form named Form1. Set Form1’s Click event handler to Form1_Click.

Web Applications Example Topics

 

Code: Adding Items to a List Control

This example uses the Add method of the ListBox.Items property to add items to the list.

Example

// Create a string array and assign items.

string[] ListContents = {“Enju”, “Sue”, “Mary”};

 

// Add the array items to the list box.

for (int i = 0; i <= ListContents.Length – 1; i++)

ListBox1.Items.Add(ListContents[i]);

Code: Removing Items From a List Control

This example uses the Remove method of the ListBox.Items property to remove an item from the list.

Example

ListBox1.Items.Remove(“Mary”);

Compiling the Code

Start a new ASP.NET Web application and do the following:

  • Add a list box named ListBox1.
  • Copy the code and paste it into the Page_Load method.

Code: Determining the Selected Item in a List Control

This example uses the SelectedIndex and SelectedItem properties of a List control to access information about the selected item.

Example

// The index:

int ListItemIndex;

// Value of the item:

string ListItemValue;

 

ListItemIndex = ListBox1.SelectedIndex;

ListItemValue = ListBox1.SelectedItem.Value.ToString();

Code: Selecting an Item in a List Control

This example uses the IndexOf method to search a list box for a specific text.

ListBox1.SelectedIndex = ListBox1.Items.IndexOf(ListBox1.Items.FindByText(“ValueToFind”));

 

Code: Adding Controls at Run Time

This example adds a text box and button to a Web Forms page at run time. It also dynamically binds an event handler to the button’s Click event. The handler displays the values of the dynamically generated text box.

The controls are added into a Panel Web server control, which acts as a placeholder. The controls are separated in the panel with line breaks (HTML <BR> elements), which are added to the panel using the LiteralControl control.

Example

private void Page_Load(object sender, System.EventArgs e)

{

if (!IsPostBack)

AddControls();

}

protected override void LoadViewState(object savedState)

{

base.LoadViewState(savedState);

if (ViewState[“controsladded”] == null)

AddControls();

}

private void AddControls()

{

TextBox dynamictextbox = new TextBox();

dynamictextbox.Text = “(Enter some text)”;

dynamictextbox.ID = “dynamictextbox”;

Button dynamicbutton = new Button();

dynamicbutton.Click += new System.EventHandler(dynamicbutton_Click);

dynamicbutton.Text = “Dynamic Button”;

Panel1.Controls.Add(dynamictextbox);

Panel1.Controls.Add(new LiteralControl(“<BR>”));

Panel1.Controls.Add(new LiteralControl(“<BR>”));

Panel1.Controls.Add(dynamicbutton);

ViewState[“controlsadded”] = true;

}

private void dynamicbutton_Click(Object sender, System.EventArgs e)

{

TextBox tb = new TextBox();

tb = (TextBox) (Panel1.FindControl(“dynamictextbox”));

Label1.Text = tb.Text;

}

Code: Displaying Data in a Web Forms DataGrid Control

This example uses the DataBind method to bind the contents of a dataset to a DataGrid control.

Example

if (!IsPostBack)

{

sqlDataAdapter1.Fill(dataSet11);

DataGrid1.DataBind();

}

Compiling the Code

This example requires:

  • A Web Forms page.
  • A DataGrid control named DataGrid1.
  • A typed dataset named dataSet11, which is an instance of the typed dataset class DataSet1.
  • A properly configured data adapter named sqlDataAdapter1. You can bind the DataGrid control to any Web Forms page data source.
  • The application must have permission to access the database. For details, see Using SQL Server in Web Applications.

Robust Programming

You can specify the DataGrid control’s DataSource property at design time in the Properties window. You do not have to specify it at run time, as is shown in the previous example.

You should always wrap data access calls in a try-catch block:

try

{

sqlDataAdapter1.Fill(dataSet11);

DataGrid1.DataBind();

}

catch

{

Label1.Text = “Unable to connect to the database.”;

}

You should bind the DataGrid control to its data source only when there is a change to the data or to the control’s state. Do not data bind the control on each round trip. In the previous example, the control is bound only the first time the page runs, not on every postback.

Web Forms pages often benefit by caching a dataset rather than requerying the database

Code: Passing Data from One Web Forms Page to Another

This example stores information in session state and navigates to another page in the same application, then retrieves the stored information in the second page.

Example

// First part: Saves info on first page.

string firstName = “John”;

string lastName = “Smith”;

string city = “Seattle”;

Session.Add(“First”, firstName);

Session.Add(“Last”, lastName);

Session.Add(“City”, city);

 

// Redirect to second page.

Server.Transfer(“WebForm2.aspx”);

 

// Second part: Reads info into variables on the second page.

string firstName = (string)(Session[“First”]);

string lastName = (string)(Session[“Last”]);

string city = (string)(Session[“City”]);

 

Compiling the Code

  • Start an ASP.NET application with two Web Forms pages, WebForm1.aspx and WebForm2.aspx.
  • Paste the first part of the code into the Page_Load method (or a Click method) of WebForm1.aspx.
  • Paste the second part of the code into the Page_Load method of WebForm2.aspx.

 

Code: Writing a Cookie

The following example uses the HttpCookie class and its properties to write a cookie that expires after one minute.

Example

HttpCookie myCookie = new HttpCookie(“MyTestCookie”);

DateTime now = DateTime.Now;

 

// Set the cookie value.

myCookie.Value = now.ToString();

// Set the cookie expiration date.

myCookie.Expires = now.AddMinutes(1);

 

// Add the cookie.

Response.Cookies.Add(myCookie);

 

Response.Write(“<p> The cookie has been written.”);

Code: Reading a Cookie

The following example uses the HttpCookie class and its properties to read a cookie with a specific name.

Example

HttpCookie myCookie = new HttpCookie(“MyTestCookie”);

myCookie = Request.Cookies[“MyTestCookie”];

 

// Read the cookie information and display it.

if (myCookie != null)

Response.Write(“<p>”+ myCookie.Name + “<p>”+ myCookie.Value);

else

Response.Write(“not found”);

Compiling the Code

Start a new ASP.NET Web application and paste the code into the Page_Load method.

Robust Programming

Replace the name “MyTestCookie” with the name of the cookie to be read.

Values returned from a cookie are always of type string.

 

 

Code: Reading Values From Application State

This example retrieves a value from the HttpApplicationState object.

Example

string appMsg;

appMsg = (string)(Application[“Message”]);

Compiling the Code

Start a new ASP.NET application and paste the code into the Page_Load method.

Robust Programming

You must cast the data to the appropriate type, as shown in the example.

No exception is thrown if you attempt to get a value out of application state that does not exist. To be sure that the value you want is in application state, check first for the existence of the object with a test such as the following:

if (Application[“Message”] == null)

Response.Write(“No such value in application state.”);

If you attempt to use a non-existent application state entry in some other way (for example, to examine its type), a NullReferenceException exception is thrown

Code: Reading Values From Session State

This example accesses the HttpSessionState.Item property to retrieve the values in session state.

Example

string firstName = (string)(Session[“First”]);

string lastName = (string)(Session[“Last”]);

string city = (string)(Session[“City”]);

Compiling the Code

Start a new ASP.NET application and paste the code into the Page_Load method.

Robust Programming

Session values are of type Object. You should cast to the appropriate type when reading them.

No exception is thrown if you attempt to get a value out of session state that does not exist. To be sure that the value you want is in session state, check first for the existence of the object with a test such as the following:

if (Session[“City”] == null)

Response.Write(“No such value in session state.”);

If you attempt to use a non-existent session state entry in some other way (for example, to examine its type), a NullReferenceException exception is thrown.

Code: Reading a Value From View State

This example saves the value “yellow” to the Control.ViewState property and then, when the page posts back to the server, retrieves a value of the property. For more information on ViewState, see Saving Web Forms Page Values Using View State.

Example

string strColor;

if (Page.IsPostBack)

{

// Retrieve and display the property value.

strColor = (string)ViewState[“color”];

Response.Write(strColor);

}

else

// Save the property value.

ViewState[“color”] = “yellow”;

Compiling the Code

Copy and paste the code into the Page_Load method of an ASP.NET Web application.

Robust Programming

As shown in the example, retrieving the ViewState property occurs when the Web page is posted back to the server. Otherwise, the string will be null.

For more information on usage recommendations, see State Management Recommendations.

 

 

 

Code: Retrieving a Dataset from View State

This example retrieves the DataSet from a view state.

if (Page.IsPostBack)

{

System.IO.StringReader sr =

new System.IO.StringReader((string)(ViewState[“dSet”]));

dSet.ReadXml(sr);

}

Compiling the Code

Start a new ASP.NET Web application and do the following:

  • Add a DataAdapter named SqlDataAdapter1.
  • Generate a DataSet (the default name of the DataSet class is DataSet1).
  • Create an instance of DataSet1 named dSet.
  • Copy the code and paste it into the Page_Load method.

Code: Redirecting to Another Page

This example uses the HttpResponse.Redirect method to redirect the browser to the specified URL.

Response.Redirect(“http://www.microsoft.com&#8221;);

Code: Redirecting to Another Page in the Same Application

This example uses the Server.Transfer method to redirect the browser to the specified page.

Server.Transfer(“WebForm2.aspx”);

Code: Saving Values in Application State

This example uses the HttpApplicationState class to save global information.

Example

Application[“Message”] = “AppMsg”;

Application[“AppStartTime”] = DateTime.Now;

 

Code: Saving Values in Session State

This example uses the Session.Add method to persist values within an individual session.

Example

string firstName = “Jeff”;

string lastName = “Smith”;

string city = “Seattle”;

 

Session.Add(“First”, firstName);

Session.Add(“Last”, lastName);

Session.Add(“City”, city);

Compiling the Code

Start a new ASP.NET application and paste the code into the Page_Load method.

Code: Saving a Dataset to View State

This example uses the Control.ViewState property to save a dataset.

Example

sqlDataAdapter1.Fill(dSet);

System.IO.StringWriter sw = new System.IO.StringWriter();

 

// Write the DataSet to the ViewState property.

dSet.WriteXml(sw);

ViewState[“dSet”] = sw.ToString();

Compiling the Code

Start a new ASP.NET Web application and do the following:

  • Add a DataAdapter named SqlDataAdapter1.
  • Generate a dataset and then create an instance named dSet.
  • Copy the code and paste it into the Page_Load method.

Code: Saving a Value in View State

This example saves the string value “yellow” to the Control.ViewState property. For more information, see Saving Web Forms Page Values Using View State.

ViewState[“color”] = “yellow”;

VS C# Sample codes

Code: Declaring an Array (Visual C#)

This example shows three different ways to declare different kinds of arrays: single-dimensional, multidimensional, and jagged.

Example

Copy

// Single-dimensional arrays.

int[] myArray1 = new int [5];

string[] myArray2 = new string[6];

 

// Multidimensional arrays.

int[,] myArray3 = new int[4,2];

int[,,] myArray4 = new int [4,2,3];

 

// Jagged array.

int[][] myArray5 = new int[3][];

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Robust Programming

Make sure you initialize the elements of the jagged array before using it, as follows:

myArray5[0] = new int[7];

myArray5[1] = new int[5];

myArray5[2] = new int[2];

Code: Initializing an Array (Visual C#)

This example shows three different ways to initialize different kinds of arrays: single-dimensional, multidimensional, and jagged.

Example

// Single-dimensional array (numbers).

int[] n1 = new int[4] {2, 4, 6, 8};

int[] n2 = new int[] {2, 4, 6, 8};

int[] n3 = {2, 4, 6, 8};

// Single-dimensional array (strings).

string[] s1 = new string[3] {“John”, “Paul”, “Mary”};

string[] s2 = new string[] {“John”, “Paul”, “Mary”};

string[] s3 = {“John”, “Paul”, “Mary”};

 

// Multidimensional array.

int[,] n4 = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };

int[,] n5 = new int[,] { {1, 2}, {3, 4}, {5, 6} };

int[,] n6 = { {1, 2}, {3, 4}, {5, 6} };

 

// Jagged array.

int[][] n7 = new int[2][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };

int[][] n8 = new int[][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };

int[][] n9 = { new int[] {2,4,6}, new int[] {1,3,5,7,9} };

Code: Iterating Through an Array (Visual C#)

This example uses the foreach statement to access and display items of an array.

Example

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

foreach (int element in numbers)

{

System.Console.WriteLine(element);

}

Code: Iterating Through a Collection (Visual C#)

This example uses the Add method on the Hashtable class to add entries to a Hashtable collection. It then uses a foreach statement to iterate through the collection.

Example

Hashtable phones = new Hashtable();

// Add items.

phones.Add(“John”, “123-4567”);

phones.Add(“Enju”, “351-8765”);

phones.Add(“Molly”, “221-5678”);

phones.Add(“James”, “010-4077”);

phones.Add(“Nelly”, “110-5699”);

phones.Add(“Leah”, “922-5699”);

 

// Iterate through the collection.

Console.WriteLine(“Name\t\tNumber”);

foreach (string name in phones.Keys)

{

Console.WriteLine(name +”\t”+ phones[name]);

}

Code: Declaring a Property (Visual C#)

This example declares an instance property. For more information and examples on instance and static properties, see Properties.

Example

private string name;

// A read-write instance property:

public string NameProperty

{

get

{

return name;

}

set

{

name = value;

}}

Robust Programming

  • You can use the get accessor to either return the field value or compute the value and return it, for example:

get

{

return (name != null) ? name : “NA”;

}

  • Do not use the get accessor to change the state of the object, for example:

get

{

return myNumericField++;

}

Code: Determining the Span Between Two Dates (Visual C#)

This example calculates the difference in days between two dates and constructs a TimeSpan value for that difference.

Example

DateTime oldDate = new DateTime(2002,7,15);

DateTime newDate = DateTime.Now;

 

// Difference in days, hours, and minutes.

TimeSpan ts = newDate – oldDate;

// Difference in days.

int differenceInDays = ts.Days;

 

Console.WriteLine(“Difference in days: {0} “, differenceInDays);

 

 

 

 

Code: Inheriting From a Class (Visual C#)

This example defines the Circle and Rectangle classes, which both inherit from the Shape class, and the Square class, which inherits from the Rectangle class.

Example

public class Shape

{

// Definitions of properties, methods, fields, and events.

}

public class Circle : Shape

{

// Specialized properties, methods, fields, events for Circle.

}

public class Rectangle : Shape

{

// Specialized properties, methods, fields, events for Rectangle.

}

public class Square : Rectangle

{

// Specialized properties, methods, fields, events for Square.

}

Code: Passing Object Arrays to Methods (Visual C#)

This example shows how an array of objects is passed to the DisplayMyCollection method, which uses the params keyword to accept any number of arguments.

Example

class MyBoxingClass

{

public static void DisplayMyCollection(params object[] anArray)

{

foreach (object obj in anArray)

{

System.Console.Write(obj + “\t”);

}

 

// Suspend the screen.

System.Console.ReadLine();

}

 

static void Main()

{

DisplayMyCollection(101, “Visual C# Basics”, 2002);

}

}

 

 

Code: Reading a Text File One Line at a Time (Visual C#)

This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. Each text line is stored into the string line and displayed on the screen.

Example

int counter = 0;

string line;

 

// Read the file and display it line by line.

System.IO.StreamReader file =

new System.IO.StreamReader(“c:\\test.txt”);

while((line = file.ReadLine()) != null)

{

Console.WriteLine (line);

counter++;

}

 

file.Close();

 

// Suspend the screen.

Console.ReadLine();

Code: Reading Class Data from an XML File (Visual C#)

This example reads the data stored in an object in the IntroToVCS.xml file using the Deserialize method of the XmlSerializer class.

Example

public class Book

{

public string title;

 

static void Main()

{

Book introToVCS  = new Book();

System.Xml.Serialization.XmlSerializer reader = new

System.Xml.Serialization.XmlSerializer(introToVCS.GetType());

 

// Read the XML file.

System.IO.StreamReader file=

new System.IO.StreamReader(“c:\\IntroToVCS.xml”);

 

// Deserialize the content of the file into a Book object.

introToVCS = (Book) reader.Deserialize(file);

System.Windows.Forms.MessageBox.Show(introToVCS.title,

“Book Title”);

}

}

 

Code: Reading From a Text File (Visual C#)

This example reads the contents of a text file into a string using the ReadToEnd method of the StreamReader class.

Example

// Read the file as one string.

System.IO.StreamReader myFile =

new System.IO.StreamReader(“c:\\test.txt”);

string myString = myFile.ReadToEnd();

 

myFile.Close();

 

// Display the file contents.

Console.WriteLine(myString);

// Suspend the screen.

Console.ReadLine();

 

Code: Reading XML From a File (Visual C#)

This example uses the XMLTextReader class to extract the element names and text strings from the IntroToVCS.xml file and store the information in a string variable.

Example

System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(“c:\\IntroToVCS.xml”);

string contents = “”;

while (reader.Read())

{

reader.MoveToContent();

if (reader.NodeType == System.Xml.XmlNodeType.Element)

contents += “<“+reader.Name + “>\n”;

if (reader.NodeType == System.Xml.XmlNodeType.Text)

contents += reader.Value + “\n”;

}

Console.Write(contents);

Code: Writing Class Data to an XML File (Visual C#)

This example writes the data stored in an object to the IntroToVCS.xml by means of the Serialize method of the XmlSerializer class.

Example

public class Book

{

public string title;

 

static void Main()

{

Book introToVCS = new Book();

introToVCS.title = “Intro to Visual CSharp”;

System.Xml.Serialization.XmlSerializer writer =

new System.Xml.Serialization.XmlSerializer(introToVCS.GetType());

System.IO.StreamWriter file =

new System.IO.StreamWriter(“c:\\IntroToVCS.xml”);

 

writer.Serialize(file, introToVCS);

file.Close();

}

}

Code: Writing to a Text File (Visual C#)

This example writes a string to a text file using the WriteLine method of the StreamWriter class.

Example

// Compose a string that consists of three lines.

string lines = “First line.\r\nSecond line.\r\nThird line.”;

 

// Write the string to a file.

System.IO.StreamWriter file = new System.IO.StreamWriter(“c:\\test.txt”);

file.WriteLine(lines);

 

file.Close();

 

Code: Running a Program (Visual C#)

This example loads and runs the MSPaint application using the Process.Start method.

Example

System.Diagnostics.Process.Start(“mspaint.exe”);

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Replace "mspaint.exe" with the path to the application you want to run

Code: Running a Program Associated With a File Type (Visual C#)

This example opens the test.txt file in Notepad using the Process.Start method.

Example

System.Diagnostics.Process.Start(“c:\\test.txt”);

Code: Searching for a String in an Array of Strings (Visual C#)

This example calls the IndexOf method on an array of strings to report the string number and index of the first occurrence of a substring.

Example

string[] strArray = {“ABCDEFG”, “HIJKLMNOP”};

string findThisString = “JKL”;

int strNumber;

int strIndex = 0;

for (strNumber = 0; strNumber < strArray.Length; strNumber++)

{

strIndex = strArray[strNumber].IndexOf(findThisString);

if (strIndex >= 0)

break;

}

Console.WriteLine(“String number: {0}\nString index: {1}”,

strNumber, strIndex);

Code: Searching Within a String (Visual C#)

This example calls the IndexOf method on a String object to report the index of the first occurrence of a substring.

Example

string searchWithinThis = “ABCDEFGHIJKLMNOP”;

string searchForThis = “DEF”;

int firstCharacter = searchWithinThis.IndexOf(searchForThis);

 

Console.WriteLine(“First occurrence: {0}”, firstCharacter);

Code: Simulating Default Parameters (Visual C#)

This example demonstrates the use of method overloading to simulate default parameters, which is not allowed in C#.

Example

class MyClass

{

static string myMethod(string precip, string country, string location)

{

return string.Format(“The {0} in {1} stays mainly in the {2}.”,

precip, country, location );

}

 

static string myMethod(string precip, string country )

{

return myMethod(precip, country, “plain”);

}

 

static string myMethod()

{

return myMethod(“rain”, “Spain”, “plain”);

}

 

static void Main(string[] args)

{

Console.WriteLine(myMethod());

Console.WriteLine(myMethod(“snow”, “Walla Walla”));

}

}

Code: Finding the Names of Resources in an Assembly (Visual C#)

This example creates a string that contains the names of all the resources in an assembly.

Example

System.Reflection.Assembly thisExe;

thisExe = System.Reflection.Assembly.GetExecutingAssembly();

string [] resources = thisExe.GetManifestResourceNames();

string list = “”;

 

// Build the string of resources.

foreach (string resource in resources)

list += resource + “\r\n”;

Code: Catching an Exception (Visual C#)

This example uses the trycatch blocks to catch division by zero as an exception.

Example

int top = 0, bottom = 0, result = 0;

try

{

result = top / bottom;

}

catch (System.DivideByZeroException ex)

{

Console.WriteLine(“{0} Exception caught.”, ex);

}