XML

Here is an XML file named "countries.xml":

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

<countries>

<country>
  <text>Norway</text>
  <value>N</value>
</country>

<country>
  <text>Sweden</text>
  <value>S</value>
</country>

<country>
  <text>France</text>
  <value>F</value>
</country>

<country>
  <text>Italy</text>
  <value>I</value>
</country>

</countries>

<%@ Import Namespace="System.Data" %>

Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded:
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New DataSet
  mycountries.ReadXml(MapPath("countries.xml"))
end if
end sub
To bind the DataSet to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page:
<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>

</body>
</html>
Then add the script that builds the XML DataSet:
<%@ Import Namespace="System.Data" %>

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New DataSet
  mycountries.ReadXml(MapPath("countries.xml"))
  rb.DataSource=mycountries
  rb.DataValueField="value"
  rb.DataTextField="text"
  rb.DataBind()
end if
end sub
</script>

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
</form>

</body>
</html>
Then we add a sub routine to be executed when the user clicks on an item in the RadioButtonList control. When a radio button is clicked, a text will appear in a label:

Example

<%@ Import Namespace="System.Data" %>

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New DataSet
  mycountries.ReadXml(MapPath("countries.xml"))
  rb.DataSource=mycountries
  rb.DataValueField="value"
  rb.DataTextField="text"
  rb.DataBind()
end if
end sub

sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end sub
</script>

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
<p><asp:label id="lbl1" runat="server" /></p>
</form>

</body>
</html>

Event handling

Event Handling in C#



No GUI application is complete without enabling actions. Even though arranging components is a significant issue, applying actions is also equally important. These actions are what instructs the program to act when something happens.  For example, Mouse clicks, Keyboard presses, etc. Before beginning our discussion let's review how different API’s handle events.

Microsoft Foundation Classes (MFC): These classes are based upon Microsoft's Win32 API. Normally development work is done through Visual C++.  

Java API: Here, the majority of work is done by employing AWT and Swing packages. Actions are enabled by applying Interfaces. The main difficulty is that you should learn and remember all methods in the corresponding interfaces.  Otherwise, you receive compile time errors.

As compared to the above, Event handling in C# is much more simplified. It's possible to handle various Mouse and Key related events quickly and in a more efficient manner. Learning will be easier, if you understand the basic principles behind handling events, which are elaborated below 

  1. Invoke the related event by supplying a custom method or event handler using the += operator as shown here:  


b1.Click += new EventHandler(OnClick);


  1. Apply the event handler as described below. It must be in conformance with a delegate of the class System.EventHandler:

          
public delegate void EventHandler(object sender, Event args)


The first argument indicates the object sending the event and the second argument contains information for the current event. You can use this argument object to handle functions associated with the related event. Listing - 1 below illustrates how to print ”Hello C#” inside a Textbox when a Button is clicked:

Listing – 1


using System;
using System.Windows.forms;
using System.Drawing;

public class Butevent:form  {

        TextBox t1 = new TextBox();
        Button b1 = new Button();

        public Butevent() {

            this.Text = "Program developed by Pradeepta M";

            t1.Location = new Point(20,30);

            b1.Text = "Click here to activate";
            b1.Location = new Point(20,55);
            b1.Size = new Size(150,20);

           
// Invoking Method or EventHandler
           b1.Click+=new EventHandler(OnClick);

           this.Controls.Add(t1);
           this.Controls.Add(b1);

           
// Invoking Method or EventHandler
           this.Resize += new EventHandler(OnResize);
    }

  
  //Applying EventHandler
    public void OnResize(object sender,EventArgs ee) {

        MessageBox.Show("oops! form Resized");

    }


     //Applying EventHandler
    public void OnClick(object sender,EventArgs e)   {

        t1.Text = "Hello C#";

    }

    public static void Main() {

        Application.Run(new Butevent());

    }
}

The above example also shows how to handle a Resize event. try resizing the forms border and observe the result.

Handling MouseEvents


You can handle various Mouse actions by using the events specified in the Control class. The following listing shows how to handle a simple MouseUp Event:

Listing – 2


using System;
using System.Windows.forms;
using System.Drawing;

public class Mousedemo:form  {

    public Mousedemo()  {

        this.MouseUp += new MouseEventHandler(OnMouseup);

    }

    public void OnMouseup(object sender,MouseEventArgs e)   {

        this.Text = "Current Position (" +e.X + " , " + e.Y +")";

    }

    public static void Main()  {

         Application.Run(new Mousedemo());

    }
}

try out the above example and observe the result.  Click, DoubleClick, MouseEnter, and  MouseLeave events can be handled in a similar way.

Using KeyBoard Events


Every modern programming language contains all necessary functions for handling KeyBoard related events. C# also provides us with three events Keypress, KeyUp and KeyDown, which you can use to handle Keyboard events. Listing – 3, below, shows the usage of the KeyUp Event. Copy the code given below, compile, and observe the output.

Listing – 3


using System;
using System.Windows.forms;
using System.Drawing;

public class Keydemo:form {

    public Keydemo() {

        this.KeyUp += new KeyEventHandler(OnKeypress);
    }

    public void OnKeypress(object sender, KeyEventArgs e)    {

        MessageBox.Show(e.KeyCode.ToString(), "Your input");

    }

    public static void Main()    {

        Application.Run(new Keydemo());
    }
}

I hope you now have significant exposure to Event Handling techniques using the C# language. You can explore more events by going through online help. 



Adding and deleting the option values of a select element of html from javascript.

<html>
<body>
<script language="javascript">
                   
                    function setQuantity()
{


var i=0;
 var myselect=document.getElementById("mySelect");
 //alert(document.getElementById("mySelect").value);
 var len=myselect.length;



for(i=myselect.length-1; i>=0; i--)
    {

  
        myselect.options[i] = null;
    
    }




if(document.getElementById("selHomepageTile").value=="Large")
{
    var newOpt1 = new Option(1, 1);
    myselect.options[0] = newOpt1;
}

if(document.getElementById("selHomepageTile").value=="Medium")
{
for(i=3;i>=1;i--)
{


var newOpt1 = new Option(i, i);
    myselect.options[i-1] = newOpt1;
   

}
myselect.selectedIndex = 0;

}
if(document.getElementById("selHomepageTile").value=="Small")
{
for(i=12;i>=1;i--)
{
    var newOpt1 = new Option(i, i);
    myselect.options[i-1] = newOpt1;
   
    }
     myselect.selectedIndex = 0;
}
   
 }
                   
                    </script>             

<select name="selHomepageTile" id="selHomepageTile" disabled="true"  onChange="setQuantity();">
                        <option value="Large">Large (1) $200</option>
                        <option value="Medium">Medium (3) $120/each</option>
                        <option value="Small">Small (12) $80/each</option>

</select>
<select name="mySelect" id="mySelect" disabled="disabled">

           <option value="1">1</option>
</select>
</body>
</html>

Finding records in one table not present in another table

Difference between NOT IN, LEFT JOIN and NOT EXISTS.
The objective is to fetch all records in one table that are not present in another table. The most common code I’ve seen at client sites includes the use of NOT IN, because this keyword is included in most programming languages and programmers tend to use this technique when writing stored procedures in the database too. The code example I have found in most cases is this simple and understandable
SELECT     a.iFROM       #a AS aWHERE      a.i NOT IN (SELECT b.j FROM #b AS b)           
OR a.i IS NULL
The basic idea is to get all records from table #a where the value in column i is either NULL or not present in column j of table #b. What basically happens behind the scene is that the NOT IN part creates a list of values and stores them in a temporary table and then matches the values from column i in table #a against this temporary table. If there is not a match, or value from table #a is NULL, the column value is valid and returned to query.
There are at least three other ways to do this, which all are much more efficient!
SELECT     a.iFROM       #a AS aWHERE      a.i NOT IN (SELECT b.j FROM #b AS b)
UNION ALL
SELECT     a.iFROM       #a AS aWHERE      a.i IS NULL

SELECT     a.iFROM       #a AS aLEFT JOIN  #b AS b ON b.j = a.iWHERE      b.j IS NULL

SELECT     a.iFROM       #a AS aWHERE      NOT EXISTS (SELECT * FROM #b AS b
 WHERE b.j = a.i)
Running these four queries simultaneously gives exactly the same result.
Original query takes 95% of the batch, second query (first alternative with UNION ALL) takes 2%, and the last two takes only 1% each!
This is the average profiler results for the four queries after 100 executions each 
CPU
Reads
Writes
Duration
Rows
Query 1
1 767
26 292
0
1 772
2 193
Query 2
6
57
0
6
2 193
Query 3
6
24
0
6
2 193
Query 4
3
24
0
3
2 193

   
As you can see, all three alternative approaches are superior to the NOT IN approach!
Next question is obviously “Which approach to use”?
  • Second query can be the best choice if there are few records because there are now 5 table scans compared to two table scans in the original query.
  • Third query is fast, but can be slow if table #b has many more records than table #a.
  • Fourth query will always perform fast because the EXISTS parts ends directly when first matching record is found. But if the second table #b is a mix of more JOINS this will not perform that fast.
It seems that LEFT JOIN and NOT EXISTS are both superior to NOT IN.
Which one of the two approaches you choose, must be decided carefully for every query needing this technique.
Also remember that if table #b were not a temporary table, SQL Server would have places a lot of locks on that table.