Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

27 May 2021

Visual Studio: how to temporarily deactivate all try / catch blocks

To catch exceptions the moment they're thrown ("first-chance exceptions" in Win32 parlance):
  • in VS2008: go to Debug, Exceptions...
  • in VS2015 (and later): this has been moved to Debug > Windows > Exception Settings
Then check the box Thrown for Common Language Runtime Exceptions:


Found here.

10 November 2017

System.IO.IOException: The process cannot access the file 'file_name'

Quando cancelli o sposti un file:
GC.Collect()
GC.WaitForPendingFinalizers()

Se non basta, provare anche questo (non testato):
public static System.Boolean FileInUse(System.String file)
{
    try
    {
        if (!System.IO.File.Exists(file)) // The path might also be invalid.
        {
            return false;
        }

        using (System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open))
        {
            return false;
        }
    }
    catch
    {
        return true;
    }
}

Also, to wait for a file I have made:
public static void WaitForFile(System.String file)
{
    // While the file is in use...
    while (FileInUse(file)) ; // Do nothing.
}

Via.

12 April 2017

Generate a Stream from a String

in C#:
public static MemoryStream GenerateStreamFromString(string value)
{
    return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}

in VB:
Dim myStream As New MemoryStream(Encoding.UTF8.GetBytes(If(rawData, "")))



Another solution:
public static Stream GenerateStreamFromString(string s)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;
}

Don't forget to use Using:


using (Stream s = GenerateStreamFromString("a,b \n c,d"))
{
    // ... Do stuff to stream
}

About the StreamWriter not being disposed. StreamWriter is just a wrapper around the base stream, and doesn't use any resources that need to be disposed. The Dispose method will close the underlying Stream that StreamWriter is writing to. In this case that is the MemoryStream we want to return.

In .NET 4.5 there is now an overload for StreamWriter that keeps the underlying stream open after the writer is disposed of, but this code does the same thing and works with other versions of .NET too.



Trovato qui.

08 March 2013

Generating UTF-8 with System.Xml.XmlWriter

Today i decided to experiment with XmlWriter. The first i wanted to do was set the Encoding to UTF-8.:
StringBuilder stringBuilder = new StringBuilder();
XmlWriter xmlWriter = XmlWriter.Create(stringBuilder);
xmlWriter.Settings.Encoding = Encoding.UTF8;

When i ran this code i recieved the following exception: XmlException was unhandled: The "XmlWriterSettings.Encoding" property is read only and cannot be set. The documentation for the Settings property clearly says:
The XmlWriterSettings object returned by the Settings property cannot be modified. Any attempt to change individual settings results in an exception being thrown.

So i wrote the following:
StringBuilder stringBuilder = new StringBuilder();
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Encoding = Encoding.UTF8;
 
XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("root", "http://www.timvw.be/ns");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
 
string xmlString = stringBuilder.ToString();

As you can see: is still not what i want. Apparently is the Encoding property ignored if the XmlWriter is not using a Stream. So here is my next attempt:
MemoryStream memoryStream = new MemoryStream();
// initialize xmlWriterSettings as above...
 
XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
// call the same operations on the xmlWriter as above...
 
string xmlString = Encoding.UTF8.GetString(memoryStream.ToArray());

Ok, i'm getting close:
?




Luckily enough i knew that the ? (byte with value 239) at the beginning is the BOM (Byte Order Mark). In order to get rid of that byte i had to create my own instance of UTF8Encoding. Finally, i can present some working code:
MemoryStream memoryStream = new MemoryStream();
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Encoding = new UTF8Encoding(false);
xmlWriterSettings.ConformanceLevel = ConformanceLevel.Document;
xmlWriterSettings.Indent = true;
 
XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("root", "http://www.timvw.be/ns");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
 
string xmlString = Encoding.UTF8.GetString(memoryStream.ToArray());


Trovato qui.

06 March 2013

Get NBA scores RSS from ESPN

Ad esempio, l'URL http://sports.espn.go.com/nba/bottomline/scores ritorna questa stringa:

&nba_s_delay=120&nba_s_stamp=0306085718&nba_s_left1=^Boston%20109%20%20%20Philadelphia%20101%20(FINAL)&nba_s_right1_1=P.%20Pierce%2018pts,%207ast,%2011reb&nba_s_right1_2=J.%20Holiday%2018pts,%2010ast,%205reb&nba_s_right1_count=2&nba_s_url1=http://sports.espn.go.com/nba/boxscore?gameId=400278616&nba_s_left2=LA%20Lakers%20105%20%20%20^Oklahoma%20City%20122%20(FINAL)&nba_s_right2_1=K.%20Bryant%2030pts,%202ast,%203reb&nba_s_right2_2=R.%20Westbrook%2037pts,%205ast,%2010reb&nba_s_right2_count=2&nba_s_url2=http://sports.espn.go.com/nba/boxscore?gameId=400278617&nba_s_left3=^Denver%20120%20%20%20Sacramento%20113%20(FINAL)&nba_s_right3_1=T.%20Lawson%2024pts,%207ast,%203reb&nba_s_right3_2=I.%20Thomas%2023pts,%208ast,%203reb&nba_s_right3_3=D.%20Cousins%205%20blocks&nba_s_right3_4=M.%20Thornton%205-11%20three%20pointers&nba_s_right3_count=4&nba_s_url3=http://sports.espn.go.com/nba/boxscore?gameId=400278618&nba_s_count=3&nba_s_loaded=true


Il parametro nell'URL è la "/nba/".

Questo programma prende la stringa di output, e la splitta:







Debug delle coppie nome/valore:

nba_s_delay=120
nba_s_stamp=0306072047

nba_s_left1=Boston 109 Philadelphia 101 (FINAL)
nba_s_right1_1=P. Pierce 18pts, 7ast, 11reb
nba_s_right1_2=J. Holiday 18pts, 10ast, 5reb
nba_s_right1_count=2
nba_s_url1=http://sports.espn.go.com/nba/boxscore?gameId=400278616

nba_s_left2=LA Lakers 105 Oklahoma City 122 (FINAL)
nba_s_right2_1=K. Bryant 30pts, 2ast, 3reb
nba_s_right2_2=R. Westbrook 37pts, 5ast, 10reb
nba_s_right2_count=2
nba_s_url2=http://sports.espn.go.com/nba/boxscore?gameId=400278617

nba_s_left3=Denver 120 Sacramento 113 (FINAL)
nba_s_right3_1=T. Lawson 24pts, 7ast, 3reb
nba_s_right3_2=I. Thomas 23pts, 8ast, 3reb
nba_s_right3_3=D. Cousins 5 blocks
nba_s_right3_4=M. Thornton 5-11 three pointers
nba_s_right3_count=4

nba_s_url3=http://sports.espn.go.com/nba/boxscore?gameId=400278618
nba_s_count=3
nba_s_loaded=true




Versione PHP originale, che crea un RSS:
\n\n";
echo "\n\n";
echo "\n\n";
echo "\n";

echo "NBA Scores\n";
echo "http://www.nba.com\n";
echo "NBA Scores\n";
echo "en-us\n";
echo "\n";
echo " NBA Scores\n";
echo " http://www.mpiii.com/scores/nba.gif\n";
echo " http://www.nba.com\n";
echo "\n";
echo "info@nba.com\n";

$content = get_content ("http://sports.espn.go.com/nba/bottomline/scores");

$content_array=explode("&", $content);
$scorearray = array();
$i=0;
foreach($content_array as $content) {
	if (strpos($content, "_left")) {
		$equalpos = strpos($content, "=");
		$end = strlen($content);
		$title = substr($content, ($equalpos+1), $end);
		$title = str_replace("^", "", $title);
		$title = str_replace("%20", " ", $title);
		$scorearray[$i]["title"] = $title;

	}
	if (strpos($content, "_url")) {
		$equalpos = strpos($content, "=");
		$end = strlen($content);
		$url = substr($content, ($equalpos+1), $end);
		$url = str_replace("^", "", $url);
		$url = str_replace("%20", " ", $url);
		$scorearray[$i]["url"] = $url;
				$i++;

	}
}
foreach($scorearray as $score) {
	echo "\n";
	echo "".$score["title"]."\n";
	echo "".$score["url"]."\n";
	echo "\n";
}

echo "\n";
echo "\n";
?>


Trovato qui e qui.

Elenco di tutti i parametri/feed di espn.

Sono i dati utilizzati dall'applicazione ESPN Bottomline.

04 October 2012

Using Multiple Programming Languages in a Web Site Project

By default, the App_Code folder does not allow multiple programming languages. However, in a Web site project you can modify your folder structure and configuration settings to support multiple programming languages such as Visual Basic and C#. This allows ASP.NET to create multiple assemblies, one for each language.

The App_Code folder is not explicitly marked as containing files written in any one programming language. Instead, the ASP.NET infers which compiler to invoke for the App_Code folder based on the files it contains. If the App_Code folder contains .vb files, ASP.NET uses the Visual Basic compiler; if it contains .cs files, ASP.NET uses the C# compiler, and so on.

 
  
  
 


Trovato qui e qui.

03 November 2011

VB.NET and C# Comparison

Scarica il PDF! =)

Trovato qui.

21 October 2011

Use asp:Menu and asp:MultiView to create tab control

/*
ASP.NET 2.0 Unleashed (Unleashed) (Hardcover)
by Stephen Walther 

# Publisher: Sams; Bk&CD-Rom edition (June 6, 2006)
# Language: English
# ISBN: 0672328232
*/

<%@ Page Language="C#" %>




    
    MultiView Tabs


    

This is the first view
This is the first view
This is the first view
This is the first view

This is the second view
This is the second view
This is the second view
This is the second view

This is the third view
This is the third view
This is the third view
This is the third view

Trovato qui.

17 May 2010

Chiudere la connessione dal DataReader

When you create a DataReader, you call .ExecuteDataReader. This method accepts a parameter that can be CommandBehavior.CloseConnection. This parameter tells the DataReader that when it is closed, the underlying connection should be closed as well. This is an example function that shows how you can return a DataReader and ensure that it is closed by the calling method:
// C# version

public static IDataReader SelectByRoyalty(int Percentage)
{ 
 SqlDataReader dr=null;
 SqlConnection cn=new SqlConnection
                  ("Server=Aron1;Database=pubs;Trusted_Connection=True;");
 cn.Open();
 try
 {
  SqlCommand cmd=new SqlCommand("byRoyalty",cn);
  cmd.CommandType=CommandType.StoredProcedure;
  cmd.Parameters.Add("@Percentage",Percentage);
   
  dr=cmd.ExecuteReader(CommandBehavior.CloseConnection);
 }
 catch ( Exception Ex )
 {
  if ( dr!=null )
  {
   dr.Close();
   cn.Close();
  }
  throw Ex;
 }
 return (IDataReader)dr;
}
' VB version

Public Shared Function SelectByRoyalty(ByVal Percentage As Integer) As IDataReader
    Dim dr As SqlDataReader = Nothing
    Dim cn As New SqlConnection("Server=Aron1;Database=pubs;Trusted_Connection=True;")
    cn.Open()
    Try
        Dim cmd As New SqlCommand("byRoyalty", cn)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.Add("@Percentage", Percentage)

        dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
    Catch Ex As Exception
        If dr <> Nothing Then
            dr.Close()
            cn.Close()
        End If
        Throw Ex
    End Try
    Return DirectCast(dr, IDataReader)
End Function
Then, you could call the method as follows:
IDataReader dr=Coatings.SelectCoating(CoatingID);
try
{
 // Use the DataReader..
}
Finally
{
 dr.Close();
}
Failure to use a pattern like this will lead to a great deal of difficulty with connections that are not closed in a timely fashion. I believe that Microsoft initially pushed DataReaders as the preferred way to do database access, at least for ASP.NET applications. As time went on, I think the company discovered that many developers misused DataReaders, not properly closing the connection. Recent Microsoft presentations have often emphasized DataSets even for ASP.NET applications.

01 March 2010

Console Screen Buffer

If you plan on making any console based games with the screen refreshing constantly you will find it flickers a lot unless you use what is known as a buffer. Here I show you a class that has a couple of functions to draw to, and then output the "image" to the console.

public class ScreenBuffer
{					
    //initiate important variables
    public static char[,] screenBufferArray = new char[roomWidth,roomHeight]; //main buffer array
    public static string screenBuffer; //buffer as string (used when drawing)
    public static Char[] arr; //temporary array for drawing string
    public static int i = 0; //keeps track of the place in the array to draw to
 
    //this method takes a string, and a pair of coordinates and writes it to the buffer
    public static void Draw(string text, int x, int y)
    {
        //split text into array
        arr = text.ToCharArray(0,text.Length);
        //iterate through the array, adding values to buffer 
        i = 0;
        foreach (char c in arr)
        {
            screenBufferArray[x + i,y] = c;
            i++;
        }   
    }
 
    public static void DrawScreen()
    {
        screenBuffer = "";
        //iterate through buffer, adding each value to screenBuffer
        for (int iy = 0; iy < roomHeight-1; iy++)
        {
            for (int ix = 0; ix < roomWidth; ix++)
            {
                screenBuffer += screenBufferArray[ix, iy];
            }
        }
    //set cursor position to top left and draw the string
        Console.SetCursorPosition(0, 0);
        Console.Write(screenBuffer);
        screenBufferArray = new char[Game.roomWidth, Game.roomHeight];
    //note that the screen is NOT cleared at any point as this will simply overwrite the existing values on screen. Clearing will cause flickering again.
    }
 
}

roomWidth and roomHeight are the width and height of your console screen respectively. This can easily be set using

Console.SetWindowSize(roomWidth,roomHeight);

Usage

Usage is very simple with this class. First of all you'll need to create the class by using

ScreenBuffer sb = new ScreenBuffer();

This simply create an instance of the ScreenBuffer class with the reference "sb" (you can change this to whatever you want). To draw to it all you need to do is use the method Draw.

ScreenBuffer.Draw("text here",x,y);

Beware that this method will not handle new lines correctly. This could be easily added by using a check within the draw function, and if it detects \n simply jump the the next line in the array. Now all you need to do is call the DrawScreen method at the end of the frame you are displaying and the array will be flushed onto the console screen, giving you a flicker free game!

~ knighty (Graeme Pollard - )

Trovato qui.

10 November 2009

Jaw-dropping experience with custom build providers

Source file: DalGeneratorBuildProvider.zip

Every once in a while when I'm exploring a technology, I experience a jaw-dropping moment where I'm blown away by how elegant, or well designed, or rife with potential something is. This weekend I had such a moment with ASP.NET 2.0 (yes, I know it was a holiday weekend, but I suddenly have a lot of deadlines looming). In preparation for a conference talk I'm giving at WinDev this year on compiliation in ASP.NET 2.0, I had a chance to try building my own custom build provider. As you may already know, when you place a source code file (like mycomponent.cs) under the top level /code directory it is compiled into an assembly and the rest of your pages can then reference the classes in that assembly. This is a nice feature in that it completes the delay-compile picture for deployment. In the ASP.NET 1.x you had to pre-compile any components you wanted to include and deploy them in the /bin directory (or find a page that wasn't using code behind and hijack its src= attribute, or use the assembly directive, each of which had its own set of issues). Now you can truly deploy nothing but .as*x and source files to a site, or even work in that mode and deploy with only binary.

What's even more interesting about the /code directory is that you can place other types of files in it as well, including .wsdl and .xsd files. Dropping a .wsdl file into /code will trigger a custom build step that involves generating a webservice proxy class which you then have immediate access to in your pages. VS.NET 2005 has really nice support for this too - as soon as you drop a .wsdl file into the directory you can use the object browser to view the generated proxy class, and you immediately have intellisense in all your pages for the proxy. Dropping a .xsd file into /code generates a typesafe DataSet-derived class like you may have used in the past when you ran the xsd.exe utility or selected 'Generate typesafe DataSet' from the designer.

Anyway, these are nice features, but this was not the jaw-dropping momemt for me. It turns out that you can build your own 'builder' and associate it with a specific extension. Once you deploy it, any file with your extension placed in the /code directory will then use your builder to spit out whatever code you want and compile it as part of the generated assembly for the /code directory. I have recently been working on building a data access layer for a client of mine, and for a number of reasons we chose not to go with typed DataSets, so instead I had written a code generator to extract schema information from a database connection and spit out a class with all the appropriate fields and properties based on the column types (actually similar to what the typed DataSet generator does, but without a lot of the other baggage). This seemed like a perfect candidate to test out as a custom builder, so I set to work.

The first step was to define the input file for my builder (this would be the file you place in the /code directory once I was done). I had an XML format I had been using, so I stuck with it and decided to use the extension of .dal for the file association. Here's a sample .dal file that would generate a class for the authors, publishers, discounts, and sales tables of the pubs database:

<!-- file: pubs.dal -->
<dalGenerator>
  <connectionString>server=.;trusted_connection=yes;database=pubs</connectionString>
  
  <namespace>MyDAL</namespace>
  
  <tables>
    <table>
      <name>authors</name>
    </table>
    <table>
      <name>publishers</name>
    </table>
    <table>
      <name>discounts</name>
    </table>
    <table>
      <name>sales</name>
    </table>
  </tables>
  
</dalGenerator>
Now, to associate the .dal extension with a custom build provider, you add an entry to your web.config file that looks like:
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <system.web>
    <compilation>
      <buildProviders>
        <add extension=".dal" appliesTo="Code" type="PS.DalBuildProvider" />
      </buildProviders>
    </compilation>
  </system.web>
</configuration>

Where the PS.DalBuildProvider was the class I had yet to build. So the next step is obviously to go build the build provider class. To do this, you create a class the derives from the BuildProviderabstract base class, and most of the time you will just override the GenerateCode method which takes a reference to a AssemblyBuilder class as a paramter. Your job in this method is to create a newCodeCompileUnit (yes, you have to use the CodeDom) filled with whatever code you want compiled and add it to the AssemblyBuilder as a compile unit.

Here's a shell of such a class to give you an idea of what must be done - I've used theCodeSnippetCompileUnit in this sample so I can easily drop in a chunk of C# code. In the realDalBuildProvider I used the CodeDom classes (I'll provide a link to the complete sample below) which I recommend you do too for language independence.

using System;
using System.Text;
using System.Web.Compilation;
using System.Web;
using System.Web.UI;
using System.CodeDom;
using System.Web.Hosting;
using System.IO;
namespace PS
{
  public class DalBuildProvider : BuildProvider
  {
    public override void GenerateCode(AssemblyBuilder ab)
    {
   // retrieve input file
      string filename = base.VirtualPath;
      XmlDocument doc = new XmlDocument();
      using (Stream inFile = VirtualPathProvider.OpenFile(base.VirtualPath))
      {
        doc.Load(inFile);
      }
   // this is where I would navigate the DOM to generate code
   string sampleCode = "class Foo {}";
      ab.AddCodeCompileUnit(this, 
        new CodeSnippetCompileUnit(samplecode));
    }
  }
}

Once this class was built, I deployed it in my local /bin and added the pubs.dal file shown above to the /code directory, and it worked! Here's a screenshot of what the screen looked like when my jaw actually hit the floor :)

Screenshot

by fritz-onion.

Trovato qui.

26 October 2009

Tips on Optimizing Your Queries

The next few paragraphs will attempt to give you a few rudimentary rules for speeding up your queries in general, and especially how SQLite is adversely affected by the kinds of SQL behaviors you may have taken for granted in other providers. It is by no means a complete optimization guide. For even more details on optimizing your queries, visit sqlite.org.
The Importance of Transactions

If you are inserting data in SQLite without first starting a transaction: DO NOT PASS GO! Call BeginTransaction() right now, and finish with Commit()! If you think I'm kidding, think again. SQLite's A.C.I.D. design means that every single time you insert any data outside a transaction, an implicit transaction is constructed, the insert made, and the transaction destructed. EVERY TIME. If you're wondering why in the world your inserts are taking 100x longer than you think they should, look no further.
Prepared Statements

Lets have a quick look at the following code and evaluate its performance:

      using (SQLiteCommand mycommand = new SQLiteCommand(myconnection))
      {
        int n;
        
        for (n = 0; n < 100000; n ++)
        {
          mycommand.CommandText = String.Format("INSERT INTO [MyTable] ([MyId]) VALUES({0})", n + 1);
          mycommand.ExecuteNonQuery();
        }
      }

This code seems pretty tight, but if you think it performs well, you're dead wrong. Here's what's wrong with it:

  • I didn't start a transaction first! This insert is dog slow!
  • The CLR is calling "new" implicitly 100,000 times because I am formatting a string in the loop for every insert
  • Since SQLite precompiles SQL statements, the engine is constructing and deconstructing 100,000 SQL statements and allocating/deallocating their memory
  • All this construction and destruction is involving about 300,000 more native to managed interop calls than an optimized insert

So lets rewrite that code slightly:

      using (SQLiteTransaction mytransaction = myconnection.BeginTransaction())
      {
        using (SQLiteCommand mycommand = new SQLiteCommand(myconnection))
        {
          SQLiteParameter myparam = new SQLiteParameter();
          int n;
        
          mycommand.CommandText = "INSERT INTO [MyTable] ([MyId]) VALUES(?)";
          mycommand.Parameters.Add(myparam);
          
          for (n = 0; n < 100000; n ++)
          {
            myparam.Value = n + 1;
            mycommand.ExecuteNonQuery();
          }
        }
        mytransaction.Commit();
      } 

Now this is a blazing fast insert for any database engine, not just SQLite. The SQL statement is prepared one time -- on the first call to ExecuteNonQuery(). Once prepared, it never needs re-evaluating. Furthermore, we're allocating no memory in the loop and doing a very minimal number of interop transitions. Surround the entire thing with a transaction, and the performance of this insert is so far and away faster than the original that it merits a hands-on-the-hips pirate-like laugh.

Every database engine worth its salt utilizes prepared statements. If you're not coding for this, you're not writing optimized SQL, and that's the bottom line.

13 October 2009

Ottenere una lista in italiano dei mesi dell'anno

VB.NET
    For i As Integer = 1 To 12
      Dim s As String = New DateTime(DateTime.Now.Year, i, 1).ToString("MMMM", _
                                     New System.Globalization.CultureInfo("it-IT"))
      System.Diagnostics.Debug.WriteLine(s)
    Next
C#
      for (int i = 1; i < 13; i++)
      {
         string s = new DateTime(DateTime.Now.Year,i,1).ToString("MMMM",
                                 new System.Globalization.CultureInfo("it-IT"));
         System.Diagnostics.Debug.WriteLine(s);
      }

18 May 2009

Working with a CheckBoxList

/******************************************************************************
 
 Q10028 - C#: Working with a CheckBoxList

 Article ID: Q10028
 Created Date: 5/7/2007
 Last Modified: 5/7/2007
 Author: Dale
 Original URL: http://www.geekycodesamples.com/article.aspx?id=10028
 
******************************************************************************/




// How to populate a CheckBoxList from a DataTable
private void PopulateCheckboxList(CheckBoxList chkList)
{
   ProdConfigSupport pcs = new ProdConfigSupport();

   DataTable dt = pcs.GetProductList();

   if (dt != null && dt.Rows.Count > 0)
 {
       chkList.DataSource = dt;
       chkList.DataTextField = "ProductDescription";
       chkList.DataValueField = "ProductID";
       chkList.DataBind();
       chkList.Visible = true;
   }
 else
 {
       chkList.Visible = false;
   }
}




// How to iterate through a checkbox list. In this case we are
// capturing the ‘value’ of any Checkboxes that were selected
// and packaging them into an ArrayList
ArrayList arySelectedProducts = new ArrayList();

foreach (ListItem itm in chkBoxListProducts.Items)
{
   if (itm.Selected)
 {
       arySelectedProducts.Add(itm.Value);
   }
}




// How to programmatically ‘check’ the previously-checked selections
// of a CheckBoxList. In this case, the method
// GetPreviouslySelectedProducts() populates an ArrayList called
// arySelectedProducts that contains a list of the ProductID’s
// that should be ‘checked’
ArrayList arySelectedProducts = GetPreviouslySelectedProducts();

foreach (ListItem itm in this. chkBoxListProducts.Items)
{
   if (arySelectedProducts.Contains(Convert.ToString(itm.Value)))
 {
       itm.Selected = true;
   }
}