.NET 101





.NET is basically an interface for a single programming language. MSIL, However languages can be written to be compliant with MSIL and thus usable with the .NET framework.


Using System

Most Basic Project setup

Hello World


Using System.Text


            String / StringBuilder

                        Strings are immutable (non appendable) thus very inefficient when there are multiple changes to the value.

                        My habit I’ve tried to develop is anytime I am using += more than once or twice I use a StringBuilder.


            Array / ArrayList

                        Array List had Dynamic Resisizing

:Add method so you don’t have to keep track of last index.

:Remove/ RemoveAt / RemoveRange  Method


 Also properties: Count



Using System.Web

            Web Controls (except Data grid) and Data Binding

All controls are Server Controls when dropped off the toolbox. This means they are very useful, unless you want to do some client side processing to avoid trips to the server. If this is your desire then you need to use handbuild HTML clientside controls.


All Controls inherit from Control Class (Buttons including regular/radio/checkboxes inherit from ButtonClass which inherits from Control Class.

Basic, most commonly used Control Class Properites.

Anchor (Anchors when window resized), BackColor, Dock(Docks to edges of window), Enabled, ForeColor, Height, Left, Name, Parent, Right, TabIndex, TabStop, Tag(a spot to store additional data associated with the control, Often used to hold valid or not), Top, Visible, Width


.Text is most commonly used Property                                                   


Warning if you use Multiline = True, then it changes when it renders from an HTML TextBox to a HTML TextArea which changes some of the available events.      Specifically maxlength property is inaccessible.                            

                        Buttons / ImageButtons / Link Buttons


                                    SelectedItem most commonly used property                                           

                        ComboBox / DropDowns

SelectedItem most commonly used property       


ListItem and ListItemCollection are two key objects for interfacing with List Controls



                        **DataBind must be in !Page.IsPostBack if later events to avoid rebinding everything which clears your values that you think you have.


Here is a list of some of the other controls that we won’t be going over today, but are available.

                        ListBox, ListView, GroupBox/Panel, RichTextBox, StatusBar, ImageList, TabControl, Validators, Calendar              



Using System.IO


The Base class is the StreamReader, but the functionality of the TextReader and XMLReader are very similar.

Key code to remember: stringreaderExample.Peek()>-1






Using System.XML

Key code: SelectNodes

Xpath is like a folder system -- 10 Second intro to Xpath

                        / represents absolute path, // relative path, * wildcard, //@ for attributes, [1], selects first , count( ) returns count, starts-with ( )..


                        Sample XML

<?xml version='1.0' encoding='ISO-8859-1'?>


<cd country='USA'>

<title>Empire Burlesque</title>

<artist>Bob Dylan</artist>



<cd country='UK'>

<title>Hide your heart</title>

<artist>Bonnie Tyler</artist>



<cd country='USA'>

<title>Greatest Hits</title>

<artist>Dolly Parton</artist>





State / Request / QueryString


Key code: String s = Request.QueryString["Name"];

Getting an item passed through can be grabbed in C# or Javascript. The most common way is to grab in C#

vVariable = Request["Variable "]

then get in javascript alert(‘<%=vVariable%>’)


In order to hold a value through multiple postbacks putting an variable in to “ViewState” is often the simplest way to go.


Application level state can be controlled through global.asax

                        Session Level state can be controlled using Session[anyvarname”]










                        Can still use, but must be perfect syntax            




More Complex Project Setup

The best architecture for multiple developer .NET projects is utilizing SourceSafe.

On a server you have the original copy of the Project. Whenever you work on the project you check it out and work locally on your machine. (The whole project is running on your machine, not just the file. – Thus you must ‘Get Latest Version’ of the entire project regularly to ensure you have updated code for the pages that you are not checking out.) Then when you are done you check it back in which mouse it back to the Server. You can then do a build on this Server to update this server. This server can be your Live Server, in which case you are done….or for an extra layer of comfort, this can be your Dev machine. The Live Server is just like any other machine/user who checks never checks out stuff. Because you can do a ‘Get Latest Version’ of only a few files or do a ‘Get Latest Version’ of the whole project you can very safely update small sections of your website.


One more hint : Don’t start page names with numbers – Confuses C#

                        References/ Web References (add web.mail to windows form)



                        Copy Project

                                    You must use this to move a project, copy and paste in Windows Explorer doesn’t work.

If you are not using SourceSafe this is the simplest way to move files back and forth. However there is no project management. You simply overwrite the Live Server.

                        Bulk Comment/Uncomment

                        Go to Definition / Reference…

                        Region Blocks

                                    # region Mail and IO functions / # endregion

                        Design View Format – Align lefts, Make same size, snap to grid

                        += works in c# and vb.              


Using System.Net



Key objects – HttpWebRequest, HttpWebResponse.

Sample Code

HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(strURL);

                                    HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();

                                    string stringResult;

                                    using (StreamReader sR = new StreamReader(HttpWResp.GetResponseStream()))


                                                stringResult = sR.ReadToEnd();


                                    }// Insert code that uses the response object.




Using System.Data / System.Data.SqlClient

            Data Access


                        ADO.NET is very similar looking to ADO at first glance but very different the more your find.

                        Both use the connection and command object, and the recordset is relatively similar to the dataset object. That said…

                        SqlClient is faster than OldDb for SqlServer.


Connection object – very similar to the ADO connection. 99%  of connection strings work for ADO.NET


The command object is similar but with enhancements. The command object is exposes the Reader object which cannot be directly instantiated. Thus the only way to utilize is through the Reader’s Methods

ExecuteNonQuery (Returns nothing),

ExecuteScalar (returns a single string)

ExecuteReader (a forward-only, read-only DataSet) is through the Command object.

ExecuteXMLReader which returns an XML document


A dataset is a disconnected set of data and can represent tables or multiple tables. It is usually built through the dataAdapter’s object fill method.


            More Controls

                        DataGrid, DataList, Repeater

**DataBind must be in !Page.IsPostBack if later events to avoid rebinding everything which clears your values that you think you have.


                                    AutoGenerateColumns vs. Bound Columns


                                    Formatting for datagrid, BackColor, Font, CellPadding, CellSpacing, Wdth, Horizontal Align.

                                    Styles – HeaderStyle, FooterSytle, ItemStyle, AlternatingItemStyle

                                    It is possible to specify these bound columns programmatically, but it’s ugly and ton’s of code.                               

                                    Formatting for bound columns, HeaderText, FooterText, HeaderStyle/FooterStyle/ItemStyle, DataFormatString



                                    Slightly faster than DataGrid, but requires hand building of columns.



More Data


                                    Disconnected like Recordset, but can hold multiple Tables.


                                    Used to populate DataSet

                        Stored Procedure

                                    Command.CommandType = CommandType.StoredProcedure;

                                    Command.ComandText = “spTblTest”;


                                    Use to properly input Text field data into databases.

                                    SqlParameter spParam = new SqlParameter("@sName", SqlDbType.VarChar);

                                    spParam.Value = "blank1";




Using System.ServiceProcess


                        Create webservice .asmx page using prewritten code

                        Create call to it by adding web reference and

localhost.Service1 webServ = new localhost.Service1();

webServ.Url = "http://localhost/Net101Service/Service1.asmx";

                        You should be able to click on the url and see the available services.


Event Handling

            Server Side

                        DataGrid – Auto

                        Most Common double click button/control and event function automatically build, simply add event code

                        Must utilize  !Postback… in PageLoad to avoid binding rebinding on events and losing your event args.


AutoPostback Controls               Non-Auto Postback Controls

                                    Button                                                   Checkbox (list)

                                    DataGrid                                               Listbox

                                    Image                                                   RadioButton(list)

                                    Link                                                      DropDownList

                                    DataList                                                TextBox


            Client Side

                        Javascript just like asp

                        To add javascript event to a server side control add the following to code behind

txtItemDes.Attributes.Add( "OnKeyUp","checklen()");



A few Other C# objects worth remembering




                        ListItem / ListItemCollection



Practice Exercise.

    1. Create 3 strings –Math, Physics, English
    2. Use StringBuilder to create another sbClass – History
    3. Combine into a single string strAll;
    4. Create string array strArrClasses and split strAll into it.
    5. Create RadioButtonList rblClasses and bind alClasses to it.
    6. Add button btnGo and grab selected radio rblClasses.SelectedItem.ToString(); (watch postback)
    7. Insert new row into Database with
    8. Create a DataGrid dgClasses
    9. Get Datareader from table tblTest where  tblTestName is in our previous arrayList and bind to dgClasses
    10. Format Header (fix names in SQL) and make every other row grey and the header row black with white lettering.

    11. Extra for fast kids, add a dropdownlist above radio buttons called ddlDate
    12. Create a string array with max of 3 ;s
    13. Assign index 0 today’s date (hint: DateTime object) – index 1 Tomorrow’s date, index 2 Yesterday’s date.
    14. Bind array to ddl and when Go is clicked add this item as second Column.