<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Dave on C-Sharp</title>
	
	<link>http://www.daveoncsharp.com</link>
	<description>C# Programming Tutorials</description>
	<lastBuildDate>Sun, 24 Feb 2013 04:57:39 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/DaveOnCSharp" /><feedburner:info uri="daveoncsharp" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by-nc/2.0/</creativeCommons:license><feedburner:emailServiceId>DaveOnCSharp</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Binding a Windows Forms ComboBox in C#</title>
		<link>http://feedproxy.google.com/~r/DaveOnCSharp/~3/XcotiFc3SjM/</link>
		<comments>http://www.daveoncsharp.com/2009/11/binding-a-windows-forms-combobox-in-csharp/#comments</comments>
		<pubDate>Sun, 29 Nov 2009 18:18:07 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[Binding]]></category>
		<category><![CDATA[ComboBox]]></category>
		<category><![CDATA[KeyValuePair]]></category>

		<guid isPermaLink="false">http://www.daveoncsharp.com/?p=1652</guid>
		<description><![CDATA[Most often when reading the selected item of a bound combobox you will need more information than just the selected text or the selected index of the combo. For example, if you have a combobox bound to a user table in your database, you will most probably want to have the full user name displayed [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/06/windows-forms-event-sequence/' rel='bookmark' title='Windows Forms Event Sequence'>Windows Forms Event Sequence</a></li>
<li><a href='http://www.daveoncsharp.com/2009/09/how-to-paint-a-gradient-background-for-your-forms/' rel='bookmark' title='How to paint a Gradient Background for your Forms'>How to paint a Gradient Background for your Forms</a></li>
<li><a href='http://www.daveoncsharp.com/2009/06/prevent-users-closing-your-windows-form/' rel='bookmark' title='Prevent Users Closing Your Windows Form'>Prevent Users Closing Your Windows Form</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p></p><p>Most often when reading the selected item of a bound combobox you will need more information than just the selected text or the selected index of the combo. For example, if you have a combobox bound to a user table in your database, you will most probably want to have the full user name displayed in the combobox, but when a user is selected you will want to work with the user code or user id. In this case the combo&#8217;s selected index is of no use and neither is the display text. You need a way to be able to retrieve the user code when a user is selected. </p>
<p>Fortunately, this is quite easy to accomplish. All we need to do is bind our combobox to a list of <code>KeyValuePair</code> objects. In this article I am going to show you how to do exactly that.</p>
<p>To start off create a form which looks similar to the below one:</p>
<p><img style=' display: block; margin-right: auto; margin-left: auto;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/11/screenshot.jpg" alt="Binding a ComboBox" title="Binding a ComboBox" width="264" height="150" class="aligncenter size-full wp-image-1654" /></p>
<p>Now in  the <code>Form_Load</code> event handler we must add the following code:</p>
<pre class="code"><span style="color: blue">private void </span>MainForm_Load(<span style="color: blue">object </span>sender, <span style="color: #2b91af">EventArgs </span>e)
{
    <span style="color: green">// Create a List to store our KeyValuePairs
    </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">KeyValuePair</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt;&gt; data = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">KeyValuePair</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt;&gt;();

    <span style="color: green">// Add data to the List
    </span>data.Add(<span style="color: blue">new </span><span style="color: #2b91af">KeyValuePair</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt;(<span style="color: #a31515">&quot;p1&quot;</span>, <span style="color: #a31515">&quot;Joe&quot;</span>));
    data.Add(<span style="color: blue">new </span><span style="color: #2b91af">KeyValuePair</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt;(<span style="color: #a31515">&quot;p2&quot;</span>, <span style="color: #a31515">&quot;David&quot;</span>));
    data.Add(<span style="color: blue">new </span><span style="color: #2b91af">KeyValuePair</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt;(<span style="color: #a31515">&quot;p3&quot;</span>, <span style="color: #a31515">&quot;Keith&quot;</span>));
    data.Add(<span style="color: blue">new </span><span style="color: #2b91af">KeyValuePair</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt;(<span style="color: #a31515">&quot;p4&quot;</span>, <span style="color: #a31515">&quot;Andrew&quot;</span>));
    data.Add(<span style="color: blue">new </span><span style="color: #2b91af">KeyValuePair</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt;(<span style="color: #a31515">&quot;p5&quot;</span>, <span style="color: #a31515">&quot;Maria&quot;</span>));
    
    <span style="color: green">// Clear the combobox
    </span>cboData.DataSource = <span style="color: blue">null</span>;
    cboData.Items.Clear();

    <span style="color: green">// Bind the combobox
    </span>cboData.DataSource = <span style="color: blue">new </span><span style="color: #2b91af">BindingSource</span>(data, <span style="color: blue">null</span>);
    cboData.DisplayMember = <span style="color: #a31515">&quot;Value&quot;</span>;
    cboData.ValueMember = <span style="color: #a31515">&quot;Key&quot;</span>;
}</pre>
<p><span id="more-1652"></span></p>
<p>In the first line of code we are creating a <code>List</code> object to store our <code>KeyValuePair</code> objects. The <code>KeyValuePair</code> class can be very useful since it allows you to create a pair of objects of any type, one of which is the key and the other is the value. What this means is that you can have an object of type <code>string</code> paired with a key of type <code>integer</code> for example. Or you could have a value of type <code>MyClass</code> with a key of type <code>string</code>. The combinations are limitless.</p>
<p>As you can see in the code, we are creating a <code>KeyValuePair</code> where both the key and the value are <code>strings</code>. We are then adding data to the <code>List</code> object by creating <code>KeyValuePair</code> instances and adding them to our <code>List</code>. Next we are clearing the combobox as a precaution (<em>just in case it was populated with something already</em>), and finally we are binding the combobox to the <code>List</code>.</p>
<p>The last two lines of the above code are critical for your binding to work correctly. We must tell the combo which is the <code>DisplayMember</code> and which is the <code>ValueMember</code> of our <code>KeyValuePair</code> so that it will know which object from the pair to display and which to use as the key.</p>
<p>Once you have created the above code run your project and you will see that the combobox is populated with the above names. The key value however cannot be seen, so let&#8217;s create some code to visually see the selected key.</p>
<p>Subscribe to the <code>SelectedIndexChanged</code> event of your combobox and add the following code:</p>
<pre class="code"><span style="color: blue">private void </span>cboData_SelectedIndexChanged(<span style="color: blue">object </span>sender, <span style="color: #2b91af">EventArgs </span>e)
{
    <span style="color: green">// Get the selected item in the combobox
    </span><span style="color: #2b91af">KeyValuePair</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt; selectedPair = (<span style="color: #2b91af">KeyValuePair</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">string</span>&gt;)cboData.SelectedItem;
    
    <span style="color: green">// Show selected information on screen
    </span>lblSelectedKey.Text = selectedPair.Key;
    lblSelectedValue.Text = selectedPair.Value;
}</pre>
<p>What we are doing here is retrieving the combo&#8217;s selected item and converting it to a <code>KeyValuePair</code> object. Then from our <code>KeyValuePair</code> object we are accessing the <code>Key</code> and the <code>Value</code> properties and assigning them to the labels on our form.</p>
<p>Now if you run the application again you should have something like the following, and as you can see the key and value are being displayed in our labels.</p>
<p><img style=' display: block; margin-right: auto; margin-left: auto;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/11/screenshot2.jpg" alt="Binding a ComboBox" title="Binding a ComboBox" width="264" height="150" class="aligncenter size-full wp-image-1662" /></p>
<p>Now using this technique you can easily bind a combobox and have one value displayed while another value is used as your key. </p>
<p>I hope you found this useful.<br />
Dave.</p>
<div class='yarpp-related-rss'>
<br /><p>Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/06/windows-forms-event-sequence/' rel='bookmark' title='Windows Forms Event Sequence'>Windows Forms Event Sequence</a></li>
<li><a href='http://www.daveoncsharp.com/2009/09/how-to-paint-a-gradient-background-for-your-forms/' rel='bookmark' title='How to paint a Gradient Background for your Forms'>How to paint a Gradient Background for your Forms</a></li>
<li><a href='http://www.daveoncsharp.com/2009/06/prevent-users-closing-your-windows-form/' rel='bookmark' title='Prevent Users Closing Your Windows Form'>Prevent Users Closing Your Windows Form</a></li>
</ol></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=XcotiFc3SjM:BAT-gQSDJT4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=XcotiFc3SjM:BAT-gQSDJT4:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?i=XcotiFc3SjM:BAT-gQSDJT4:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DaveOnCSharp/~4/XcotiFc3SjM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncsharp.com/2009/11/binding-a-windows-forms-combobox-in-csharp/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://www.daveoncsharp.com/2009/11/binding-a-windows-forms-combobox-in-csharp/</feedburner:origLink></item>
		<item>
		<title>C# Escape Sequence Listing</title>
		<link>http://feedproxy.google.com/~r/DaveOnCSharp/~3/9EVlzis2EWQ/</link>
		<comments>http://www.daveoncsharp.com/2009/11/csharp-escape-sequence-listing/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 19:29:48 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[String Operations]]></category>
		<category><![CDATA[Escape]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://www.daveoncsharp.com/?p=1598</guid>
		<description><![CDATA[What is an escape sequence? Well, put simply, an escape sequence is a series of special characters which are interpreted by the compiler as a command. In other words, they suspend the normal processing to perform some special function. In C#, escape sequences are represented by a ‘\’ (backslash) followed by a letter or a [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/06/windows-forms-event-sequence/' rel='bookmark' title='Windows Forms Event Sequence'>Windows Forms Event Sequence</a></li>
<li><a href='http://www.daveoncsharp.com/2009/09/formatting-integers-in-csharp/' rel='bookmark' title='Formatting Integers in C#'>Formatting Integers in C#</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p></p><p>What is an <em>escape sequence</em>? Well, put simply, an escape sequence is a series of <strong>special characters</strong> which are interpreted by the compiler as a command. In other words, they suspend the normal processing to perform some special function.</p>
<p>In C#, escape sequences are represented by a <strong>‘\’</strong> (<em>backslash</em>) followed by a letter or a combination of digits. </p>
<p>The following table represents the most common escape sequences used in C#.</p>
<table class="customTable" border="0" cellspacing="0" cellpadding="0" width="100%">
<thead>
<tr>
<td valign="top">Escape Sequence</td>
<td valign="top">What it Represents</td>
</tr>
</thead>
<tbody>
<tr>
<td valign="top"><strong>\’</strong></td>
<td valign="top">Single Quotation Mark (character 39)</td>
</tr>
<tr>
<td valign="top"><strong>\”</strong></td>
<td valign="top">Double Quotation Mark (character 34)</td>
</tr>
<tr>
<td valign="top"><strong>\?</strong></td>
<td valign="top">Literal Question Mark</td>
</tr>
<tr>
<td valign="top"><strong>\\</strong></td>
<td valign="top">Backslash (character 92)</td>
</tr>
<tr>
<td valign="top"><strong>\a</strong></td>
<td valign="top">Alert/Bell (character 7)</td>
</tr>
<tr>
<td valign="top"><strong>\b</strong></td>
<td valign="top">Backspace (character 8 ) </td>
</tr>
<tr>
<td valign="top"><strong>\f</strong></td>
<td valign="top">Formfeed (character 12)</td>
</tr>
<tr>
<td valign="top"><strong>\n</strong></td>
<td valign="top">New Line (character 10)</td>
</tr>
<tr>
<td valign="top"><strong>\r</strong></td>
<td valign="top">Carriage Return (character 13)</td>
</tr>
<tr>
<td valign="top"><strong>\t</strong></td>
<td valign="top">Horizontal Tab (character 9)</td>
</tr>
<tr>
<td valign="top"><strong>\v</strong></td>
<td valign="top">Vertical Tab (character 11)</td>
</tr>
<tr>
<td valign="top"><strong>\</strong>ooo</td>
<td valign="top">ASCII character in octal notation</td>
</tr>
<tr>
<td valign="top"><strong>\x</strong>hh</td>
<td valign="top">ASCII character in hexadecimal notation</td>
</tr>
</tbody>
</table>
<p><span id="more-1598"></span></p>
<h4>Examples</h4>
<ol>
<li>In the below code we are escaping the backslash in the path string.
<p><pre class="code"><span style="color: blue">string </span>path = <span style="color: #a31515">&quot;C:\\Program Files\\Microsoft&quot;</span>;</pre>
</p>
<p>		The result would look like this: <em>C:\Program Files\Microsoft</em> </li>
<li>In the below code we are adding a carriage return and a new line by using the <strong>\r\n </strong>escape sequences together.
<p><pre class="code"><span style="color: #2b91af">MessageBox</span>.Show(<span style="color: #a31515">&quot;Hello from...\r\nhttp://www.daveoncsharp.com&quot;</span>, 
                <span style="color: #a31515">&quot;Escape Sequences&quot;</span>, 
                <span style="color: #2b91af">MessageBoxButtons</span>.OK, 
                <span style="color: #2b91af">MessageBoxIcon</span>.Information);</pre>
</p>
<p>		The result will be a message box with the message string split on two lines as shown below.</p>
<p>		<img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="EscapeSequences" border="0" alt="EscapeSequences" src="http://www.daveoncsharp.com/wp-content/uploads/2009/11/EscapeSequences_thumb.jpg" width="290" height="175" />
	</li>
</ol>
<p>I hope you found this useful. Feel free to visit this blog often for more similar articles.</p>
<p>Dave.</p>
<div class='yarpp-related-rss'>
<br /><p>Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/06/windows-forms-event-sequence/' rel='bookmark' title='Windows Forms Event Sequence'>Windows Forms Event Sequence</a></li>
<li><a href='http://www.daveoncsharp.com/2009/09/formatting-integers-in-csharp/' rel='bookmark' title='Formatting Integers in C#'>Formatting Integers in C#</a></li>
</ol></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=9EVlzis2EWQ:Fb6lHK-732w:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=9EVlzis2EWQ:Fb6lHK-732w:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?i=9EVlzis2EWQ:Fb6lHK-732w:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DaveOnCSharp/~4/9EVlzis2EWQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncsharp.com/2009/11/csharp-escape-sequence-listing/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://www.daveoncsharp.com/2009/11/csharp-escape-sequence-listing/</feedburner:origLink></item>
		<item>
		<title>Retrieving Data From a MySQL Database</title>
		<link>http://feedproxy.google.com/~r/DaveOnCSharp/~3/oEg-qOPBjWs/</link>
		<comments>http://www.daveoncsharp.com/2009/11/retrieving-data-from-a-mysql-database/#comments</comments>
		<pubDate>Sat, 07 Nov 2009 19:13:29 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Connection]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://www.daveoncsharp.com/?p=1591</guid>
		<description><![CDATA[In this article I am going to show you how to programmatically retrieve data from a MySQL database using the MySqlDataAdapter and the MySqlDataReader classes. Both these classes are available once you install the MySQL Connector for .NET which can be downloaded from here: MySQL Connectors. For this example we need a database with some [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/10/connecting-to-a-mysql-database-programmatically/' rel='bookmark' title='Connecting to a MySQL Database Programmatically'>Connecting to a MySQL Database Programmatically</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p></p><p>In this article I am going to show you how to programmatically retrieve data from a MySQL database using the <strong>MySqlDataAdapter</strong> and the <strong>MySqlDataReader</strong> classes. Both these classes are available once you install the MySQL Connector for .NET which can be downloaded from here: <a href="http://dev.mysql.com/downloads/connector/">MySQL Connectors</a>.</p>
<p>For this example we need a database with some test data. MySQL has an sql script which creates a set of tables with world country information. I will be using these tables for this example so I suggest you <a href="http://downloads.mysql.com/docs/world.sql.zip">download this script</a> and run it on your MySQL database. Once done, you will have added the following three tables to your database.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="Schema Diagram" border="0" alt="Schema Diagram" src="http://www.daveoncsharp.com/wp-content/uploads/2009/11/schema.jpg" width="341" height="373" /> </p>
<p>  <span id="more-1591"></span><br />
<h4>Connecting to a MySQL Database</h4>
<p>To retrieve data from a MySQL database you must obviously connect to the database first. If you do not know how to do this check out my article called <a href="http://www.daveoncsharp.com/2009/10/connecting-to-a-mysql-database-programmatically/">Connecting to a MySQL Database Programmatically</a>.</p>
<h4>Retrieving Data Using MySqlDataAdapter</h4>
<p>In the below code we are retrieving all the data in the <strong>country</strong> table and populating a <strong>DataTable</strong> using the <strong>MySqlDataAdapter</strong>. Then we are binding the <strong>DataTable</strong> instance to a <strong>DataGridView</strong> on the form.</p>
<pre class="code"><span style="color: blue">private void </span>btnPopulateGrid_Click(<span style="color: blue">object </span>sender, <span style="color: #2b91af">EventArgs </span>e)
{
    <span style="color: #2b91af">MySqlConnection </span>conn = <span style="color: blue">null</span>;
    <span style="color: #2b91af">MySqlCommand </span>cmd = <span style="color: blue">null</span>;
    <span style="color: #2b91af">DataTable </span>dataTable = <span style="color: blue">new </span><span style="color: #2b91af">DataTable</span>();

    <span style="color: blue">try
    </span>{
        <span style="color: blue">string </span>sql = <span style="color: #a31515">&quot;SELECT * FROM country ORDER BY name ASC&quot;</span>;

        conn = <span style="color: blue">new </span><span style="color: #2b91af">MySqlConnection</span>(Properties.<span style="color: #2b91af">Settings</span>.Default.ConnectionString);

        cmd = <span style="color: blue">new </span><span style="color: #2b91af">MySqlCommand</span>(sql, conn);

        conn.Open();

        <span style="color: blue">using </span>(<span style="color: #2b91af">MySqlDataAdapter </span>da = <span style="color: blue">new </span><span style="color: #2b91af">MySqlDataAdapter</span>(cmd))
        {
            da.Fill(dataTable);
        }

        dataGridView.DataSource = dataTable;
        dataGridView.DataMember = dataTable.TableName;
    }
    <span style="color: blue">catch </span>(<span style="color: #2b91af">Exception </span>ex)
    {
        <span style="color: #2b91af">MessageBox</span>.Show(<span style="color: blue">string</span>.Format(<span style="color: #a31515">&quot;An error occurred {0}&quot;</span>, ex.Message), <span style="color: #a31515">&quot;Error&quot;</span>, <span style="color: #2b91af">MessageBoxButtons</span>.OK, <span style="color: #2b91af">MessageBoxIcon</span>.Error);
    }
    <span style="color: blue">finally
    </span>{
        <span style="color: blue">if </span>(conn != <span style="color: blue">null</span>) conn.Close();
    }
}</pre>
</p>
<p>When the code is run, it will populate the <strong>DataGridView</strong> as shown below.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="MySqlDataAdapter" border="0" alt="MySqlDataAdapter" src="http://www.daveoncsharp.com/wp-content/uploads/2009/11/MySqlDataAdapter.jpg" width="456" height="359" /></p>
<h4>Retrieving Data Using MySqlDataReader</h4>
<p>With the <strong>MySqlDataReader</strong> we have a little more work to do than we did with the <strong>MySqlDataAdapter</strong>, but there is also an advantage to using it, which is speed. The <strong>DataReader</strong> retrieves data faster than the <strong>DataAdapter</strong> because it is a read-only, forward-only stream of data. So if you just want to read data from the database and display it somewhere in your application, I would suggest you go with the <strong>DataReader</strong>. It is true that you have to code more to use it but it is worth the extra effort.</p>
<p>The below code is selecting specific data for the country <em>Malta</em> using the <strong>DataReader</strong>.</p>
<pre class="code"><span style="color: blue">private void </span>btnPopulateLabels_Click(<span style="color: blue">object </span>sender, <span style="color: #2b91af">EventArgs </span>e)
{
    <span style="color: #2b91af">MySqlConnection </span>conn = <span style="color: blue">null</span>;
    <span style="color: #2b91af">MySqlCommand </span>cmd = <span style="color: blue">null</span>;
    <span style="color: #2b91af">MySqlDataReader </span>reader = <span style="color: blue">null</span>;

    <span style="color: blue">try
    </span>{
        <span style="color: blue">string </span>sql = <span style="color: #a31515">&quot;SELECT name, continent, region, surfacearea FROM country WHERE code = 'MLT'&quot;</span>;

        conn = <span style="color: blue">new </span><span style="color: #2b91af">MySqlConnection</span>(Properties.<span style="color: #2b91af">Settings</span>.Default.ConnectionString);
        cmd = <span style="color: blue">new </span><span style="color: #2b91af">MySqlCommand</span>(sql, conn);

        conn.Open();

        reader = cmd.ExecuteReader();

        <span style="color: blue">while </span>(reader.Read())
        {
            lblCountryCode.Text = <span style="color: #a31515">&quot;MLT&quot;</span>;
            lblName.Text = reader.GetString(<span style="color: #a31515">&quot;name&quot;</span>);
            lblContinent.Text = reader.GetString(<span style="color: #a31515">&quot;continent&quot;</span>);
            lblRegion.Text = reader.GetString(<span style="color: #a31515">&quot;region&quot;</span>);
            lblSurfaceArea.Text = <span style="color: blue">string</span>.Format(<span style="color: #a31515">&quot;{0:0.00}&quot;</span>, reader.GetFloat(<span style="color: #a31515">&quot;surfacearea&quot;</span>));
        }
    }
    <span style="color: blue">catch </span>(<span style="color: #2b91af">Exception </span>ex)
    {
        <span style="color: #2b91af">MessageBox</span>.Show(<span style="color: blue">string</span>.Format(<span style="color: #a31515">&quot;An error occurred {0}&quot;</span>, ex.Message), <span style="color: #a31515">&quot;Error&quot;</span>, <span style="color: #2b91af">MessageBoxButtons</span>.OK, <span style="color: #2b91af">MessageBoxIcon</span>.Error);
    }
    <span style="color: blue">finally
    </span>{
        <span style="color: blue">if </span>(reader != <span style="color: blue">null</span>) reader.Close();
        <span style="color: blue">if </span>(conn != <span style="color: blue">null</span>) conn.Close();
    }
}</pre>
<p>The most significant part of this code is the <strong>while</strong> loop. This code will keep iterating until the <strong>DataReader</strong> finishes reading the data stream. It retrieves records one by one so within each iteration you have access to the fields you selected. </p>
<p>If your sql query returned no records, the <strong>Read()</strong> method of the <strong>DataReader</strong> will return <strong>false</strong>, therefore the code within the while loop will not execute.</p>
<p>When the above code is run, it will populate the form below:</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="MySqlDataReader" border="0" alt="MySqlDataReader" src="http://www.daveoncsharp.com/wp-content/uploads/2009/11/MySqlDataReader.jpg" width="456" height="210" /> </p>
<p>I hope you found this article useful. Stay tuned for more soon.</p>
<p>Dave</p>
<div class='yarpp-related-rss'>
<br /><p>Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/10/connecting-to-a-mysql-database-programmatically/' rel='bookmark' title='Connecting to a MySQL Database Programmatically'>Connecting to a MySQL Database Programmatically</a></li>
</ol></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=oEg-qOPBjWs:hFpoIpqto5M:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=oEg-qOPBjWs:hFpoIpqto5M:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?i=oEg-qOPBjWs:hFpoIpqto5M:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DaveOnCSharp/~4/oEg-qOPBjWs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncsharp.com/2009/11/retrieving-data-from-a-mysql-database/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://www.daveoncsharp.com/2009/11/retrieving-data-from-a-mysql-database/</feedburner:origLink></item>
		<item>
		<title>Connecting to a MySQL Database Programmatically</title>
		<link>http://feedproxy.google.com/~r/DaveOnCSharp/~3/AwSCl4AwK84/</link>
		<comments>http://www.daveoncsharp.com/2009/10/connecting-to-a-mysql-database-programmatically/#comments</comments>
		<pubDate>Sun, 18 Oct 2009 20:03:15 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Connection]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Settings]]></category>

		<guid isPermaLink="false">http://www.daveoncsharp.com/?p=1541</guid>
		<description><![CDATA[Microsoft Visual Studio lets you create a database connection using its IDE, and it&#8217;s quite powerful as well, but personally I prefer to create my database connections programmatically. When creating my connection&#8217;s code manually I find it easier to follow the code, plus it can be easier to debug as well. I am by no [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/11/retrieving-data-from-a-mysql-database/' rel='bookmark' title='Retrieving Data From a MySQL Database'>Retrieving Data From a MySQL Database</a></li>
<li><a href='http://www.daveoncsharp.com/2009/07/hibernate-or-standby-windows-programmatically/' rel='bookmark' title='Hibernate or Standby Windows Programmatically'>Hibernate or Standby Windows Programmatically</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p></p><p><img style=' float: left; padding: 4px; margin: 0 7px 2px 0;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/10/MySQLConnect.jpg" alt="" title="" width="200" height="103" class="alignleft size-full wp-image-1557" />Microsoft Visual Studio lets you create a database connection using its IDE, and it&#8217;s quite powerful as well, but personally I prefer to create my database connections programmatically. When creating my connection&#8217;s code manually I find it easier to follow the code, plus it can be easier to debug as well. I am by no means saying that this is the best way to connect to a database &#8211; it&#8217;s just my personal preference. </p>
<p>In this article I will show you how to connect to a MySQL database programmatically through C#.</p>
<h4>Why MySQL?</h4>
<p>I personally like working with MySQL because it&#8217;s freely available under the <a href="http://en.wikipedia.org/wiki/GNU_General_Public_License">GPL License</a>. I have also been working with MySQL from version 4 <em>(and that&#8217;s around 6 years now)</em> so by now I am quite used to it. If you would like to install MySQL you can find it here: <a href="http://dev.mysql.com/downloads/">MySQL Community Server</a></p>
<h4>The Connection String</h4>
<p>Every database has its own specific connection string, and since there are so many different databases out there, it&#8217;s impossible to remember each connection string by heart. That is why I use <a href="http://www.connectionstrings.com/">ConnectionStrings.com</a> to refresh my memory. It&#8217;s a great resource with connection strings for probably every type of database you can think of.</p>
<p>For this example we will be using the standard connection string which assumes MySQL is accessible on the default port of 3306. You can check out other MySQL connection strings here: <a href="http://www.connectionstrings.com/mysql">Connection strings for MySQL</a></p>
<pre>
SERVER=myServerAddress; DATABASE=myDataBase; UID=myUsername; PWD=myPassword;
</pre>
<p>So, if MySQL was installed locally, and we had a database called <em>testdb</em>, and a MySQL database user called <em>testuser</em> with password <em>testpass</em>, the connection string would look like this:</p>
<pre>
SERVER=localhost; DATABASE=testdb; UID=testuser; PWD=testpass;
</pre>
<p><span id="more-1541"></span></p>
<h4>The Connection Code</h4>
<p>To connect to MySQL we need to download and install the MySQL Connector for .NET which can be found here: <a href="http://dev.mysql.com/downloads/connector/">MySQL Connectors</a>. This is basically the MySQL standardized database driver for .NET platforms.</p>
<p>Once installed you will have access to the MySQL classes from .NET, but to use them you must first reference them. So from within your project navigate to the <strong>Add Reference</strong> window and select the <code>MySql.Data</code> .NET component. This will add it to you project and now you should be able to access the <code>MySql.Data.MySqlClient</code> namespace, which we will be using to connect to the database.</p>
<p>The actual code used to connect to the database is very simple. As long as we have access to the <code>MySqlConnection</code> class which is in the <code>MySql.Data.MySqlClient</code> namespace, we should be able to connect as shown in the below code:</p>
<pre>
string connStr = "SERVER=localhost;" +
                 "DATABASE=testdb;" +
                 "UID=testuser;" +
                 "PWD=testpass;";

MySqlConnection conn = new MySqlConnection(connStr);

conn.Open();

// Read/Write to and from your database here

conn.Close();
</pre>
<p>Since the connection string is an application setting and usually only changes per installation of your application, I would recommend placing the connection string in the <code>Settings.settings</code> file. If you do not know what this file is you can check out my article on <a href="http://www.daveoncsharp.com/2009/07/using-the-settings-file-in-csharp/">Using the Settings file in C#</a>.</p>
<p>If you were to place your connection string there you would then be able to access it from anywhere throughout your code by calling <code>Properties.Settings.Default.ConnectionString</code>.</p>
<p>Below is how your database connection code looks now:</p>
<pre>
MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.ConnectionString);

conn.Open();

// Read/Write to and from your database here

conn.Close();
</pre>
<p>I hope you found this article useful. Stay tuned because I will soon be talking about how to retrieve data from MySQL.</p>
<p>Dave</p>
<div class='yarpp-related-rss'>
<br /><p>Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/11/retrieving-data-from-a-mysql-database/' rel='bookmark' title='Retrieving Data From a MySQL Database'>Retrieving Data From a MySQL Database</a></li>
<li><a href='http://www.daveoncsharp.com/2009/07/hibernate-or-standby-windows-programmatically/' rel='bookmark' title='Hibernate or Standby Windows Programmatically'>Hibernate or Standby Windows Programmatically</a></li>
</ol></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=AwSCl4AwK84:gVV8Yz3486o:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=AwSCl4AwK84:gVV8Yz3486o:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?i=AwSCl4AwK84:gVV8Yz3486o:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DaveOnCSharp/~4/AwSCl4AwK84" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncsharp.com/2009/10/connecting-to-a-mysql-database-programmatically/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.daveoncsharp.com/2009/10/connecting-to-a-mysql-database-programmatically/</feedburner:origLink></item>
		<item>
		<title>New ASCII Codes Page</title>
		<link>http://feedproxy.google.com/~r/DaveOnCSharp/~3/BFs1uq1sbDM/</link>
		<comments>http://www.daveoncsharp.com/2009/10/new-ascii-codes-page/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 20:59:58 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[String Operations]]></category>
		<category><![CDATA[ASCII]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://www.daveoncsharp.com/?p=1511</guid>
		<description><![CDATA[I have added a new page to this blog called ASCII Codes, which can be accessed from the navigation bar at the top of the page. This new page is intended as a reference guide which you can use to look up an ascii code&#8217;s decimal, hexadecimal, and html values. There is also a description [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/09/how-to-use-a-master-page-in-asp-net/' rel='bookmark' title='How to use a Master Page in ASP.NET'>How to use a Master Page in ASP.NET</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p></p><p>I have added a new page to this blog called <a href="http://www.daveoncsharp.com/ascii-codes/">ASCII Codes</a>, which can be accessed from the navigation bar at the top of the page. This new page is intended as a reference guide which you can use to look up an ascii code&#8217;s decimal, hexadecimal, and html values. There is also a description of each code and obviously the symbol represented by each ascii code.</p>
<p>Please feel free to use this page for what it is intended to be &#8211; your ascii reference guide.</p>
<p>Dave</p>
<div class='yarpp-related-rss'>
<br /><p>Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/09/how-to-use-a-master-page-in-asp-net/' rel='bookmark' title='How to use a Master Page in ASP.NET'>How to use a Master Page in ASP.NET</a></li>
</ol></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=BFs1uq1sbDM:MA2BIyu52YA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=BFs1uq1sbDM:MA2BIyu52YA:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?i=BFs1uq1sbDM:MA2BIyu52YA:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DaveOnCSharp/~4/BFs1uq1sbDM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncsharp.com/2009/10/new-ascii-codes-page/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.daveoncsharp.com/2009/10/new-ascii-codes-page/</feedburner:origLink></item>
		<item>
		<title>How to Capture System Events using C#</title>
		<link>http://feedproxy.google.com/~r/DaveOnCSharp/~3/uVg-NPZujBs/</link>
		<comments>http://www.daveoncsharp.com/2009/10/how-to-capture-system-events-using-csharp/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 20:06:19 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Operating System]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://www.daveoncsharp.com/?p=1462</guid>
		<description><![CDATA[What are system events? Well, basically they are events raised by the operating system when a user performs an action which affects the operating environment. System events are accessible through the Microsoft.Win32.SystemEvents class. SystemEvents Events Below is a list of all the system events found within the SystemEvents class. Name Description DisplaySettingsChanged Occurs when the [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/09/monitoring-the-file-system-for-changes/' rel='bookmark' title='Monitoring the File System for Changes'>Monitoring the File System for Changes</a></li>
<li><a href='http://www.daveoncsharp.com/2009/08/add-notify-icon-to-system-tray/' rel='bookmark' title='Add a Notify Icon to the System Tray with C#'>Add a Notify Icon to the System Tray with C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/06/windows-forms-event-sequence/' rel='bookmark' title='Windows Forms Event Sequence'>Windows Forms Event Sequence</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p></p><p><img style=' float: right; padding: 4px; margin: 0 0 2px 7px;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/10/system.jpg" alt="" title="" width="200" height="149" class="alignright size-full wp-image-1486" />What are system events? Well, basically they are events raised by the operating system when a user performs an action which affects the operating environment. </p>
<p>System events are accessible through the <code>Microsoft.Win32.SystemEvents</code> class.</p>
<h4>SystemEvents Events</h4>
<p>Below is a list of all the system events found within the <code>SystemEvents</code> class.</p>
<table class="customTable" cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>
<td>
                Name
            </td>
<td>
                Description
            </td>
</tr>
</thead>
<tbody>
<tr>
<td>
                <code>DisplaySettingsChanged</code>
            </td>
<td>
                Occurs when the user changes the display settings.
            </td>
</tr>
<tr>
<td>
                <code>DisplaySettingsChanging</code>
            </td>
<td>
                Occurs when the display settings are changing.
            </td>
</tr>
<tr>
<td>
                <code>EventsThreadShutdown</code>
            </td>
<td>
                Occurs before the thread that listens for system events is terminated.
            </td>
</tr>
<tr>
<td>
                <code>InstalledFontsChanged</code>
            </td>
<td>
                Occurs when the user adds fonts to or removes fonts from the system.
            </td>
</tr>
<tr>
<td>
                <code>LowMemory</code>
            </td>
<td>
                Obsolete. Occurs when the system is running out of available RAM.
            </td>
</tr>
<tr>
<td>
                <code>PaletteChanged</code>
            </td>
<td>
                Occurs when the user switches to an application that uses a different palette.
            </td>
</tr>
<tr>
<td>
                <code>PowerModeChanged</code>
            </td>
<td>
                Occurs when the user suspends or resumes the system.
            </td>
</tr>
<tr>
<td>
                <code>SessionEnded</code>
            </td>
<td>
                Occurs when the user is logging off or shutting down the system.
            </td>
</tr>
<tr>
<td>
                <code>SessionEnding</code>
            </td>
<td>
                Occurs when the user is trying to log off or shut down the system.
            </td>
</tr>
<tr>
<td>
                <code>SessionSwitch</code>
            </td>
<td>
                Occurs when the currently logged-in user has changed.
            </td>
</tr>
<tr>
<td>
                <code>TimeChanged</code>
            </td>
<td>
                Occurs when the user changes the time on the system clock.
            </td>
</tr>
<tr>
<td>
                <code>TimerElapsed</code>
            </td>
<td>
                Occurs when a windows timer interval has expired.
            </td>
</tr>
<tr>
<td>
                <code>UserPreferenceChanged</code>
            </td>
<td>
                Occurs when a user preference has changed.
            </td>
</tr>
<tr>
<td>
                <code>UserPreferenceChanging</code>
            </td>
<td>
                Occurs when a user preference is changing.
            </td>
</tr>
</tbody>
</table>
<p><span id="more-1462"></span></p>
<p class="note"><strong>Note:</strong> Some of these system events may not be raised on Windows Vista. </p>
<h4>Example Application</h4>
<p>As an example let&#8217;s create a simple <em>Windows Forms Application</em> and place two buttons and a textbox on the main form. The buttons are going to subscribe and unsubscribe from the system events and the textbox is going to display the captured event details.</p>
<p>In our application we are going to listen for the following four system events: <code>InstalledFontsChanged</code>, <code>DisplaySettingsChanged</code>, <code>TimeChanged</code>, and <code>UserPreferenceChanged</code>. The code for this is shown below:</p>
<pre>
private bool eventHandlersCreated;

private void btnStartListening_Click(object sender, EventArgs e)
{
    this.StartListening();
}

private void btnStopListening_Click(object sender, EventArgs e)
{
    this.StopListening();
}

private void StartListening()
{
    Microsoft.Win32.SystemEvents.InstalledFontsChanged += new EventHandler(FontHandler);
    Microsoft.Win32.SystemEvents.DisplaySettingsChanged += new EventHandler(ScreenHandler);
    Microsoft.Win32.SystemEvents.TimeChanged += new EventHandler(TimeHandler);
    Microsoft.Win32.SystemEvents.UserPreferenceChanged += new Microsoft.Win32.UserPreferenceChangedEventHandler(PreferenceChangedHandler);

    this.eventHandlersCreated = true;
}

private void StopListening()
{
    Microsoft.Win32.SystemEvents.InstalledFontsChanged -= new EventHandler(FontHandler);
    Microsoft.Win32.SystemEvents.DisplaySettingsChanged -= new EventHandler(ScreenHandler);
    Microsoft.Win32.SystemEvents.TimeChanged -= new EventHandler(TimeHandler);
    Microsoft.Win32.SystemEvents.UserPreferenceChanged -= new Microsoft.Win32.UserPreferenceChangedEventHandler(PreferenceChangedHandler);

    this.eventHandlersCreated = false;
}
</pre>
<p>As you can see in the <code>StartListening</code> and <code>StopListening</code> methods we are subscribing and unsibscribing to the system events. Each event handler delegate is calling a particular method, and these methods are shown below:</p>
<pre>
private void FontHandler(object sender, EventArgs e)
{
    txtStatus.Text += string.Format("Installed fonts changed. {0}", Environment.NewLine);
}

private void PreferenceChangedHandler(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e)
{
    txtStatus.Text += string.Format("You changed a setting: {0} {1}", e.Category.ToString(), Environment.NewLine);
}

private void ScreenHandler(object sender, EventArgs e)
{
    txtStatus.Text += string.Format("Screen resolution changed. {0}", Environment.NewLine);
}

private void TimeHandler(object sender, EventArgs e)
{
    txtStatus.Text += string.Format("System time changed. {0}", Environment.NewLine);
}
</pre>
<p>If you were to run this application and then go and change the screen resolution for example, the <code>DisplaySettingsChanged</code> event will fire and its delegate will call our <code>ScreenHandler</code> method, and you will see the text <em>Screen resolution changed</em> in the textbox.</p>
<p>Below is a screenshot of our application:</p>
<p><img style=' display: block; margin-right: auto; margin-left: auto;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/10/system_events.jpg" alt="" title="" width="368" height="314" class="aligncenter size-full wp-image-1478" /></p>
<p class="alert"><strong>Note:</strong> Since these system events are static events, you must make sure you detach your event handlers when disposing your application, or you will end up with memory leaks!</p>
<p>To take care of this memory leak potential problem, when closing our application we are calling the <code>StopListening</code> method to unsubscribe from the event handlers.</p>
<pre>
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.eventHandlersCreated)
        this.StopListening();
}
</pre>
<p class="alert"><strong>Another Note:</strong> Do not perform time-consuming processing on the same thread that raises a system event handler because it might prevent other applications from functioning.</p>
<p>If your application must perform time-consuming processes, do the processing on a separate worker thread and not on the same thread which raises the system events. If you want more information on worker threads you can have a look at my articles &#8211; <a href="http://www.daveoncsharp.com/2009/09/create-a-worker-thread-for-your-windows-form-in-csharp/">Create a Worker Thread for your Windows Form in C#</a> and <a href="http://www.daveoncsharp.com/2009/09/using-the-backgroundworker-component-in-csharp/">Using the BackgroundWorker Component in C#</a>.</p>
<p>I hope you found this useful. Thanks for reading.</p>
<p>Dave</p>
<div class='yarpp-related-rss'>
<br /><p>Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/09/monitoring-the-file-system-for-changes/' rel='bookmark' title='Monitoring the File System for Changes'>Monitoring the File System for Changes</a></li>
<li><a href='http://www.daveoncsharp.com/2009/08/add-notify-icon-to-system-tray/' rel='bookmark' title='Add a Notify Icon to the System Tray with C#'>Add a Notify Icon to the System Tray with C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/06/windows-forms-event-sequence/' rel='bookmark' title='Windows Forms Event Sequence'>Windows Forms Event Sequence</a></li>
</ol></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=uVg-NPZujBs:NCj2-dfU_FM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=uVg-NPZujBs:NCj2-dfU_FM:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?i=uVg-NPZujBs:NCj2-dfU_FM:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DaveOnCSharp/~4/uVg-NPZujBs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncsharp.com/2009/10/how-to-capture-system-events-using-csharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.daveoncsharp.com/2009/10/how-to-capture-system-events-using-csharp/</feedburner:origLink></item>
		<item>
		<title>Enumerating and Controlling Windows Services with C#</title>
		<link>http://feedproxy.google.com/~r/DaveOnCSharp/~3/Pbo2hDAYa8Y/</link>
		<comments>http://www.daveoncsharp.com/2009/10/enumerating-and-controlling-windows-services-with-csharp/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 19:05:17 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Operating System]]></category>
		<category><![CDATA[Manifest]]></category>
		<category><![CDATA[Services]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.daveoncsharp.com/?p=1442</guid>
		<description><![CDATA[The Microsoft.NET Framework contains a component called the ServiceController. It is designed to allow you to control a Windows Service. With this component you can easily start, stop, and pause services, and you can also retrieve information on the service such as its display name and status among others. In this article I am going [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/08/writing-to-the-windows-event-log-using-csharp/' rel='bookmark' title='Writing To The Windows Event Log Using C#'>Writing To The Windows Event Log Using C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/08/read-write-delete-from-windows-registry-with-csharp/' rel='bookmark' title='How to Read, Write, and Delete from the Windows Registry with C#'>How to Read, Write, and Delete from the Windows Registry with C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/07/hibernate-or-standby-windows-programmatically/' rel='bookmark' title='Hibernate or Standby Windows Programmatically'>Hibernate or Standby Windows Programmatically</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p></p><p><img style=' float: left; padding: 4px; margin: 0 7px 2px 0;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/10/keyb.jpg" alt="" title="" width="200" height="149" class="alignleft size-full wp-image-1444" />The Microsoft.NET Framework contains a component called the <code>ServiceController</code>. It is designed to allow you to control a Windows Service. With this component you can easily start, stop, and pause services, and you can also retrieve information on the service such as its display name and status among others.</p>
<p>In this article I am going to show you how to use this <code>ServiceController</code> component and also how to enumerate the services running on your pc.</p>
<h4>Enumerating Windows Services</h4>
<p>To get a list of services running on a pc, we need to use the <code>System.ServiceProcess.ServiceController</code> class. The below code is using a static method called <code>GetServices</code> to return an array of <code>ServiceController</code> objects. Then the array is iterated and we are displaying the services&#8217; information in a <code>ListView</code> component.</p>
<pre>
private void GetServices()
{
    try
    {
        lstServices.Items.Clear();

        ServiceController[] svcs = ServiceController.GetServices();

        foreach (ServiceController svc in svcs)
        {
            ListViewItem item = new ListViewItem();
            item.Text = svc.DisplayName;
            item.SubItems.Add(svc.ServiceName);
            item.SubItems.Add(svc.Status.ToString());

            lstServices.Items.Add(item);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
</pre>
<p>The below screenshot shows our ListView populated with the Windows services.</p>
<p><img style=' display: block; margin-right: auto; margin-left: auto;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/10/screenshot.jpg" alt="" title="" width="546" height="316" class="aligncenter size-full wp-image-1450" /></p>
<p><span id="more-1442"></span></p>
<h4>Controlling Windows Services</h4>
<p>Now that we have a list of all the services running on our pc, we can use the <code>ServiceController</code> component to control any one of them.</p>
<p>To assign one of the selected services in the <code>ListView</code> to the <code>ServiceController</code> we must set the <code>ServiceName</code> property as shown below:</p>
<pre>
private void lstServices_SelectedIndexChanged(object sender, EventArgs e)
{
    if (lstServices.SelectedItems.Count > 0)
        this.serviceController.ServiceName = lstServices.SelectedItems[0].SubItems[1].Text.Trim();
}
</pre>
<p>Next we are using the <code>Stop</code> and <code>Start</code> methods of the <code>ServiceController</code> component to control the selected service. The code for this can be seen below:</p>
<pre>
private void btnStop_Click(object sender, EventArgs e)
{
    if (this.serviceController.CanStop)
    {
        this.serviceController.Stop();
        this.GetServices();
    }
}

private void btnStart_Click(object sender, EventArgs e)
{
    this.serviceController.Start();
    this.GetServices();
}
</pre>
<p>After we stop or start the selected service we are calling our <code>GetServices</code> method to re-populate the <code>ListView</code> so that we can see the updated statuses of our services.</p>
<h4>The app.manifest File</h4>
<p>Since we are accessing parts of the Windows operating system which require administrative privelages, we must add an <code>app.manifest</code> file to our project and set the <code>requestedExecutionLevel</code> to <code>requireAdministrator</code> if we are to run this code on <em>Windows Vista</em> or later.</p>
<pre>
&lt;requestedExecutionLevel level="requireAdministrator" uiAccess="false" /&gt;
</pre>
<p>I have already covered how to create and use an <code>app.manifest</code> file in a previous article, so if you want further information you can check it out here: <a href="http://www.daveoncsharp.com/2009/08/writing-to-the-windows-event-log-using-csharp/">Writing To The Windows Event Log Using C#</a></p>
<p>Those are the basics that you need to know to control a Windows Service. </p>
<p>I hope you found this article useful. Stay tuned for more soon.</p>
<p>Dave</p>
<div class='yarpp-related-rss'>
<br /><p>Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/08/writing-to-the-windows-event-log-using-csharp/' rel='bookmark' title='Writing To The Windows Event Log Using C#'>Writing To The Windows Event Log Using C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/08/read-write-delete-from-windows-registry-with-csharp/' rel='bookmark' title='How to Read, Write, and Delete from the Windows Registry with C#'>How to Read, Write, and Delete from the Windows Registry with C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/07/hibernate-or-standby-windows-programmatically/' rel='bookmark' title='Hibernate or Standby Windows Programmatically'>Hibernate or Standby Windows Programmatically</a></li>
</ol></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=Pbo2hDAYa8Y:_jaabhIyirs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=Pbo2hDAYa8Y:_jaabhIyirs:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?i=Pbo2hDAYa8Y:_jaabhIyirs:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DaveOnCSharp/~4/Pbo2hDAYa8Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncsharp.com/2009/10/enumerating-and-controlling-windows-services-with-csharp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.daveoncsharp.com/2009/10/enumerating-and-controlling-windows-services-with-csharp/</feedburner:origLink></item>
		<item>
		<title>How to use Temporary Files in C#</title>
		<link>http://feedproxy.google.com/~r/DaveOnCSharp/~3/TUqwIqjaH48/</link>
		<comments>http://www.daveoncsharp.com/2009/09/how-to-use-temporary-files-in-csharp/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 20:34:34 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Files and Directories]]></category>
		<category><![CDATA[Operating System]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Temp]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.daveoncsharp.com/?p=1427</guid>
		<description><![CDATA[What exactly is a temporary file? Put simply, a temporary file is a file used by an application for storing temporary data. There is no fixed rule which specifies what this data should be, but generally temporary files (or temp files) are used for storing &#8216;work data&#8216;. For example Microsoft Office uses temp files to [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/07/file-comparison-in-csharp-part-1/' rel='bookmark' title='File Comparison in C# &#8211; Part 1'>File Comparison in C# &#8211; Part 1</a></li>
<li><a href='http://www.daveoncsharp.com/2009/07/recursively-search-directories/' rel='bookmark' title='Recursively Search Directories'>Recursively Search Directories</a></li>
<li><a href='http://www.daveoncsharp.com/2009/07/file-comparison-in-csharp-part-2/' rel='bookmark' title='File Comparison in C# – Part 2'>File Comparison in C# – Part 2</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p></p><p><img style=' float: right; padding: 4px; margin: 0 0 2px 7px;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/09/tempfiles.jpg" alt="" title="" width="150" height="200" class="alignright size-full wp-image-1436" />What exactly is a temporary file? Put simply, a temporary file is a file used by an application for storing temporary data. There is no fixed rule which specifies what this data should be, but generally temporary files (or temp files) are used for storing &#8216;<em>work data</em>&#8216;. For example Microsoft Office uses temp files to store backups of documents being created or edited. Other applications might use temp files to store large amounts of data which would otherwise occupy too much memory. Basically, it is up to the developer to decide what should be kept within his/her application&#8217;s temp files.</p>
<p>In Microsoft Windows, temp files end with the <strong>.tmp</strong> extension and by default are stored in <em>C:\Users\[username]\AppData\Local\Temp</em>.</p>
<p>The .NET Framework makes creating and using temp files a breeze, so let me show you how to use them.</p>
<p>Create a new <em>Console Application</em> and add a method called <code>CreateTmpFile</code>. In this method we will use the <code>System.IO.Path</code> class to create our temp file.</p>
<pre>
private static string CreateTmpFile()
{
    string fileName = string.Empty;

    try
    {
        // Get the full name of the newly created Temporary file. 
        // Note that the GetTempFileName() method actually creates
        // a 0-byte file and returns the name of the created file.
        fileName = Path.GetTempFileName();

        // Craete a FileInfo object to set the file's attributes
        FileInfo fileInfo = new FileInfo(fileName);

        // Set the Attribute property of this file to Temporary. 
        // Although this is not completely necessary, the .NET Framework is able 
        // to optimize the use of Temporary files by keeping them cached in memory.
        fileInfo.Attributes = FileAttributes.Temporary;

        Console.WriteLine("TEMP file created at: " + fileName);
    }
    catch (Exception ex)
    {
       Console.WriteLine("Unable to create TEMP file or set its attributes: " + ex.Message);
    }

    return fileName;
}
</pre>
<p><span id="more-1427"></span></p>
<p>As you can see in the above code we are calling the <code>GetTempFileName</code> method of the <code>Path</code> class to create our temp file. When called, this method will automatically create the temp file in the correct folder according to your version of Windows. Then we are creating a <code>FileInfo</code> object and setting the <code>Temporary</code> attribute of our temp file. You can work without setting this attribute, but it is recommended to set it since the .NET Framework will optimize the way it uses your temp file if set.</p>
<p>And that&#8217;s all you need to do to create a temp file. The temp file&#8217;s name is automatically generated and looks something like this: <em>tmpBD28.tmp</em>.</p>
<p>Now let&#8217;s write some data to our temp file:</p>
<pre>
private static void UpdateTmpFile(string tmpFile)
{
    try
    {
        // Write to the temp file.
        StreamWriter streamWriter = File.AppendText(tmpFile);
        streamWriter.WriteLine("Hello from www.daveoncsharp.com!");
        streamWriter.Flush();
        streamWriter.Close();

        Console.WriteLine("TEMP file updated.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error writing to TEMP file: " + ex.Message);
    }
}
</pre>
<p>As you can see all we are doing here is opening the temp file using the <code>StreamWriter</code> class and then writing to it. It&#8217;s just like writing to a normal text file.</p>
<p>To read from the temp file is quite similar:</p>
<pre>
private static void ReadTmpFile(string tmpFile)
{
    try
    {
        // Read from the temp file.
        StreamReader myReader = File.OpenText(tmpFile);
        Console.WriteLine("TEMP file contents: " + myReader.ReadToEnd());
        myReader.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error reading TEMP file: " + ex.Message);
    }
}
</pre>
<p>Once you&#8217;re done using the temp file you need to delete it or else it will obviously remain there, and over time these files will end up filling your temp folder.</p>
<pre>
private static void DeleteTmpFile(string tmpFile)
{
    try
    {
        // Delete the temp file (if it exists)
        if (File.Exists(tmpFile))
        {
            File.Delete(tmpFile);
            Console.WriteLine("TEMP file deleted.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error deleteing TEMP file: " + ex.Message);
    }
}
</pre>
<p>Once you create all the above methods, you can call them for testing purposes as shown below:</p>
<pre>
static void Main(string[] args)
{
    string tmpFile = CreateTmpFile();
    UpdateTmpFile(tmpFile);
    ReadTmpFile(tmpFile);
    DeleteTmpFile(tmpFile);

    Console.ReadLine();
}
</pre>
<p>Another useful method within the <code>Path</code> class is the <code>GetTempPath()</code> method. This returns the path of the current system&#8217;s temporary folder, which you might want when working with temp files.</p>
<p>I hope you found this article useful. Feel free to add comments or ask any questions below.</p>
<p>Dave</p>
<div class='yarpp-related-rss'>
<br /><p>Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/07/file-comparison-in-csharp-part-1/' rel='bookmark' title='File Comparison in C# &#8211; Part 1'>File Comparison in C# &#8211; Part 1</a></li>
<li><a href='http://www.daveoncsharp.com/2009/07/recursively-search-directories/' rel='bookmark' title='Recursively Search Directories'>Recursively Search Directories</a></li>
<li><a href='http://www.daveoncsharp.com/2009/07/file-comparison-in-csharp-part-2/' rel='bookmark' title='File Comparison in C# – Part 2'>File Comparison in C# – Part 2</a></li>
</ol></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=TUqwIqjaH48:E-6r0KUCvIQ:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=TUqwIqjaH48:E-6r0KUCvIQ:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?i=TUqwIqjaH48:E-6r0KUCvIQ:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DaveOnCSharp/~4/TUqwIqjaH48" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncsharp.com/2009/09/how-to-use-temporary-files-in-csharp/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://www.daveoncsharp.com/2009/09/how-to-use-temporary-files-in-csharp/</feedburner:origLink></item>
		<item>
		<title>Monitoring the File System for Changes</title>
		<link>http://feedproxy.google.com/~r/DaveOnCSharp/~3/b2gzV3HSZc8/</link>
		<comments>http://www.daveoncsharp.com/2009/09/monitoring-the-file-system-for-changes/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 21:17:04 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Files and Directories]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[Comparison]]></category>
		<category><![CDATA[Directory]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[File]]></category>

		<guid isPermaLink="false">http://www.daveoncsharp.com/?p=1402</guid>
		<description><![CDATA[In this article I am going to show you how to monitor a folder for changes. A reason why you might want to do this is for example if you want to keep two files in different locations in sync. When the original file is changed it would trigger an event and you can update [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/10/how-to-capture-system-events-using-csharp/' rel='bookmark' title='How to Capture System Events using C#'>How to Capture System Events using C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/08/add-notify-icon-to-system-tray/' rel='bookmark' title='Add a Notify Icon to the System Tray with C#'>Add a Notify Icon to the System Tray with C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/07/using-the-settings-file-in-csharp/' rel='bookmark' title='Using the Settings file in C#'>Using the Settings file in C#</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p></p><p><img style=' float: left; padding: 4px; margin: 0 7px 2px 0;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/09/monitoring.jpg" alt="" title="" width="200" height="135" class="alignleft size-full wp-image-1422" />In this article I am going to show you how to monitor a folder for changes. A reason why you might want to do this is for example if you want to keep two files in different locations in sync. When the original file is changed it would trigger an event and you can update the copy in the other location with the updated original file. </p>
<p>The .NET framework provides a component called the <code>FileSystemWatcher</code> which is designed to do exactly what its name suggests &#8211; watch the file system for changes. Let&#8217;s create an example which uses this component.</p>
<p>Create a new <em>Windows Forms Application</em> project and design a form which looks similar to the one below:</p>
<p><a href="http://www.daveoncsharp.com/wp-content/uploads/2009/09/screenshot1.jpg"><img style=' display: block; margin-right: auto; margin-left: auto;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/09/screenshot1_small.jpg" alt="" title="" width="400" height="252" class="aligncenter size-full wp-image-1406" /></a></p>
<p>Then add a <code>FileSystemWatcher</code> component to your form from the <em>Components Toolbox</em> in Visual Studio.</p>
<p>Next we&#8217;ll configure the <code>FileSystemWatcher</code> and start monitoring a folder in the <em>Monitor</em> button&#8217;s event handler. The code for this is shown below:</p>
<pre>
private void btnMonitor_Click(object sender, EventArgs e)
{
    try
    {
        // Watch for changes on this path
        fileSystemWatcher.Path = txtPath.Text.Trim();
        
        // Watch for changes on all files
        fileSystemWatcher.Filter = "*.*";

        // Also watch for changes within sub directories
        fileSystemWatcher.IncludeSubdirectories = true;

        // Begin watching
        fileSystemWatcher.EnableRaisingEvents = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
</pre>
<p><span id="more-1402"></span></p>
<p>As you can see the code is quite self explanatory. We are starting the <code>FileSystemWatcher</code> by setting its <code>EnableRaisingEvents</code> property to <code>true</code>. </p>
<p>Next we must subscribe to its four events &#8211; the <code>Changed</code>, <code>Created</code>, <code>Deleted</code>, and <code>Renamed</code> events. </p>
<pre>
private void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
    txtStatus.Text = string.Format("{0} {1} changed. {2}", 
                                   txtStatus.Text, 
                                   e.FullPath, 
                                   Environment.NewLine);
}

private void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
    txtStatus.Text = string.Format("{0} {1} created. {2}", 
                                   txtStatus.Text, 
                                   e.FullPath, 
                                   Environment.NewLine);
}

private void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
    txtStatus.Text = string.Format("{0} {1} deleted. {2}", 
                                   txtStatus.Text, 
                                   e.FullPath, 
                                   Environment.NewLine);
}

private void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
{
    txtStatus.Text = string.Format("{0} {1} renamed. {2}", 
                                   txtStatus.Text, 
                                   e.FullPath, 
                                   Environment.NewLine);
}
</pre>
<p>When each of the above events fires, we are updating the main textbox (<code>txtStatus</code>) with some text which describes the event. A screenshot of this can be seen below:</p>
<p><a href="http://www.daveoncsharp.com/wp-content/uploads/2009/09/screenshot2.jpg"><img style=' display: block; margin-right: auto; margin-left: auto;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/09/screenshot2_small.jpg" alt="" title="" width="400" height="252" class="aligncenter size-full wp-image-1409" /></a></p>
<p>As you can see from the screenshot above, whenever a file is added the <code>FileSystemWatcher</code> is firing a change event for the folder and two more for the file. If many files are added to that directory at once our application could easily be swamped by an unceasing series of events. That&#8217;s where the <code>NotifyFilter</code> property comes in.</p>
<p>The <code>NotifyFilter</code> property allows you indicate which type of changes you want to monitor. It can be set using any combination of the following values from the <code>NotifyFilters</code> enumeration:</p>
<pre>
public enum NotifyFilters
{
    // The name of the file.
    FileName = 1,
    // The name of the directory.
    DirectoryName = 2,
    // The attributes of the file or folder.
    Attributes = 4,
    // The size of the file or folder.
    Size = 8,
    // The date the file or folder last had anything written to it.
    LastWrite = 16,
    // The date the file or folder was last opened.
    LastAccess = 32,
    // The time the file or folder was created.
    CreationTime = 64,
    // The security settings of the file or folder.
    Security = 256,
}
</pre>
<p>You can combine these values using bitwise arithmetic as shown below:</p>
<pre>
fileSystemWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size;
</pre>
<p>This line of code is telling the <code>FileSystemWatcher</code> to only watch for changes to file names and file sizes. If one of these changes occurs the <code>fileSystemWatcher_Changed</code> event will fire. If, for example, a change to a file attribute occurs, such as a file is set to read-only, the change event will not fire. For it to fire we must add <code>NotifyFilters.Attributes</code> to the <code>NotifyFilter</code> values.</p>
<p>Now you should have a clear understanding of how to monitor the file system for changes using the .NET <code>FileSystemWatcher</code> component.</p>
<p>If you liked this article you can subscribe to my full RSS feed <a href="http://www.daveoncsharp.com/feed/">here</a>. Please feel free to leave any questions or comments below. </p>
<p>Dave</p>
<div class='yarpp-related-rss'>
<br /><p>Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/10/how-to-capture-system-events-using-csharp/' rel='bookmark' title='How to Capture System Events using C#'>How to Capture System Events using C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/08/add-notify-icon-to-system-tray/' rel='bookmark' title='Add a Notify Icon to the System Tray with C#'>Add a Notify Icon to the System Tray with C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/07/using-the-settings-file-in-csharp/' rel='bookmark' title='Using the Settings file in C#'>Using the Settings file in C#</a></li>
</ol></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=b2gzV3HSZc8:fFanBEmBl1o:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=b2gzV3HSZc8:fFanBEmBl1o:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?i=b2gzV3HSZc8:fFanBEmBl1o:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DaveOnCSharp/~4/b2gzV3HSZc8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncsharp.com/2009/09/monitoring-the-file-system-for-changes/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.daveoncsharp.com/2009/09/monitoring-the-file-system-for-changes/</feedburner:origLink></item>
		<item>
		<title>Formatting Decimals in C#</title>
		<link>http://feedproxy.google.com/~r/DaveOnCSharp/~3/G6ZeG2QfY80/</link>
		<comments>http://www.daveoncsharp.com/2009/09/formatting-decimals-in-csharp/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 21:29:44 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[String Operations]]></category>
		<category><![CDATA[Decimal]]></category>
		<category><![CDATA[Format]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://www.daveoncsharp.com/?p=1385</guid>
		<description><![CDATA[In this post I am going to show you a few different ways how you can format a decimal number (float, double, or decimal). Setting the Maximum Allowed Decimal Places To format your numbers to a maximum of two decimal places use the format string {0:0.##} as shown in the below example: string.Format("{0:0.##}", 256.583); // [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/09/formatting-integers-in-csharp/' rel='bookmark' title='Formatting Integers in C#'>Formatting Integers in C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/09/formatting-a-datetime-object-in-csharp/' rel='bookmark' title='Formatting a DateTime Object in C#'>Formatting a DateTime Object in C#</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p></p><p><img style=' float: right; padding: 4px; margin: 0 0 2px 7px;'  src="http://www.daveoncsharp.com/wp-content/uploads/2009/09/decimal.jpg" alt="" title="" width="198" height="88" class="alignright size-full wp-image-1398" />In this post I am going to show you a few different ways how you can format a decimal number (<code>float</code>, <code>double</code>, or <code>decimal</code>).</p>
<h4>Setting the Maximum Allowed Decimal Places</h4>
<p>To format your numbers to a maximum of two decimal places use the format string <code>{0:0.##}</code> as shown in the below example:</p>
<pre>
string.Format("{0:0.##}", 256.583); // "256.58"
string.Format("{0:0.##}", 256.586); // "256.59"
string.Format("{0:0.##}", 256.58);  // "256.58"
string.Format("{0:0.##}", 256.5);   // "256.5"
string.Format("{0:0.##}", 256.0);   // "256"
</pre>
<h4>Setting a Fixed Amount of Decimal Places</h4>
<p>This is similar to the above example but instead of hashes (<strong>&#8216;#&#8217;</strong>) in our format string we are going to use zeroes (<strong>&#8217;0&#8242;</strong>) as shown below:</p>
<pre>
string.Format("{0:0.00}", 256.583); // "256.58"
string.Format("{0:0.00}", 256.586); // "256.59"
string.Format("{0:0.00}", 256.58);  // "256.58"
string.Format("{0:0.00}", 256.5);   // "256.50"
string.Format("{0:0.00}", 256.0);   // "256.00"
</pre>
<h4>The Thousand Separator</h4>
<p>To format your decimal number using the <em>thousand separator</em>, use the format string <code>{0:0,0}</code> as shown in the below example:</p>
<pre>
string.Format("{0:0,0.00}", 1234256.583); // "1,234,256.58"
string.Format("{0:0,0}", 1234256.583);    // "1,234,257"
</pre>
<p><span id="more-1385"></span></p>
<h4>Setting a Fixed Amount of Digits Before the Decimal Point</h4>
<p>To set a minimum amount of three digits before the decimal point use the format string <code>{0:000.##}</code>.</p>
<pre>
string.Format("{0:00.000}", 1.2345);    // "01.235"
string.Format("{0:000.000}", 12.345);   // "012.345"
string.Format("{0:0000.000}", 123.456); // "0123.456"
</pre>
<h4>Alignment</h4>
<p>To specify alignment to the <code>Format</code> method you must write your format string as shown below. Note we are using a comma (<strong>&#8216;,&#8217;</strong>) to specify the number of characters used for alignment.</p>
<p><code>{0,[no. of chars]}</code> and if you want to pad with zeroes <code>{0,[no. of chars]:00.00}</code></p>
<pre>
string.Format("{0,7:##.00}", 2.356);  // "   2.36"
string.Format("{0,-7:##.00}", 2.356); // "2.36   "
string.Format("{0,7:00.00}", 2.356);  // "  02.36"
string.Format("{0,-7:00.00}", 2.356); // "02.36  "
</pre>
<h4>Positive Numbers, Negative Numbers, and Zero</h4>
<p>You can include different formats for positive numbers, negative numbers, and zero by using the semicolon character (<strong>&#8216;;&#8217;</strong>).</p>
<p>Format string:<br />
<code>{0:[positive];[negative];[zero]}</code></p>
<pre>
string.Format("{0:000.000;(000.000);zero}", 23.43);  // "023.430"
string.Format("{0:000.000;(000.000);zero}", -23.43); // "(023.430)"
string.Format("{0:000.000;(000.000);zero}", 0.0);    // "zero"
</pre>
<h4>Some Pre-Defined Formats</h4>
<pre>
string.Format("{0:C}", 1532.236);  // "£1,532.24"
string.Format("{0:C}", -1532.236); // "-£1,532.24"
string.Format("{0:E}", 1532.236);  // "1.532236E+003"
string.Format("{0:E}", -1532.236); // "-1.532236E+003"
string.Format("{0:F}", 1532.24);   // "1532.24"
string.Format("{0:F}", -1532.24);  // "-1532.24"
string.Format("{0:G}", 1532.236);  // "1532.236"
string.Format("{0:G}", -1532.236); // "-1532.236"
string.Format("{0:N}", 1532.236);  // "1,532.24"
string.Format("{0:N}", -1532.236); // "-1,532.24"
string.Format("{0:P}", 0.1532);    // "15.32 %"
string.Format("{0:P}", -0.1532);   // "-15.32 %"
string.Format("{0:R}", 1532.236);  // "1532.236"
string.Format("{0:R}", -1532.236); // "-1532.236"
</pre>
<p>Happy formatting. <img src='http://www.daveoncsharp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
Dave</p>
<div class='yarpp-related-rss'>
<br /><p>Related posts:<ol>
<li><a href='http://www.daveoncsharp.com/2009/09/formatting-integers-in-csharp/' rel='bookmark' title='Formatting Integers in C#'>Formatting Integers in C#</a></li>
<li><a href='http://www.daveoncsharp.com/2009/09/formatting-a-datetime-object-in-csharp/' rel='bookmark' title='Formatting a DateTime Object in C#'>Formatting a DateTime Object in C#</a></li>
</ol></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=G6ZeG2QfY80:1LTfCvjBLC4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DaveOnCSharp?a=G6ZeG2QfY80:1LTfCvjBLC4:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DaveOnCSharp?i=G6ZeG2QfY80:1LTfCvjBLC4:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DaveOnCSharp/~4/G6ZeG2QfY80" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncsharp.com/2009/09/formatting-decimals-in-csharp/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://www.daveoncsharp.com/2009/09/formatting-decimals-in-csharp/</feedburner:origLink></item>
	</channel>
</rss>
