Sponsored Ad

Friday, April 30, 2010

How to Create a First Console Application in VS 2005 – C#

Sometimes fresher's face much problem in created their first application. We are here to develop a first console application with screen shots using C# of VS 2005.

Lets go though this process step by step:

Step 1: Open VS 2005 and click on File –> New –> Projects

VS 2005

 

Step 2: Select project type as Visual c# and Templates as console Application

Select C# and console application

 

step 3: New Project is  created.

Project is Created

 

Step 4: Lets write few lines of code.

I have written two lines in program.CS file inside the main method. Console.Write is used to print the given line on the screen. Console.ReadLine is used to read line from screen. we are using Console.ReadLine here to stop the output screen until press any key. if you will remove this line the output screen will disappear.

     Console.Write("This is my First Console Application");

     Console.ReadLine();

You can add a extra file in this application also by

Right Click on MyFirstConsoleApp –> Add –> New item –> Select a Type of File and give the name of file and click on ok button.

 

Write line of Code

Step 5: Now lets run the application by pressing F5 button or click the below button.

Run The Application

 

Step 6: Output of above program is here.

Output

 

Source code:

using System;
using System.Collections.Generic;
using System.Text;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("This is my First Console Application");
            Console.ReadLine();
        }
    }
}

 

 

Congrats you have created first program and run it, Please let us know in case of any problems.

Tuesday, April 27, 2010

Operator Overloading With Multiple Parameters in C#

 

This program Demonstrate you Operator Overloading using multiple parameters.

Operator overloading is a concept to add extra functionality to existing operator. Like plus (+) have capability to add two numbers but it can not add two objects. So in this example we have done operator overloading with + operator using multiple parameters.

This is simple example, but in case any one need any help, Please comment.

Operator Overloading With Multiple Parameters in C#

 

using System;
using System.Collections.Generic;
using System.Text;

namespace Console_App
{
    public class BaseClass
    {
        public static void Main()
        {
            Operator_Overloading a1 = new Operator_Overloading(10);
            Operator_Overloading a2 = new Operator_Overloading(15);
            Operator_Overloading a3 = new Operator_Overloading(25);
            Operator_Overloading a4;
            a4 = a1 + a2 + a3;
            Console.WriteLine(a4.i);
            Console.ReadLine();
        }
    }
    public class Operator_Overloading
    {
        public int i;
        public Operator_Overloading(int j)
        {
            i = j;
        }
        public static Operator_Overloading operator +(Operator_Overloading x1, Operator_Overloading x2)
        {
            System.Console.WriteLine("Operator (+) Overloading Result : " + x1.i + " " + x2.i);
            Operator_Overloading x3 = new Operator_Overloading(x1.i + x2.i);
            return x3;
        }
    }
}

Monday, April 26, 2010

How to Add Image Icons in HTML List | Image Bullets for List

 

This sample code will help you to add image icon in place of bullets of HTML List. just set the list-style-image property from CSS and assign the image URL and all is done you can check the list bullets showing image icon.

image

 

<html>
<head>
<style type="text/css">
ul {list-style-image: url('ArrowMap.gif'); verticle}
</style>
</head>
<body>
<ul>
<li>CsharpTalk.com</li>
<li>IndiHub.com</li>
<li>SoftwareTestingNet.com</li>
</ul>
</body>
</html>

Thursday, April 22, 2010

How to Take Input From User in JavaScript

Taking a input from user is very important feature in any language. It makes a bridge between user and computer. So JavaScript also have this feature and can be implemented by prompt() method.

 

var identity= prompt("Please enter your identity","")

 

This Sample JavaScript code will help you to receive input from user and display it in webpage. prompt function is used here to take a value from user and store it in a variable. Again this program displays the value of variable.

 

<html>
<head>
</head>
<body>
<script type="text/javascript">
var identity= prompt("Please enter your identity","")
if (identity!= null && identity!= "")
{ document.write("Hey  " + identity) }
</script>
</body>
</html>

Wednesday, April 21, 2010

Substring Operations Using JavaScript

 

Substring operations are very common and useful for string manipulations. JavaScript also supports this operation by two methods:

substring()

substr()

Lets discuss both of them.

substr(5,8) function start counting string from 0 and find the 5th count of string character and calculate till length of 8 characters.

0-T 1-h 2-i 3-s 4-  5-S 6-u 7-b 8-s 9-t 10-r 11-i 12-n 13-g manipulation is brought you by CsharpTalk.com

as given in above example the substring result start with 5-S and end at 5+8 length=12-n.

 

Now lets discuss substring(5,8)

substring(5,8) function starts with 5th character and end before 8th character

0-T 1-h 2-i 3-s 4-  5-S 6-u 7-b 8-s 9-t 10-r 11-i 12-n 13-g manipulation is brought you by CsharpTalk.com

So as in above example the result of this operation will be 5-S to 7th character.

 

<html>
<body>
<script type="text/javascript">
var str= "This Substring manipulation is brought you by CsharpTalk.com"
document.write(str.substr(5,8))
document.write("<br /><br />")
document.write(str.substring(5,8))
</script>
<p>
Example of substr() and substring() of JavaScript.
</p>
</body>
</html>

 

Output of given program:

Output of str.substr(5,8)

Substrin

Output of str.substring(5,8)

Sub

How to Manage Adsense Ads in ASP.NET project

Sometime it is hard to manage adsense ads with asp.net project. The primary problem is that suppose sometimes we want to change ad or off the ad, asp.net project need a recompilation. Here is solution to this problem.

 

How to Manage Adsense Ads in ASP.NET project

 

Like given in above figure, I have added a Ad Script folder and inside this folder I have added different control files for different ads. Suppose I have add a text ad of 250x250 , for this ad we can give file name as Text250x250.ascx. put your adsense code inside these ascx file. One ad one file. Note that for ascx file content change we do not need a recompilation of whole source code. Just change the contents of this file and everything is done.

Here is code to add ascx file into aspx page:

<%@ Register Src="Ad Script/Text250x250.ascx" TagName="Text250x250" TagPrefix="uc4" %>

Now you need to add this control file to you original page and deploy the code.

:)

Tuesday, April 20, 2010

Save Images in SQL Server Database using C#

There are number of options to store images, one popular option is to store images in database. But generally we do not prefer to store images in database because of , its take longer time to store in database that storing in directory.

Here is simple sample code to store images in database. First programmer need to create a table with column type image in database and then insert image in table using c# code.

Please let us know if you face any problem in this code.

Step1: Create an Table in Sql Server Database.

CREATE TABLE [dbo].[Demo](

[DemoImageName] [varchar] (50),

[DemoImage] [image] NULL

)

Step 2: Write a code to save select image into Database table.

 

if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
        {

byte[] imageSize = newbyte[FileUpload1.PostedFile.ContentLength];

HttpPostedFile uploadedImage = FileUpload1.PostedFile;

            uploadedImage.InputStream.Read(imageSize, 0, (

int)FileUpload1.PostedFile.ContentLength);

// Create SQL Connection

            SqlConnection sqlConn = newSqlConnection("Data Source=Server Name;Initial Catalog=DatabaseName;Integrated Security=True");

// Create SQL Command

            SqlCommand cmd = new SqlCommand();

            cmd.CommandText =

"INSERT INTO DemoImages(DemoImageName,Image)" +

" VALUES (@DemoImageName,@DemoImage)";

            cmd.CommandType =

CommandType.Text;

            cmd.Connection = sqlConn;

            SqlParameter ImageName = newSqlParameter("@ImageName", SqlDbType.VarChar, 50);

            ImageName.Value = FileUpload1.FileName;

            cmd.Parameters.Add(ImageName);

            SqlParameter UploadedImage = newSqlParameter("@Image", SqlDbType.Image, imageSize.Length);

            UploadedImage.Value = imageSize;

            cmd.Parameters.Add(UploadedImage);

            sqlConn.Open();

int result = cmd.ExecuteNonQuery();

            sqlConn.Close();

if (result > 0) lblMessage.Text = "Demo File Uploaded and Saved";

        }

Saturday, April 17, 2010

How to Reverse String Using C#

This simple post will help you to reverse the C# string. This method loop through all the characters of string and construct the new string in reverse order.

To  use this function pass the given string in this method and it will return the reversed string as output.

 

private string ReverseStr(string szLine)
    {
        int index;
        string strTemp;
        string strA;

        strTemp = "";
        try
        {
            for (index = szLine.Length; index >= 1; index--)
            {
                strA = szLine.Substring(index - 1, 1);
                strTemp = strTemp + strA;
            }
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {
        }
        return strTemp;
    }

 

 

Another way to do string reversal is:

 

private  string ReverseString(string str)
  {
      char[] StringArrya = str.ToCharArray();
      Array.Reverse(StringArrya);
      return new string(StringArrya);
  }

Thursday, April 15, 2010

How to Add Link in Dropdown(Select) using JavaScript

Sometimes we need to to add links of another page or site with dropdown values. This example will help you to code this functionality using JavaScript code.

Call a method onchange of dropdown and inside that method write a line

document.forms[0].wheretogo.value

where wheretogo is dropdown name.  and it will open a corresponding page when user will select a option.

 

<html>
<head>
<script type="text/javascript">
function go()
{
location=document.forms[0].wheretogo.value
}
</script>
</head>
<body>
<form>
<select id="wheretogo" onchange="go()">
<option>-Select Destination location
<option value="
http://IndiHub.com">India New
<option value="
http://BharatClick">Free Indian Classifieds
<option value="
http://SharePointBank.com">Microsoft SharePoint Resources
</select>
</form>
</body>
</html>

Wednesday, April 14, 2010

How to Fill HTML Dropdown(SELECT) From C# | Call C# Method From HTML Code

This sample code will help you to call an C# method from HTML code using server tags. there is two ways to fill HTML select dropdown.

1. Hardcoded values

2. Iterating through dataset

 

How to Fill HTML Dropdown(SELECT) From C# | Call C# Method From HTML Code

 

ASP.NET code:

<html  >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    </script>
</head>
<body>
    <form id="form1" runat="server">
    Method 1:
    <select id="tmplPriority" name="tmplPriority1" >
                        <%=LoadList1()%>
                    </select>
                    <br />
                    <br />
       Method 2:
    <select id="Select1" name="tmplPriority2" >
                        <%=LoadList2()%>
                    </select>
    </form>
</body>
</html>

 

C# code:

use namespace

using System.Data;

 

protected void Page_Load(object sender, EventArgs e)
    {
        LoadList1();
        LoadList2();
    }
    public string LoadList1()
    {

        string sOption = "";
        sOption = sOption + "<OPTION VALUE=" + "Option 1" + ">" + "Option 1" + "<//OPTION>";
        sOption = sOption + "<OPTION VALUE=" + "Option 2" + ">" + "Option 2" + "<//OPTION>";
        sOption = sOption + "<OPTION VALUE=" + "Option 3" + ">" + "Option 3" + "<//OPTION>";
        sOption = sOption + "<OPTION VALUE=" + "Option 4" + ">" + "Option 4" + "<//OPTION>";
        return sOption;
    }

    public string LoadList2()
    {
        //Fill using dataset
        string sOption = "";
        DataSet oDs = Get_Data();
        if (oDs != null && oDs.Tables.Count > 0)
        {
            for (int irow = 0; irow < oDs.Tables[0].Rows.Count; irow++)
                sOption = sOption + "<OPTION VALUE=" + oDs.Tables[0].Rows[irow][0] + ">" + oDs.Tables[0].Rows[irow][1] + "<//OPTION>";

            return sOption;
        }
        else
            return "<OPTION></OPTION>";
    }

    private DataSet Get_Data()
    {
        DataSet ds = new DataSet();
          DataTable dt = new DataTable();
          try
          {
              dt.Columns.Add(new DataColumn("value",Type.GetType("System.String")));               
              dt.Columns.Add(new DataColumn("text",Type.GetType("System.String")));
              dt.AcceptChanges();
              DataRow dr = dt.NewRow();
              //First Row
              dr["value"] = "Option 1";
              dr["text"] = "Option 1";
              dt.Rows.Add(dr);
              dt.AcceptChanges();
              //Second Row
              dr=null;
              dr=dt.NewRow();
              //First Row
              dr["value"] = "Option 2";
              dr["text"] = "Option 2";
              dt.Rows.Add(dr);
              dt.AcceptChanges();
              //Third Row
              dr=null;
              dr=dt.NewRow();
              //First Row
              dr["value"] = "Option 3";
              dr["text"] = "Option 3";
              dt.Rows.Add(dr);
              dt.AcceptChanges();

              ds.Tables.Add(dt);

              return ds;
          }
          catch(Exception ex)
          {
              throw;
          }
          finally
          {
              if(dt != null)
              {
                  dt =null;
              }
          }
      }

Tuesday, April 13, 2010

GridView - RowCreated Event Check the Value and Hide Row and Cell Values

This sample code will help you to perform hide and other operation at row level inside the Gridview RowCreated Event.

ASP.NET Code:

<asp:GridView ID="GridViewAllNews" runat="server" DataSourceID="ObjectDataSourceAllNews" 

OnRowCreated="GridViewAllNews_RowCreated"                                                                              DataKeyNames="Id" >
                                                                          

First check if EventArgs is null just return. always check for RowType is DataRow and DataItem is not null.

Find the control using

Image newsImage = (Image)e.Row.FindControl("Image2");

and set the visibility of cell.

C# code:

protected void GridViewAllNews_RowCreated(object source, GridViewRowEventArgs e)
  {
      if (e.Row == null) return;

      // display if 'Visible' = true
      if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null)
      {
          bool visible = (bool)DataBinder.Eval(e.Row.DataItem, "Visible");
          e.Row.Visible = visible;
      }

      // display image if a url is specified
      string imageUrl = (string)DataBinder.Eval(e.Row.DataItem, "ImageUrl");
      if (String.Empty.Equals(imageUrl))
      {
          Image newsImage = (Image)e.Row.FindControl("Image2");
          if (newsImage != null)
              newsImage.Visible = false;
      }

   }

Check for Decimal Number in C# | IsDecimal()

This small utility will help you to find that given string or number is decimal or not.

Just pass the given string in IsDecimal function and it will return true if given string is Decimal otherwise will return false.

 

public static bool IsDecimal(string n)
     {
         try
         {
             Decimal.Parse(n.Trim());
             return true;
         }
         catch { return false; }
     }

Monday, April 12, 2010

Get Full Useful Exception Message from Exception object

This post will help to collect full useful exception message from exception object.

This utility constructs the exception message from

1. Exception Source

2. Exception Target

3. Exception Message

and returns a concatenated string for logging. This is very useful while debugging the application.

 

 

       /// <summary>
        /// Get the Whole useful Exception Message from Exception object.
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static string GetExceptionMessage(Exception ex)
        {
            try
            {
                if (ex != null) // taking care of exception object sent in is if NULL
                {
                    string expMessage = string.Concat("Exception Source: ", ex.Source, "\n", "Exception Target : ", ex.TargetSite, "\n", "Exception Message: ", ex.Message);
                    return expMessage;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception e)
            {
                throw;
            }

        }

How to Access Selected CheckBox Rows in GridView Using C#

This sample code will help you to loop through the ASP.NET GridView Control and Collect the id columns for selected checkboxes.

 

How to access checkbox from GridView

CheckBox box = r.FindControl("AdCheckBox") as CheckBox;

 

        string strIDs = "";
        foreach (GridViewRow r in AdsGrid.Rows)
        {
            CheckBox box = r.FindControl("AdCheckBox") as CheckBox;
            if (box != null && box.Checked)
            {
                DataKey idKey = AdsGrid.DataKeys[r.RowIndex];
                strIDs += idKey.Value.ToString();
            }
        }

 

ASP.NET Code:

 

<asp:GridView ID="AdsGrid" runat="server" DataSourceID="AdsDataSource" AutoGenerateColumns="False" DataKeyNames="Id" >
<Columns>

<asp:TemplateField ItemStyle-CssClass="col_checkbox" HeaderStyle-CssClass="col_checkbox">
<HeaderTemplate>
<input type="checkbox" id="ChkSelectAll"  />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="AdCheckBox" runat="server"  />
</ItemTemplate>
</asp:TemplateField>

<asp:HyperLinkField HeaderText="Actions" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="~/EditAd.aspx?id={0}"
                                            Text="Edit" HeaderStyle-CssClass="col_general" ItemStyle-CssClass="col_general">

</Columns>

</asp:GridView>

How to Add Checkbox Column in GridView and JavaScript Function to Select All Checkboxes

This Sample code will guide you to Add Checkbox template column in GridView control. add a ASP.NET Check Box control in itemtemplate and a checkbox in header also to implement Select all Functionality.

Check Java Script method implements the select all functionality for checkbox columns.It works whenever user clicks on header check box it select all/Deselect all the grid checkbox.

How to Add Checkbox Column in GridView and JavaScript Function to Select All Checkboxes

 

JavaScript Code;

<script type="text/javascript" language="javascript">
function Check(parentChk)

{
var elements = document.getElementsByTagName("input");
for(i=0; i<elements.length;i++)
{
if(parentChk.checked == true)
{
if( IsCheckBox(elements[i]))
{
elements[i].checked = true;
}
}
else
{
elements[i].checked = false;
}
}

}

function IsCheckBox(chk)
{
if(chk.type == 'checkbox') return true;
else return false;
}
</script>

 

ASP.NET Code:

<asp:GridView ID="AdsGrid" runat="server" DataSourceID="AdsDataSource" AutoGenerateColumns="False" DataKeyNames="Id" >
<Columns>

<asp:TemplateField ItemStyle-CssClass="col_checkbox" HeaderStyle-CssClass="col_checkbox">
<HeaderTemplate>
<input type="checkbox" id="ChkSelectAll" onclick="Check(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="AdCheckBox" runat="server" CssClass="AdminAdsGrid" />
</ItemTemplate>
</asp:TemplateField>

</Columns>

</asp:GridView>

Sunday, April 11, 2010

Step By Step Guide to Install Microsoft Visual Studio 2010 Ultimate Beta 2

 

This post will help you to install Visual studio Ultimate Beta 2 on your PC. 

Step 1: Go to the Microsoft site to download the latest version of Visual studio (Microsoft Visual Studio 2010 Ultimate Beta 2).

http://www.microsoft.com/downloads/details.aspx?FamilyID=dc333ac8-596d-41e3-ba6c-84264e761b81&displaylang=en

 

Step 2:  Extract the ISO file using winrar or mount using daemon tool.

 

Step 3: Click on set up file to start installation. And Click on Install VS.

 

Step By Step Guide to Install Microsoft Visual Studio 2010 Ultimate Beta 2

Step By Step Guide to Install Microsoft Visual Studio 2010 Ultimate Beta 2

 

Step 4: Click on next button.

Step By Step Guide to Install Microsoft Visual Studio 2010 Ultimate Beta 2

 

Step 5: Accept the term and conditions.

Step By Step Guide to Install Microsoft Visual Studio 2010 Ultimate Beta 2

 

Step 6: Select if you want to install the full features or would like to customize installation.

Step By Step Guide to Install Microsoft Visual Studio 2010 Ultimate Beta 2

 

After installing the VS you will get a finish screen.  Congratulation you are ready to use Latest version of visual studio.

Saturday, April 10, 2010

How to Check if Number is power of Two(2)

This small utility will help you to find out if a given number is power of two or not. Just pass the given number in this utility and will return true or false.

 

private static bool IsPowerOfTwo(ulong val)
    {
        while (val > 0)
        {
            if ((val & 0x1) != 0)
            {
                // If the low bit is set, it should be the only bit set
                if (val != 0x1)
                {
                    return false;
                }
            }

            val >>= 1;
        }

        return true;
    }

Friday, April 9, 2010

How to Get File Name from Full File Path in C#

 

This utility will help you to extract the file name from a given full file path in C#. Just pass the full file name as input to this function and you will get file in result.

This method find the last index of \\ and then extract the string after that.

 

       /// <summary>
       /// Get the file part of a path.
       /// </summary>
       /// <param name="path">The path to process</param>
       /// <returns>The file part of the path</returns>
       public static string GetFileFromPath(string path)
       {
           string trimmed = path.Trim('\\');

           int index = trimmed.LastIndexOf('\\');
           if (index < 0)
           {
               return trimmed; // No directory, just a file name
           }

           return trimmed.Substring(index + 1);
       }

How to Extract Directory/Folder Name From Path in C#

This Utility will help you to get Folder Directory Name from a file full path.

Just pass the full file path as input to this utility and it will return the Folder/Directory Name as a result.

 

        /// <summary>
       /// Extracts the directory part of a path.
       /// </summary>
       /// <param name="path">The path to process</param>
       /// <returns>The directory part</returns>
       public static string GetDirectoryFromPath(string path)
       {
           string trimmed = path.TrimEnd('\\');

           int index = trimmed.LastIndexOf('\\');
           if (index < 0)
           {
               return ""; // No directory, just a file name
           }

           return trimmed.Substring(0, index);
       }

Wednesday, April 7, 2010

How to Use RequiredFieldValidator in ASP.NET | Client Side Empty Value Validation

This Simple asp.NET program will demonstrate you to use the RequiredFieldValidator.  The use of require field validation is very simple and it to validate values it does not require a server trip. So all validation is perform on Client side.

Just specify the ControlToValidate property and give the id of control which need to validated. We have given example with radio button and text box , you can use it for other controls also.

 

<html>
<head>
<script language="C#" runat=server>
void abc(Object S, EventArgs e)
{
if (Page.IsValid == true)
{
aa.Text = "Page is Valid!";
}
else
{
aa.Text = "Some of the required fields are empty";
}
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<asp:Label ID="aa" text="fill it up" runat=server />
<ASP:RadioButtonList id=bb runat=server>
<asp:ListItem>a1</asp:ListItem>
<asp:ListItem>a2</asp:ListItem>
</ASP:RadioButtonList>
<asp:RequiredFieldValidator id="r1" ControlToValidate="bb" InitialValue="" runat=server>
Radio Button Selection is missing
</asp:RequiredFieldValidator>
<br />
<br />
<br />
<ASP:TextBox id=cc runat=server />
<asp:RequiredFieldValidator id="r2" ControlToValidate="cc" Width="100%" runat=server>
Text Field Values are Missing
</asp:RequiredFieldValidator>
<ASP:Button id=B1 text="Validate" OnClick="abc" runat=server />
</form>
</body>
</html>

How to Write HTML File in C#

This sample code will guide you to write an html file into given path. You just need to pass the file full path and values to write on file.

 

public static bool WriteHtmlFile(string pHtmlFileNameWithFullPath, string pValue)
        {
            bool mSuccess = false;

            if (pValue.Trim().Length > 0)
            {

                try
                {
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(pHtmlFileNameWithFullPath, false);

                    sw.Write(pValue);

                    sw.Close();
                }
                catch (Exception)
                {
                    Exception ex = new Exception(pHtmlFileNameWithFullPath.Substring(pHtmlFileNameWithFullPath.LastIndexOf("\\")) + " not accessible !! contact administrator..");
                    throw ex;
                }

                mSuccess = true;
            }

            return mSuccess;
        }

Monday, April 5, 2010

How to Read an HTML file in C#

 

This utility help you to code the logic to read an HTML file. This code block usase the StreamReader to read the file and stores in Stringbuilder. One can use this to perform any manipulation operation on stringbuilder and write it back on HTML file.

This utility is also helpful to read and analyze the content of HTML file. In case you feel any problem, Please contact us or comment below.

 

        /// <summary>
        /// Purpose : To read a HTML file and return as stringbuilder object
        /// </summary>
        public static System.Text.StringBuilder ReadHtmlFile(string pHtmlFileNameWithFullPath)
        {
            System.Text.StringBuilder pSb = new System.Text.StringBuilder();

            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (System.IO.StreamReader mSrHtml = new System.IO.StreamReader(pHtmlFileNameWithFullPath))
                {
                    string mLine;
                    // Read and display lines from the file until the end of
                    // the file is reached.
                    while ((mLine = mSrHtml.ReadLine()) != null)
                    {
                        pSb.Append(mLine);
                    }
                }
            }
            catch (Exception objError)
            {
                throw objError;
            }

            return pSb;
        }

How to Get the List box Selected Items in C# | Loop Through List Box Selection

This Sample post will guide you to get all selected values from a ASP.NET list box control. Just Pass the list box in the given function and it will return all selected values in comma separated format.

you can have selected values in different format or can use inside the loop.

 

       /// <summary>
       /// Gets the Selected Items from the Listbox
       /// </summary>
       /// <param name="lstBox"></param>
       /// <returns></returns>
       public static string sGetSelectedValues(ListBox lstBox)
       {
           string sSelected = "";

           if (Convert.ToInt16(lstBox.SelectedIndex.ToString()) == -1)
               return sSelected;

           for (int i = 0; i < lstBox.Items.Count; i++)
           {
               if (lstBox.Items[i].Selected)
               {
                   sSelected += lstBox.Items[i].Value + ",";

               }
           }
           if (sSelected != "")
               sSelected = sSelected.Substring(0, sSelected.Length - 1);
           return sSelected;

       }

Sunday, April 4, 2010

List of Countries – Array format – C#

This is sample code what developer need while developing a international application just copy this code block in your application and you will have list of all countries in array format.

Please let us know if we missing any country.

 

        /// <summary>
        /// Returns list of countries.
        /// </summary>
        public static string[] CountriesList = new string[] {
         "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
         "Angola", "Anguilla", "Antarctica", "Antigua And Barbuda", "Argentina",
         "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
           "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus",
           "Belgium", "Belize", "Benin", "Bermuda", "Bhutan",
           "Bolivia", "Bosnia Hercegovina", "Botswana", "Bouvet Island", "Brazil",
           "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Byelorussian  SSR",
           "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands",
           "Central African Republic", "Chad", "Chile", "China", "Christmas Island",
           "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Cook Islands",
           "Costa Rica", "Cote D'Ivoire", "Croatia", "Cuba", "Cyprus",
           "Czech Republic", "Czechoslovakia", "Denmark", "Djibouti", "Dominica",
           "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador",
           "England", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia",
           "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France",
           "Gabon", "Gambia", "Georgia", "Germany", "Ghana",
           "Gibraltar", "Great Britain", "Greece", "Greenland", "Grenada",
           "Guadeloupe", "Guam", "Guatemela", "Guernsey", "Guiana",
           "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Islands",
           "Honduras", "Hong Kong", "Hungary", "Iceland", "India",
           "Indonesia", "Iran", "Iraq", "Ireland", "Isle Of Man",
           "Israel", "Italy", "Jamaica", "Japan", "Jersey",
           "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, South",
           "Korea, North", "Kuwait", "Kyrgyzstan", "Lao People's Dem. Rep.", "Latvia",
           "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein",
           "Lithuania", "Luxembourg", "Macau", "Macedonia", "Madagascar",
           "Malawi", "Malaysia", "Maldives", "Mali", "Malta",
           "Mariana Islands", "Marshall Islands", "Martinique", "Mauritania", "Mauritius",
           "Mayotte", "Mexico", "Micronesia", "Moldova", "Monaco",
           "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar",
           "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles",
           "Neutral Zone", "New Caledonia", "New Zealand", "Nicaragua", "Niger",
           "Nigeria", "Niue", "Norfolk Island", "Northern Ireland", "Norway",
           "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea",
           "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland",
           "Polynesia", "Portugal", "Puerto Rico", "Qatar", "Reunion",
           "Romania", "Russian Federation", "Rwanda", "Saint Helena", "Saint Kitts",
           "Saint Lucia", "Saint Pierre", "Saint Vincent", "Samoa", "San Marino",
           "Sao Tome and Principe", "Saudi Arabia", "Scotland", "Senegal", "Seychelles",
           "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
           "Somalia", "South Africa", "South Georgia", "Spain", "Sri Lanka",
           "Sudan", "Suriname", "Svalbard", "Swaziland", "Sweden",
           "Switzerland", "Syrian Arab Republic", "Taiwan", "Tajikista", "Tanzania",
           "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago",
           "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu",
           "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States",
           "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City State", "Venezuela",
           "Vietnam", "Virgin Islands", "Wales", "Western Sahara", "Yemen",
           "Yugoslavia", "Zaire", "Zambia", "Zimbabwe"};

    }

Sponsored Ad

More Related Articles

Website Update

Followers