Multiple arguments with CommandArgument

Handy tip for passing as many arguments as you like with an OnCommand event.

Simply add the attributes you want to pass and the values:

<asp:LinkButton  ID=”LinkButton1″ runat=”server” OnCommand=”link_Clicked” CommandArgument='<%# Eval(“arg1”) %>’ NewArg='<%# Eval(“arg2”) %>‘>Link Here</asp:LinkButton>

Then in the event handler you can access them from the sender attributes:

protected void SubCatLink_Clicked(object sender, CommandEventArgs e)
LinkButton link = (LinkButton)sender;
String NewVal = link.Attributes[“NewArg”].toString();


Rescale and save Image on the server using ASP.Net GetThumbnailImage

A quick function I use to save a rescaled version of an image during upload.

Handle the upload click and do the rescaling:

protected void UploadFileClick(object sender, EventArgs e)
    // get the upload control
    FileUpload FileUpload1 = (FileUpload)ColourFV.FindControl("FileUpload1");
    // get the filename
    String strFileName1 = FileUpload1.PostedFile.FileName;

    if (strFileName1 != "")
        //Grab the file name from its fully qualified path at client 
        TextBox FilenameProfileTbx1 = (TextBox)ColourFV.FindControl("FilenameProfileTbx1");
        //only the attached file name not its path
        String fileName2 = System.IO.Path.GetFileName(strFileName1);

        //Save uploaded file to server 
            FileUpload1.PostedFile.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["your setting"]) + fileName1);
        catch (Exception ex)
            // do any error handling u like here

        // Now this function is called to rescale and save 
        RescaleAndSaveImge((Server.MapPath(ConfigurationManager.AppSettings["your setting"]) + fileName1),
            (Server.MapPath(ConfigurationManager.AppSettings["your setting"]) + "Thumbnails/" + fileName1), 155, 81);


Here is the code for the function to rescale:

    public bool ThumbnailCallback()
        // do any error handling here
        return false;
    // TargetImgFile = filepath of image saved to the server which you want to rescale
    // DestImgFile = filepath of the new image you want to save to
    // NewWidth = new width in px 
    // NewHeight = new height in px
    public void RescaleAndSaveImge(String TargetImgFile, String DestImgFile, Int32 NewWidth, Int32 NewHeight)
        System.Drawing.Image.GetThumbnailImageAbort myCallback = 
            new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); 

        using(System.Drawing.Image TargetImage =
            using (System.Drawing.Image Thumbnail = 
                TargetImage.GetThumbnailImage(NewWidth, NewHeight, myCallback, IntPtr.Zero)) 


Checkbox OnCheckChanged within datalist/repeater/gridview controls do not fire ItemCommand event

I needed a checkbox inside a datalist to call a function when selected/unselected and found it would not fire. It did not raise the container controls itemcommand event.

Here’s a workaround that worked:

Next to your checkbox, create an asp:button with style=”display:none” so that it’s hidden, but enabled. I created a call with this one attribute and set the CssClass=”hider”.

In the codebehind, automate a click of the button when the checkbox (chk) is clicked by doing:

    chk.Add("onclick", "javascript:document.getElementById('" + btn.ClientID + "').click()");

When you check/uncheck the checkbox, the button’s click event will fire and also raise the ItemCommand event on its parent container and you can then do what you need to do here.

Using RadioButton Controls inside a Repeater (groupname problem)

Radio Buttons have the attribute ‘groupname’. The point of this attribute to to ensure any radio buttons in the same group are mutely exclusive (only one in the group can be selected).

This is the case when using them normally but as soon as you put them into a repeater control (e.g. datalist) .Net scrambles the group name value and it no longer works as a group. All can be selected.

This can be fixed with a bit of Javascript and some code during the list databinding event (provided by Microsoft).

See this link ->

Works for .Net 1.0 and 2.0.

Set CheckBox ‘checked’ from SQL DB if an entry exists without any code-behind

Found an interesting way to set the checked value of a checkbox as a databound control. Used in a datalist for example.

The checkbox in the datalist bound to a value in the usual way:

<asp:CheckBox ID=”MainCatCbx” runat=”server” Checked='<%# Eval(“Active”)%>’ CssClass=”smalltext12″ />

Then the query, this was fairly complicated as I wanted to join 2 tables and set the checkbox to ticked if a value was found and not-ticked if it wasn’t, but still display all the records.

The important part (bold) adds a column (active) which is detmind by the result of the case statement. If the DBID column is null the the active column is set to 0(zero) or 1 (one) and cast as a bit so that when the binding takes place it is evaluated as true or false for the checkbox checked value.

SelectCommand=”SELECT tb1.DBID, tb1.Title, tb2.DBID,
tb1.ParentDBID FROM tb1 LEFT OUTER JOIN tb2 ON Specs_NavTbl.DBID = tb2.CatDBID
WHERE (tb2.DBID = ?) OR (tb2.DBID IS NULL)
AND (tb1.ParentDBID = 0)”

I found this to become usefull rather than writing codebehind to populate datasets from the DB and manually loop through and set the checkbox checked values etc.


Formview/Detailsview EditMode & FindControl

This stumped me for a bit today.

I changed a Formview to defaultmode=”edit” and found that FindControl would not work either in Page_Load or even in the FormView databound event – which I found very odd.

Anyway to solve it I just attached a function to the Prerender event for the controls I was trying to change values for (TextBox) and set it there.


Page_Load or DataBound are no good for accessing controls on a Formview in Editmode.

Use the controls Prerender event to handle updating the control value before the page is displayed.

Using SqlBulkCopy to efficiently copy table from Access to SQL Server

SqlBulkCopy is a quick and efficient way to copy a whole table from a source to SQL Server, below shows how to copy from an Access DB to a table in SQL Server.

More info on SqlBulkCopy can be found in this link.

// Setup destination source and delete the table data if already exists

SqlConnection cnn = new SqlConnection(“Data Source=; Password=pass;User ID=user;Initial Catalog=DB” providerName=”System.Data.OleDb”);

// delete backup data
SqlCommand cmd = new SqlCommand(“DELETE FROM LPH_ProductTable”, cnn);
SqlDataReader rdr = cmd.ExecuteReader();

// Setup source data connection
String connString = (“Provider=Microsoft.Jet.OLEDB.4.0;” + “Data Source=” + Server.MapPath(“folder1/folder2/accessfile.mdb”));

// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(connString);

// Set command to get table data
OleDbCommand MDBCommand = new OleDbCommand(“Select * FROM LPH_ProductTable”, objConn);
OleDbDataReader rdr2;

// Open connection with the database.

// Read data
rdr2 = MDBCommand.ExecuteReader();

// Initializing an SqlBulkCopy object for destinaion
SqlBulkCopy sbc = new SqlBulkCopy(“Data; Password=pass;User ID=user;Initial Catalog=DB” providerName=”System.Data.OleDb”);

// Copying data to destination
sbc.DestinationTableName = “DestinationTableName”;

// Closing connection and the others