Vinz' Blog

"Code, Beer and Music ~ my way of being a programmer"
posts - 129, comments - 469, trackbacks - 0

My Links

News

Archives

Image Galleries

I'm a...

I'm at...

Monday, February 01, 2010

Highlight Multiple Dates in Calendar and Make it Selectable

Recently, one of the members at forums.asp.net is asking how to highlight multiple dates in the ASP Calendar and make it selectable and make rest of the unhighlighted dates disabled. So I thought of sharing the solution that I have provided on that thread as a reference to others who might need it.

Here's the code block below:

C#

 

  1. public partial class _Default : System.Web.UI.Page
  2. {
  3.     private List<DateTime> listDates;
  4.     protected void Page_Load(object sender, EventArgs e)
  5.     {
  6.         //Suppose that you have the following list of dates below
  7.         listDates = new List<DateTime>();
  8.         listDates.Add(DateTime.Now);
  9.         listDates.Add(DateTime.Now.AddDays(1));
  10.        
  11.         listDates.Add(DateTime.Now.AddDays(5));
  12.     }
  13.     protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
  14.     {
  15.         //Set Default properties
  16.         e.Day.IsSelectable = false;
  17.         e.Cell.BackColor = System.Drawing.Color.Gray;
  18.         //Now loop through the list of dates and make it
  19.         //Selectable
  20.         foreach (DateTime d in listDates) {
  21.             Calendar1.SelectedDates.Add(d);
  22.             if (e.Day.IsSelected) {
  23.                 e.Cell.BackColor = System.Drawing.Color.Green;
  24.                 e.Day.IsSelectable = true;
  25.             }
  26.         }
  27.     }
  28.     protected void Calendar1_SelectionChanged(object sender, EventArgs e)
  29.     {
  30.         //Print the selected date
  31.         Response.Write("You have selected: " + Calendar1.SelectedDate.ToShortDateString());
  32.     }
  33. }

 

VB.NET

 

  1. Public Partial Class _Default
  2.     Inherits System.Web.UI.Page
  3.     Private listDates As List(Of DateTime)
  4.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
  5.         'Suppose that you have the following list of dates below
  6.         listDates = New List(Of DateTime)()
  7.         listDates.Add(DateTime.Now)
  8.         listDates.Add(DateTime.Now.AddDays(1))
  9.        
  10.         listDates.Add(DateTime.Now.AddDays(5))
  11.     End Sub
  12.     Protected Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As DayRenderEventArgs)
  13.         'Set Default properties
  14.         e.Day.IsSelectable = False
  15.         e.Cell.BackColor = System.Drawing.Color.Gray
  16.         'Now loop through the list of dates and make it
  17.         'Selectable
  18.         For Each d As DateTime In listDates
  19.             Calendar1.SelectedDates.Add(d)
  20.             If e.Day.IsSelected Then
  21.                 e.Cell.BackColor = System.Drawing.Color.Green
  22.                 e.Day.IsSelectable = True
  23.             End If
  24.         Next
  25.     End Sub
  26.     Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)
  27.         'Print the selected date
  28.         Response.Write("You have selected: " & Calendar1.SelectedDate.ToShortDateString())
  29.     End Sub
  30. End Class

As you can see, the code above is very straight forward and self explanatory. Hope you will find this example useful!

posted @ Monday, February 01, 2010 4:16 PM | Feedback (0) |

Wednesday, January 27, 2010

FAQ: How to- Generate Dynamic TexBox in the Form and Save the values to Database

Few months ago I've been seeing many users in the forum asking how to generate dynamic texbox on the form and save the values to the database on Button click, so I've decided to write this post and wrap up all the examples that I wrote before on how to accomplish the task using different controls so that when I encounter such or similar questions again in the forum, I can simply refer them to this post.

Here are those examples:

Using ASP Table:

FAQ: Dynamically Adding Rows in ASP Table on Button Click event

Dynamically Adding TextBox Control to ASPNET Table

Using GridView:

Insert Values  from Dynamic Columns to Database

Adding Dynamic Rows in ASP.Net GridView Control with TextBoxes

For Deleting of rows you can refer here: http://geekswithblogs.net/dotNETvinz/archive/2009/08/12/updated-adding-dynamic-rows-in-asp.net-gridview-control-with-textboxes-again.aspx

For Saving the dynamic data to database you can refer here:

http://www.aspsnippets.com/post/2009/08/16/Save-and-Retrieve-Dynamic-TextBox-values-in-GridView-to-SQL-Server-Database.aspx


Hope you will find this post useful!

posted @ Wednesday, January 27, 2010 7:49 PM | Feedback (0) |

Tuesday, January 19, 2010

Introducing Microsoft WebsiteSpark

Microsoft WebsiteSpark ignites success in the Web business by helping Web Pros to drive new business opportunities through connections with partners and customers around the world. WebsiteSpark also provides Web Pros with Microsoft software and solutions, as well as support and training opportunities. Through their participation in WebsiteSpark, Network Partners can grow their own business and customer base by gaining exposure as a Microsoft partner and participating in an ecosystem that includes not only Web developers and designers, but also their customers. 

For more information, please visit www.microsoft.com/web/websitespark .

posted @ Tuesday, January 19, 2010 10:15 PM | Feedback (0) |

Wednesday, January 06, 2010

FAQ: Cross Browser GridView Fix Header and Footer with ASP.NET Ajax

 

Many developers from the forums (forums.asp.net) are asking if how to implement fix header in GridView while scrolling. We all know that there are lots of examples out there that provide a solution that are available, however some of the solutions provided are not cross browser compatible. While searching for a cross browser solution, I found this article at devarchive.net and it seems very interesting to me. So I play around with the extender provided by devarchive team and thought what if I also wanted to show the footer while scrolling the Grid?So I decided to extend the control a little bit further and added the fix footer while scrolling the rows in the GridView. See the sample screen shots below:

 

IE:

 

 

Firefox:

 

 

Note:I will not elaborate more about the implementation of the extender so before you proceed I would suggest you to read and download the original source codes at devarchive.net first.

 

Here are the updated codes below:

 

GridBoxDesigner.cs

 

using System;

using System.Collections.Generic;

using System.Text;

using System.Web.UI.Design;

using System.Globalization;

using System.Web.UI;

 

namespace GridBox

{

    public class GridBoxDesigner : ControlDesigner

    {

 

        private const string StandardDesignTimeHtml =

        @"<table style=""border:1px solid #CCCCCC;"" cellspacing=""0"" cellpadding=""0"">

        <tr>

        <td nowrap

        style=""font:messagebox;background-color:#ffffff;color:#444444;background-position:bottom;background-repeat:repeat-x;padding:4px;"">

        <strong>{0}</strong> - {1}</td>

        </tr>

        </table>";

 

        public override string GetDesignTimeHtml()

        {

            return

                 String.Format(

                    CultureInfo.InvariantCulture,

                    StandardDesignTimeHtml,

                    Component.GetType().Name,

                    ((Control)Component).ID);

        }

 

    }

}

 

 

GridBoxExtender.cs

 

using System;

using System.Collections.Generic;

using System.Text;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.ComponentModel;

using System.ComponentModel.Design;

using System.Web;

using System.Security.Permissions;

 

namespace GridBox

{

    [

        AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal),

        AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),

        Designer("GridBox.SimpleDesigner, GridBox"),

        ToolboxData("<{0}:GridBoxExtender runat=server></{0}:GridBoxExtender>"),

        TargetControlType(typeof(GridView))

    ]

    public class GridBoxExtender : ExtenderControl

    {

        #region Overrides

        protected override void OnLoad(EventArgs e) {

            base.OnLoad(e);

        }

 

        protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors(Control targetControl) {

            if (TargetControl == null || !TargetControl.Visible || TargetControl.Rows.Count == 0) {

                TargetControl.Height = Unit.Empty;

                yield break;

            }

            ScriptBehaviorDescriptor descriptor = new ScriptBehaviorDescriptor("GridBox.GridBoxExtender", targetControl.ClientID);

            descriptor.AddProperty("scrollField", HiddenFieldID);

            yield return descriptor;

        }

 

        protected override IEnumerable<ScriptReference> GetScriptReferences() {

            if (TargetControl == null || !TargetControl.Visible || TargetControl.Rows.Count == 0) {

                TargetControl.Height = Unit.Empty;

                yield break;

            }

            yield return new ScriptReference("GridBox.GridBoxExtender.js", this.GetType().Assembly.FullName);

        }

 

        protected override void Render(HtmlTextWriter writer) {

            ScriptManager.RegisterHiddenField(

                this,

                HiddenFieldID,

                LastScroll.ToString()

                );

            base.Render(writer);

        }

 

        private GridView TargetControl {

            get {

                GridView result = this.NamingContainer.FindControl(TargetControlID) as GridView;

                return result;

            }

        }

 

        private int LastScroll {

            get {

                int result = 0;

                if (Page.Request[HiddenFieldID] != null) {

                    int.TryParse(Page.Request[HiddenFieldID], out result);

                }

                return result;

            }

        }

 

        private string HiddenFieldID {

            get {

                return String.Format("{0}_GVFHE_Scroll", ClientID);

            }

        }

 

        #endregion

    }

}

 

 

The JavaScript file:

 

GridBoxExtender.js

 

/// <reference name="MicrosoftAjax.debug.js" />

/// <reference name="MicrosoftAjaxTimer.debug.js" />

/// <reference name="MicrosoftAjaxWebForms.debug.js" />

 

Type.registerNamespace("GridBox");

 

    GridBox.GridBoxExtender = function(element) {

    GridBox.GridBoxExtender.initializeBase(this, [element]);

    this._documentResizeDelegate = null;

    this._lock = false;

    this._mainTableID = null;

    this._innerTableID = null;

    this._divChild = null;

   

    this._scrollField = 0;

}

 

GridBox.GridBoxExtender.prototype = {

    // Overrides

    //#region

    initialize: function() {

        GridBox.GridBoxExtender.callBaseMethod(this, 'initialize');

        this.initGrid();

    },

    dispose: function() {

        //Add custom dispose actions here

        $removeHandler(window, "resize", this._documentResizeDelegate);

        if (this._divChild) {

            $clearHandlers(this._divChild);

        }

        GridBox.GridBoxExtender.callBaseMethod(this, 'dispose');

    },

    //#endregion

 

    // Properties

    //#region

    get_scrollField: function() {

        return this._scrollField;

    },

 

    set_scrollField: function(value) {

        if (this._scrollField !== value) {

            this._scrollField = value;

            this.raisePropertyChanged('scrollField');

        }

    },

    //#endregion

 

    // Methods

    //#region

    getLastScroll: function() {

        var result = 0;

        var hf = $get(this._scrollField);

        if (hf) {

            result = parseInt(hf.value);

            if (!result) result = 0;

        }

        return result;

    },

    setLastScroll: function(value) {

        var hf = $get(this._scrollField);

        if (hf) {

            hf.value = value;

        }

    },

    initGrid: function() {

        // create deep clone of target grid

        var target = this.get_element();

        var clone = target.cloneNode(true);

 

        // get desired height of inner scrollable area

        var height = target.style.height;

        var width = target.style.width;

 

        var mainTable = target.cloneNode(false);

        mainTable.id = String.format("outer_{0}", target.id);

        target.parentNode.insertBefore(mainTable, target);

 

 

        var mainHead = document.createElement("thead");

        mainTable.appendChild(mainHead);

        var mainBody = document.createElement("tbody");

        mainTable.appendChild(mainBody);

 

        //**** ADDED FOOTER

        var mainFoot = document.createElement("tfoot");

        mainTable.appendChild(mainFoot);

 

        // Clone original header

        var header = target.rows[0].cloneNode(true);

        mainHead.appendChild(header);

 

        //**** ADDED FOOTER clone footer

        var footer = target.rows[target.rows.length - 1].cloneNode(true);

        mainFoot.appendChild(footer);

 

        // add scrollable area mainTable

        var secondRow = document.createElement("tr");

        mainBody.appendChild(secondRow);

        var mainTd = document.createElement("td");

        secondRow.appendChild(mainTd)

        this.setAttribute(mainTd, "colspan", target.rows[0].cells.length);

        this.setAttribute(mainTd, "align", "left");

        this.setAttribute(mainTd, "valign", "top");

        var divChild = document.createElement("div");

        mainTd.appendChild(divChild);

        divChild.style.width = width;

        divChild.style.height = height;

        $addHandler(divChild, "scroll", Function.createDelegate(this, this.syncScroll));

        divChild.style.overflow = "auto";

        divChild.style.overflowX = "hidden";

        divChild.style.overflowY = "scroll";

        this._divChild = divChild;

 

        //        Sys.UI.DomElement.addCssClass(divChild, "divScrollVertical");

 

        // now remove old grid from document and insert new clone into the place

        target.parentNode.removeChild(target);

        divChild.appendChild(clone);

 

        // assign extender related data to clone

        clone._behaviors = target._behaviors;

        clone.GridBoxExtender = target.GridBoxExtender;

 

        // correct styles

        var attributes = [];

        for (var i = 0; i < clone.attributes.length; i++) {

            var attr = clone.attributes.item(i);

            var value = attr.value.trim().toLowerCase();

            if (value != "cellpadding" && value != "cellspacing") {

                Array.add(attributes, attr);

            }

        }

        Array.forEach(attributes, this.deleteAttribute, clone);

        clone.deleteRow(0); //remove header row

        clone.deleteRow(clone.rows.length - 1); //remove 5footer

        clone.border = "0";

        clone.style.borderWidth = "0px";

        clone.style.width = "100%";

        clone.style.height = "";

        mainTable.style.height = "";

        target.style.height = "";

 

       

        // correct widths of header columns and subscribe to document resize event:

        this._mainTableID = mainTable.id;

        this._innerTableID = clone.id;

        this._documentResizeDelegate = Function.createDelegate(

            this,

            this.syncWidths

        );

        this._documentResizeDelegate.call();

        // Attach to window's resize event to resize header cells when inner cells change their size

        $addHandler(window, "resize", this._documentResizeDelegate);

        // Restore scroll position from last time 

        divChild.scrollTop = this.getLastScroll();

    },

 

    setAttribute: function(element, attribute, value) {

        var namedItem = document.createAttribute(attribute);

        namedItem.value = value;

        element.attributes.setNamedItem(namedItem);

    },

    deleteAttribute: function(attribute, index, attributes) {

        this.removeAttribute(attribute);

    },

    syncScroll: function(args) {

        if (this._divChild) {

            this.setLastScroll(this._divChild.scrollTop);

        }

    },

    syncWidths: function(args) {

        if (!this._lock) {

            this._lock = true;

            var mainTable = $get(this._mainTableID);

            var innerCellPadding = mainTable.cellPadding;

            var header = mainTable.rows[0];

            var innerTable = $get(this._innerTableID);

            var originalRow = innerTable.rows[0];

            var headerWidth = Sys.UI.DomElement.getBounds(header).width;

            var originalRowWidth = Sys.UI.DomElement.getBounds(originalRow).width;

            var diff = headerWidth - originalRowWidth - innerCellPadding * 2;

            if (originalRow && header) {

                for (var i = 0; i < originalRow.cells.length; i++) {

                    var bounds = Sys.UI.DomElement.getBounds(originalRow.cells[i]);

                    var x = bounds.width;

                    if (i == originalRow.cells.length - 1) {

                        x = x + diff - innerCellPadding * 2;

                    } else {

                        x = x - innerCellPadding;

                    }

                    header.cells[i].style.width = x + "px";

                }

            }

            this._lock = false;

        }

    }

    //#endregion

}

GridBox.GridBoxExtender.registerClass('GridBox.GridBoxExtender', Sys.UI.Behavior);

 

 

Usage of the Extender:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestGridBox.aspx.cs" Inherits="TestGridBox" %>

 

<%@ Register Assembly="GridBox" Namespace="GridBox" TagPrefix="cc1" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>GridBox Demo</title>

    <link href="CSS/GridBoxSample.css" rel="stylesheet" type="text/css" />

</head>

<body>

    <form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server"/>

    <div style="width:500px">

        <asp:GridView ID="GridView1" runat="server" Width="100%" GridLines="None" ShowFooter="true"  AutoGenerateColumns="false" CssClass="gridbox" Height="150px">

        <RowStyle CssClass="data-row" />

        <FooterStyle CssClass="footer-style"/>

        <Columns>

            <asp:TemplateField ItemStyle-Width="5%">

            <HeaderTemplate>

                <asp:CheckBox ID="CheckBoxAll" runat="server" Text="All" />

            </HeaderTemplate>

            <ItemTemplate>

                <asp:CheckBox ID="CheckBoxSelect" runat="server" />

            </ItemTemplate>

            <FooterTemplate>

            </FooterTemplate>

            </asp:TemplateField>

            <asp:BoundField DataField="TerminalNumber" HeaderText="Terminal #" ItemStyle-Width="10%"  />

            <asp:BoundField DataField="TransactionNumber" HeaderText="Transaction #" ItemStyle-Width="10%"/>

            <asp:BoundField DataField="OperatorNumber" HeaderText="Operator #" ItemStyle-Width="10%"/>

            <asp:BoundField DataField="OperatorName" HeaderText="Operator Name" ItemStyle-Width="10%"/>

        </Columns>

        </asp:GridView>

       <cc1:GridBoxExtender ID="GridBoxExtender1" runat="server" TargetControlID="GridView1" />

      </div>

    <asp:Button ID="Button1" runat="server" Text="Button" />

    </form>

</body>

</html>

 

That was it! Hope you will find this post useful!

 

Again credits to http://devarchive.net/ (Kirill Chilingarashvili)

posted @ Wednesday, January 06, 2010 5:17 PM | Feedback (0) |

Sunday, December 06, 2009

Rank 3rd at the ASP.NET Community Hall of Fame

 

Wheew..looks like i've been so busy lately.. ;)... I never thought I’d achieve this, but I’ve somehow managed to get to the top 3 rank in ASP.NET Community Hall of Fame..This has been a very rewarding experience [~at least for me :) ]!Honestly, I really can't believe that I have helped hundreds, not only hundreds but I think thousands of geeks already within 2 years of contrinuting through forums at the official Microsoft ASP.NET site.

posted @ Sunday, December 06, 2009 8:11 PM | Feedback (1) |

Tuesday, November 24, 2009

Limit the Number to be Selected in the ListBox control - (Server Side way)

One of the members in the forum (forums.asp.net) is asking how to limit the number of selected items in the ListBox and so contributors (including me) gave the OP (Original Poster) different ideas on how to validate it. Some of them provided solution using pure JavaScripts and a mixture of code behind and JavaScript. However the OP doesn’t want to use JavaScript validation for some reason, so I decided to post the solution that I have provided on that thread as a reference to others.

Here it is:

 

ASPX:

 

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>        

         <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" Height="109px" SelectionMode="Multiple" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" Width="141px">

        <asp:ListItem >A</asp:ListItem>

        <asp:ListItem >B</asp:ListItem>

        <asp:ListItem >C</asp:ListItem>

        <asp:ListItem >D</asp:ListItem>

        <asp:ListItem >E</asp:ListItem>

        <asp:ListItem >F</asp:ListItem>

        </asp:ListBox>

    </div>

    </form>

</body>

</html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

CODE BEHIND:

 

 

protected void Page_Load(object sender, EventArgs e) {

        if (!Page.IsPostBack)

        {

            ListBox1.ClearSelection();

        }

    }

 

    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)

    {

        int count = 0;

        int limit = 0;

        int lastSelectedIndex = 0;

        if(ViewState["lastSelectedIndex"] != null){

            lastSelectedIndex = int.Parse(ViewState["lastSelectedIndex"].ToString());

            ViewState["lastSelectedIndex"] = lastSelectedIndex;

        }

        else{

            lastSelectedIndex = ListBox1.SelectedIndex;

        }

            for (int i = 0; i < ListBox1.Items.Count; i++) {

            if (ListBox1.Items[i].Selected) {

                if (ViewState["CountLimit"] != null) {

                    count++;

                    ViewState["CountLimit"] = count;

                    limit = (int)ViewState["CountLimit"];

                }

                else {

                    count++;

                    ViewState["CountLimit"] = count;

                }

                if (limit > 3) // Selected Item Limit is up to 3

                {

                    Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowBox", "alert('You are only allowed to Select 3 items!');", true);

                    ListBox1.Items[lastSelectedIndex].Selected = false;

                }

            }

        }

    }

 

 That's it! Hope you will find this example useful!

 

posted @ Tuesday, November 24, 2009 2:52 PM | Feedback (0) |

Sunday, October 18, 2009

Hide Panel When Clicking Anywhere in the Page

This example shows how to hide a Div when clicking anywhere the page:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

      <script type="text/javascript" language="javascript">

        function HideDiv()

        {

             document.getElementById("ContainerDiv").style.display = 'none';

             return false;

        }

        function ShowDiv(e)

        {

            document.getElementById("ContainerDiv").style.display = 'block';

            if(!e)

            e=window.event;

            e.cancelBubble=true;

            return false;

        }

    </script>

</head>

<body onclick="return HideDiv();">

    <form id="form1" runat="server">

    <asp:Button ID="Button1" runat="server" Text="Show Div" OnClientClick="return ShowDiv(event);" />

      <div id="ContainerDiv"

       style="width:521px;

              height:200px;

              background-color:Gray;

              left:150px;

              position:absolute;

              top: 201px;

              display:block"

              align="center"

              onclick ="return ShowDiv(event);">

       HELLO ASP.NET

       <br />

       <asp:TextBox ID="TextBox1" runat="server" onclick = "return ShowDiv(event);"></asp:TextBox>

      </div>

    </form>

</body>

</html>


That's it!

posted @ Sunday, October 18, 2009 2:22 PM | Feedback (0) |

Thursday, October 08, 2009

Move Multiple Rows Between GridViews

This example shows how to move multiple rows between GridViews. The main idea here is to use a CheckBox control for selecting the rows to be removed from one GridView to another and vise versa.

 

Take a look at sample screen shots below:

 

On initial load:



 Selecting rows from the left GridView:


 

After Moving the selected rows to the right GridView:

As you notice the selected rows are automatically sorted by its ID upon moving.

Selecting rows from the Right GridView:

After Moving the selected rows to the Left GridView:



Here are the code blocks below for the implementation:


ASPX SOURCE:

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    </div>

    <table>

        <tr>

            <td valign="top">

                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

                <Columns>

                    <asp:TemplateField>

                        <ItemTemplate>

                            <asp:CheckBox ID="CheckBox1" runat="server" />

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:BoundField DataField="EmployeeID" HeaderText="ID" />

                    <asp:BoundField DataField="LastName" HeaderText="Last Name" />

                    <asp:BoundField DataField="FirstName" HeaderText="First Name" />

                </Columns>

                </asp:GridView>

            </td>

            <td>

                <asp:Button ID="Button1" runat="server" Text=">>>" onclick="Button1_Click" />

                <br />

                <asp:Button ID="Button2" runat="server" Text="<<<" onclick="Button2_Click" />

            </td>

            <td valign="top">

               <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">

                <Columns>

                    <asp:TemplateField>

                        <ItemTemplate>

                            <asp:CheckBox ID="CheckBox1" runat="server" />

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:BoundField DataField="EmployeeID" HeaderText="ID" />

                    <asp:BoundField DataField="LastName" HeaderText="Last Name" />

                    <asp:BoundField DataField="FirstName" HeaderText="First Name" />

                </Columns>

              </asp:GridView>

            </td>

        </tr>

    </table>

    </form>

</body>

</html>

 

 

RELEVANT CODES:

 

public partial class AddMultipleRowsGridView : System.Web.UI.Page

{

    private DataTable _clonedTable;

 

    private string GetConnectionString()

    {

        return @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Northwind.mdf;Integrated Security=True;User Instance=True";

    }

 

    private DataTable QueryData()

    {

        DataTable dt = new DataTable();

        SqlConnection connection = new SqlConnection(GetConnectionString());

        try

        {

            connection.Open();

            string sqlStatement = "SELECT TOP(10)EmployeeID, LastName, FirstName FROM Employees";

            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);

            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            sqlDa.Fill(dt);

        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            string msg = "Fetch Error:";

            msg += ex.Message;

            throw new Exception(msg);

        }

        finally

        {

            connection.Close();

        }

 

        return dt;

    }

 

    private void BindGrid(DataTable dt, GridView gv)

    {

        if (dt.Rows.Count > 0)

        {

            dt = TrimEmptyRow(dt);

            gv.DataSource = SortData(dt);

            gv.DataBind();

        }

        else

        {

            ShowNoResultFound(dt, gv);

        }

        if (gv.ID == "GridView1")

            ViewState["OrigData"] = dt;

        else

        {

            ViewState["MovedData"] = dt;

        }

    }

    private DataTable SortData(DataTable dt)

    {

        DataView dv = dt.DefaultView;

        dv.Sort = "EmployeeID ASC";

        dt = dv.ToTable();

 

        return dt;

    }

       

    private void MoveRows(DataTable dt, GridView gv)

    {

            for (int i = gv.Rows.Count - 1; i >= 0; i--)

            {

                CheckBox cb = (CheckBox)gv.Rows[i].Cells[0].FindControl("CheckBox1");

                if (cb != null)

                {

                    if (cb.Checked)

                    {

                        AddRow(dt.Rows[i], gv);

                        dt.Rows.Remove(dt.Rows[i]);

                    }

                }

            }

            BindGrid(dt, gv);

    }

 

    private void AddRow(DataRow row,GridView gv)

    {

        DataTable dt = null;

        if (ViewState["MovedData"] == null)

        {

            dt = (DataTable)ViewState["ClonedTable"];

            dt.ImportRow(row);

            dt.Rows.Remove(dt.Rows[0]);

            ViewState["MovedData"] = dt;

            BindGrid(dt, GridView2);

        }

        else

        {

            if (gv.ID == "GridView1")

            {

                dt = (DataTable)ViewState["MovedData"];

                dt.ImportRow(row);

                ViewState["MovedData"] = dt;

                BindGrid(dt, GridView2);

            }

            else

            {

                dt = (DataTable)ViewState["OrigData"];

                dt.ImportRow(row);

                ViewState["OrigData"] = dt;

                BindGrid(dt, GridView1);

            }

        }

    }

 

    private DataTable TrimEmptyRow(DataTable dt)

    {

        if (dt.Rows[0][0].ToString() == string.Empty)

        {

            dt.Rows.Remove(dt.Rows[0]);

        }

        return dt;

    }

 

    private void ShowNoResultFound(DataTable source, GridView gv)

    {

 

        source.Rows.Add(source.NewRow()); // create a new blank row to the DataTable

        // Bind the DataTable which contain a blank row to the GridView

        gv.DataSource = source;

        gv.DataBind();

        // Get the total number of columns in the GridView to know what the Column Span should be

        int columnsCount = gv.Columns.Count;

        gv.Rows[0].Cells.Clear();// clear all the cells in the row

        gv.Rows[0].Cells.Add(new TableCell()); //add a new blank cell

        gv.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell

        //You can set the styles here

        gv.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;

        gv.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;

        gv.Rows[0].Cells[0].Font.Bold = true;

        //set No Results found to the new added cell

        gv.Rows[0].Cells[0].Text = "NO ITEMS FOUND!";

 

    }

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            BindGrid(QueryData(), GridView1);

            _clonedTable = QueryData().Clone();

            ViewState["ClonedTable"] = _clonedTable;

 

            ShowNoResultFound(_clonedTable, GridView2);

        }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        DataTable dtOrigData = (DataTable)ViewState["OrigData"];

        MoveRows(SortData(dtOrigData), GridView1);

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        DataTable dtMovedData = (DataTable)ViewState["MovedData"];

        MoveRows(SortData(dtMovedData), GridView2);

    }

}

 


As you can see the code above was very self explanatory and straight forward. Hope you will find this example useful!


posted @ Thursday, October 08, 2009 11:19 PM | Feedback (0) |

Thursday, September 10, 2009

How To: Reset Identity Column Value in SQL Table

Recently, one of the members at forums.asp.net is asking if how to reset identity count in sql table. So I thought of sharing the possible solution that we have discussed in this thread as a reference to others.

HTH!

posted @ Thursday, September 10, 2009 2:17 PM | Feedback (0) |

Monday, September 07, 2009

Good News!: SEA MVPs Blog-A-Holic has Officially Launched Today

Check this out:

Microsoft SEA MVP Blog

posted @ Monday, September 07, 2009 1:49 PM | Feedback (0) |

Powered by: