Windows Phone Developers

Friday, April 23, 2010

How to pass Database Field Name to SQLDataReader GetString Function

How to retrieve data from SQLDataReader using FieldNames in C# (.NET)

It is always better practice to use Field names instead of Index. You can decide which of the following is clear



string sPlayerName =  rdr[1].ToString();
             sPlayerName = rdr["PlayerFirstName"].ToString();


The best overloaded method match for 'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Parametrized Query in C# / .NET

How to pass parameters in SQL Queries in .NET (C#)

Parametrized queries are more secure (avoids SQL Injection etc) and easy to handle. The following example shows an simple example.


The above table has details of Players like name, contact details etc.

Let us try to get the details of players whose first name is 'Sachin'. First make a connection to database :

string sConString = GetConnectionString("TeamDBConnectionString");
            SqlConnection Con = new SqlConnection(sConString);
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Con;

            Con.Open();


Then set the CommandText property of SQLCommand and pass the parameters

String sSQLCmdText = "Select * from PlayerDetails where PlayerFirstName  = @FirstName";
            Cmd.CommandText = sSQLCmdText;
            Cmd.Parameters.AddWithValue("@FirstName", "Sachin");

Once this done, declare a SQLDataReader and get the rows into it


SqlDataReader rdr = Cmd.ExecuteReader();

            while (rdr.Read() == true)
            {
              string sPlayerName =  rdr.GetString(1);
            }
            
            Con.Close();


You can also pass the FieldName as parameter to query Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

SQLDataReader - Invalid attempt to read when no data is present

The error occurs when there no data is returned / the data has not been read.

The first case can be checked using HasRows flag

If the data is not read it can be done as follows:



SqlDataReader rdr = Cmd.ExecuteReader();

            while (rdr.Read() == true)
            {
              string sName =  rdr.GetString(1);
            }
      


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Wednesday, April 21, 2010

How to Add Generic List Items to ListBox in C# / VB.NET

We have already seen How to Add an ArrayList to ListBox. The following code shows how to add a C# Generic List to ListBox


        public void Load_LB_GenericList()
        {
            List Team = new List();
            ClassTeam CT = new ClassTeam(ClassTeam.playerType.Contract, "Sachin", 23, "33420242");
            Team.Add(CT);
            CT = new ClassTeam(ClassTeam.playerType.Contract, "Sourav", 23, "33420242");
            Team.Add(CT);
            CT = new ClassTeam(ClassTeam.playerType.Contract, "Dravid", 23, "33420242");

            Team.Add(CT);
            listBox1.DataSource = Team;
            listBox1.DisplayMember = "Name";
            listBox1.ValueMember = "Phone";

        }
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to assign an ArrayList to ListBox in .NET (C#)

How to add ArrayList items to ListBox (VB.NET/C#) / How to Add Objects to ListBox using C# (.NET)

Let us consider an userform with a listbox. We now need to assign the Arraylist to the Listbox.

We go back to our Teamexample. We have a class called ClassTeam with following properties


     class ClassTeam
    {
        #region declarations
        public enum playerType { ClassA, ClassB, ClassC, Contract }
        private playerType _PlayerType;
        string _Name;
        int _Age;
        string _Phone;


        #endregion

        #region properties
        public playerType PlayerType
        {
            //accessor
            get { return _PlayerType; }

            //mutator
            set
            {
                _PlayerType = value;
            }

        }

        public string Name
        {
            get { return _Name; }

            set
            {
                _Name = value;
            }
        }

        public string Phone
        {
            get { return _Phone; }

            set
            {
                _Phone = value;
            }
        }

        public int Age
        {
            get { return _Age; }

            set
            {
                _Age = value;
            }
        }
        #endregion

        #region public methods
        public string SetPlayer()
        {

            return null;
        }
        #endregion

        #region ClassTeam Construct
        public ClassTeam(playerType PT, string sName, int iAge, string sPhone )
        {
            PlayerType = PT;
            _Name= sName;
            _Age = iAge;
            _Phone = sPhone;
        }

    #endregion

    }




Now we create objects of the above class and add it to an Arraylist


            ArrayList Team = new ArrayList();
            ClassTeam CT = new ClassTeam(ClassTeam.playerType.Contract, "Sachin", 23, "33420242");
            Team.Add(CT);
            CT = new ClassTeam(ClassTeam.playerType.Contract, "Sourav", 23, "33420242");
            Team.Add(CT);
            CT = new ClassTeam(ClassTeam.playerType.Contract, "Dravid", 23, "33420242");

            Team.Add(CT);
 

The arraylist 'Team' will nowcontain three ClassTeam objects.

Assign the ArrayList as datasource to the listbox and set the displaymember and valuemember



            listBox1.DataSource = Team;
            listBox1.DisplayMember = "Name";
            listBox1.ValueMember = "Phone";


Some methods of ListBox will not be available when use DataSource. Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Items collection cannot be modified when the DataSource property is set.

Sorted property of ListBox Throws error


The error occurs when you are trying to do something that is not allowed. For example, Sorting is not allowed in Listbox when it is linked to DataSource. If you need to sort, then sort the DataSet before linking it to Listbox Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Monday, April 19, 2010

How to iterate MultiSelect ListBox using C# (.NET)

C# - Get Selected Values from MultiSelect ListBox

Here is a way of retrieving the selected values of Multiselect listbox

for (int i1 = 0; i1 < listBox1.SelectedItems.Count; i1++)
            {
                DataRowView D1 = listBox1.SelectedItems[i1] as DataRowView;

                MessageBox.Show(D1[1].ToString());
            }
The above code uses SelectedItems collection to retrieve information Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Saturday, April 17, 2010

How to Create MultiSelect Listbox in .NET (C#)

Enable MultiSelect in ListBox (C#/.NET)

Modifying the SelectionMode property of the listbox allows Multiple Items to be selected
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to get the selected value of listbox using C# code

The following code retrieves the value of listbox and the accompanying text

private void listBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            MessageBox.Show(listBox1.Text);
            MessageBox.Show(listBox1.SelectedValue.ToString());
        }



The above method retrieves the displaytext (DisplayMember) and the selected value (DisplayValue) from the selected item of listbox Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to Bind DataSet to ListBox using C#

How to add items from database to Listbox control using C#

The following code binds the PlayerDetails table with the listbox

string sConString = GetConnectionString("TeamDBConnectionString");
            SqlConnection Con = new SqlConnection(sConString);
            Con.Open();

            //Command Text
            String sSQLCmdText = "Select * from PlayerDetails";
            
            //Create a new SQL Data Adapter
            SqlDataAdapter DA = new SqlDataAdapter(sSQLCmdText , Con);
            
            DataSet DS = new DataSet("PlayerDS"); //DataSet

            DS.Clear();
            DA.Fill(DS, "Player");

            listBox1.DisplayMember = "PlayerName";
            listBox1.ValueMember = "PlayerID";
            listBox1.DataSource = DS.Tables["Player"];

            Con.Close();

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Friday, April 16, 2010

How to retrieve specific connection string from App.Config file using C# (.NET)

Get specific connection string from App.Config file using C# (.NET)

The connection string can be retrieved from the App.Config file using ConnectionStrings method of ConfigurationManager. You need to add the following directive in the code:


using System.Configuration;

The ConnectionStrings method without any arguments will return a collection of Connection strings in the App.Config file. If you want to retrieve specific ones you can either pass an index or string to it

private static string retsettings(String sConnName)
        {
            try
            {
                ConnectionStringSettings sConnection = ConfigurationManager.ConnectionStrings[sConnName];
                return sConnection.ConnectionString;
            }
            catch (Exception ex1)
            {
                return null;
            }
            finally
            { }

            
        }
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Wednesday, April 14, 2010

How to validate password using C# (.NET)

How to check password using C# Regular Expressions / How to enforce strong password using C# .NET

One of the common methods to check and validate password is through regular expressions. The criteria for strong password is :

1. Password should be minimum eight characters in length
2. Password should contain atleast a digit and an alphabet
3. Password should contain a non-alphanumeric character

The code uses Regular Expressions and hence the following directive is used:

using System.Text.RegularExpressions; 

The code below checks for the length:

if (sPassword.Length < 8 )
                {
                    throw new Exception("Password should contain mimimum 8 chars");   
                }

the code below checks for presence of atleast one number
sPattern = "\\d";
                oReg = new Regex(sPattern, RegexOptions.IgnoreCase);
                if (oReg.IsMatch(sPassword) == false)
                {
                    throw new Exception("Password should contain mimimum one numeric character");
                }

the code below checks for presence of atleast one alphabet
sPattern = "\\w";
                oReg = new Regex(sPattern, RegexOptions.IgnoreCase);
                if (oReg.IsMatch(sPassword) == false)
                {
                    throw new Exception("Password should contain mimimum one alphabet character");
                }

the code below checks for presence of atleast one non-alphanumeric character
string sPattern;
                sPattern = "[^a-zA-Z0-9\n\r\t ]";
                Regex oReg = new Regex(sPattern, RegexOptions.IgnoreCase);
                if (oReg.IsMatch(sPassword) == false)
                {
                    throw new Exception("Password should contain mimimum one non-alphanumeric character");   
                }
Exceptions are raised and handled if the criteria is not matching Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Monday, April 12, 2010

How to Raise Exceptions in C# / .NET

Raise Error in C# (.NET) / Throw Error/Exception in C# (.NET)

The following code generates an exception if the supplied text (password) is less than eight characters.

try {
                if (sPassword.Length < 8 )
                {
                    throw new Exception("Password should contain mimimum 8 chars");   
                }
            }
                            catch(Exception ex1)
            {
                sMessage= ex1.Message.ToString();
                return false;
                            }
     

This way of raising user-defined exception helps in efficient way of handling exceptions Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Sunday, April 11, 2010

How to Add an Array to List using C# /.NET

Add Range to List using C# / .NET

Let us take our own IPL example. The current IPL has eight teams that are part of the list

            List lstIPLTeams = new List();

            lstIPLTeams.Add("Mumbai Indians");
            lstIPLTeams.Add("Chennai SuperKings");
            lstIPLTeams.Add("Kolkatta KnightRiders");
            lstIPLTeams.Add("Deccan Chargers");
            lstIPLTeams.Add("Rajastan Royals");
            lstIPLTeams.Add("Delhi DareDevils");
            lstIPLTeams.Add("KingsXI Punjab");
            lstIPLTeams.Add("RC Bangalore");




From next year two new teams- Pune and Kochi - will be part of IPL

Hence we are adding those two teams to an Array and adding the array using AddRange method

            string[] NewIPLTeams = { "Pune", "Kochi" };
            lstIPLTeams.AddRange(NewIPLTeams);

            Console.WriteLine("\nList After Add Range");
            Console.WriteLine("=======================");
            foreach (string IPL in lstIPLTeams)
            {
                Console.WriteLine(IPL.ToString());
            }


This will add Pune and Kochi to end of the list Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to Add and Sort Items in a list using C#

Adding and Sorting List Items using .NET (C#)

The following example creates a Generic list of IPL teams and sorts them


The following code does it:

List lstIPLTeams = new List();

            lstIPLTeams.Add("Mumbai Indians");
            lstIPLTeams.Add("Chennai SuperKings");
            lstIPLTeams.Add("Kolkatta KnightRiders");
            lstIPLTeams.Add("Deccan Chargers");
            lstIPLTeams.Add("Rajastan Royals");
            lstIPLTeams.Add("Delhi DareDevils");
            lstIPLTeams.Add("KingsXI Punjab");
            lstIPLTeams.Add("RC Bangalore");


            Console.WriteLine("List Before Sorting");
            Console.WriteLine("=======================");
            foreach (string IPL in lstIPLTeams)
            {
                Console.WriteLine(IPL.ToString());
            }

            //Sort the Items
            lstIPLTeams.Sort();

            Console.WriteLine("\nList After Sorting");
            Console.WriteLine("=======================");
            foreach (string IPL in lstIPLTeams)
            {
                Console.WriteLine(IPL.ToString());
            }

Here is the output



Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Friday, April 9, 2010

Private Constructors in C# / VB.NET

Use of Private Constructors in C# (.NET)

Here is an example of a Private Constructor

public class WicketCounter
    {
        //Private Constructor
        private WicketCounter() { }

        // No of Wickets
        public static int Wickets;
        // Public Method to Return the No of Wickets
        public static int WicketCount()
        {
            return ++Wickets;
        }

     
    }


The Class has a private constructor, a public static method and a static variable. The Method increments the Wicketcount (and hence the class itself is called wicketcounter) and the value is returned through Wickets var

WicketCounter.WicketCount();
            
            MessageBox.Show(WicketCounter.Wickets.ToString());


The declaration of private constructor prevents the creation of default constructor. Hence the class cannot be instantiated and doesn;t contain any instance fields or methods Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to Download File from Website using C# (.NET)

 How to Download File from Internet using C# (.NET)


private bool download_file_from_Net()

        {
            try
            {
                WebClient WC = new WebClient();
                String sWebLocation = "http://logic.stanford.edu/talks/Web2.0/microsoft-logo.jpg";
                String sLocalPath = "C:\\Temp\\New folder (2)\\microsoft-logo.jpg";
                WC.DownloadFile(sWebLocation, sLocalPath);
                return true;
            }

           catch (Exception ex1)
            {
                return false;
            }
        }
  



Following errors might occur if you do not use the Destination File Name

For example


                String sLocalPath = "C:\\Temp\\New folder (2)";


throws the following error
 InnerException = {"Access to the path 'C:\\Temp\\New folder (2)' is denied."}

and


                String sLocalPath = "C:\\Temp\\New folder (2)\\";



 throws the following one


System.Net.WebException was caught
  Message=An exception occurred during a WebClient request.
  InnerException: System.IO.DirectoryNotFoundException

       Message=Could not find a part of the path 'C:\Temp\New folder (2)\'.

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Monday, April 5, 2010

How to Bind a Lisbox to Database in C# (.NET)

Bind Listbox to Dataset using Visual Studio

Following steps would help you in connected a database/dataset to the list box

Step1: Add a List Box control to the form and select the DataSource from quick edit

Step 2: Select appropriate data source type (We are going to connect to an SQL Server DB)


Step 3: Select Appropriate Database Model


Step 4: Add a connection to database and select appropriate DB

Step 5: Select appropriate field you want to show in listbox


A dataset will be created and will be used for it. You can write necessary code in listbox selectionchange events depending upon the business logic Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Switching Application Types using Visual Studio

Converting Application Types using Visual Studio

Visual Studio helps you to change Console Application to Windows Forms Application as shown below. This will help if you want to have your output on Console; then you can change the type from WinForms to console and view the o/p.

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Saturday, April 3, 2010

Debug.Print and Debug.Assert in C#

VB Programmers would have used Debug.Print and Debug.Assert at will while debugging the code. These two statements come handy for efficient debugging of the code.

This can be done in C# using System.Diagnostics


using System.Diagnostics;


missing the above directive will cause 'The name 'Debug' does not exist in the current context" error



int i1 = 0;
while (i1 < 10)
{
Debug.Assert(i1 != 3);
++i1;
}


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005