1

Unable To Debug The Binding Handle Is Invalid VS2005

Unable To Debug The Binding Handle Is Invalid Error VS2005. If you are trying to debug in Visual Studio 2005 and and not able to use breakpoints and getting unable to debug - the binding handle is invalid error in VS 2005 than follow these steps to fix this error.

Go control panel of your windows OS

Double click on Administrative tools > services

Now in services window > look for Terminal Services

Right click on it ans select properties > check it's startup type > it might be disabled

Restart the service and change startup type to Automatic

This should fix your problem

18

AutoNumber Column In GridView DataList ASP.NET

This example explains how to Add AutoNumber Column In GridView Or DataList In ASP.NET 2.0,3.5,4.0 Using C# And VB.NET. Several times we need to display Auto Number or serial number for Rows records in gridview or other similar controls in ASP.NET.

We can add AutoNumber column by using Container.DataItemIndex property in html markup of the Gridview.



Here's the sample html markup for the page

<title>Auto Number Cloumn in GridView </title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" 
              AllowPaging="True" AutoGenerateColumns="False"
              DataSourceID="SqlDataSource1" PageSize="6" 
              AlternatingRowStyle-BackColor="#006699" 
              AlternatingRowStyle-ForeColor="#FFFFFF" >
    <Columns>
    <asp:TemplateField HeaderText="Serial Number">
    <ItemTemplate>
        <%# Container.DataItemIndex + 1 %>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="Name" HeaderText="Name" 
                    SortExpression="Name" />
    <asp:BoundField DataField="Location" HeaderText="Location" 
                    SortExpression="Location" />
    </Columns>
    </asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Name], [Location] FROM [Details]">
</asp:SqlDataSource>

Hope this helps

16

AutocompleteExtender Textbox Loading Progress Image

Add or show Animated Loading or progress GIF Image in Ajax AutoCompleteExtender textbox using asp.net 2.0 and 3.5.

In this example i m going to describe how to add animated Progress Image inside Ajax Auto complete extender textbox to represent loading of data.

For achieving this functionality i am using two different approaches for different versions of AjaxControlToolkit.dll



If you are looking for how to implement AutoComplete textbox than read
Ajax autocomplete extender textbox in EditItemTemaplate of GridView
If you are looking for ajax cascading dropdownlist then read
Ajax Cascading DropDownList in GridView with databse in ASP.NET


1st Approach

This approach is very simple and can be handy if you are using older/earlier version of AjaxControlToolkit (eg versions like 1.0.10201.0) which does not support css properties or properties like onclientpopulating.
For this write the below mentioned javascript in head section of html markup of the aspx page

<script type="text/javascript">
function ShowImage()
{
 document.getElementById('txtAutoComplete')
      .style.backgroundImage  = 'url(images/loader.gif)';
 
 document.getElementById('txtAutoComplete')
                    .style.backgroundRepeat= 'no-repeat';
                    
 document.getElementById('txtAutoComplete')
                    .style.backgroundPosition = 'right';
}
function HideImage()
{
 document.getElementById('txtAutoComplete')
                      .style.backgroundImage  = 'none';
} 
</script>

In this script I've written two function to show and hide image, in the functions i m setting the background image style using document.getElementByID method

Now write this code in Page_Load event of aspx page
protected void Page_Load(object sender, EventArgs e)
{
 this.txtAutoComplete.Attributes.Add
                          ("onkeypress", "ShowImage()");
 this.txtAutoComplete.Attributes.Add
                              ("onblur", "HideImage()");
}
Here i've added onblur and onkeypress attributes to textbox and calling respective function of javascript to show hide image.
Build the solution and run ti see the results

2nd approach

This approach works if you are using newer versions of AjaxControlToolkit.dll (Version 1.0.20229.20821 or later)
For this write the above mentioned javascript in head section of html markup of page.
Now in source of autocomplete extender add onclientpopulating="ShowImage" and onclientpopulated="HideImage"
<ajaxToolkit:AutoCompleteExtender runat="server" 
                ID="AutoComplete1"
                BehaviorID="autoComplete"
                TargetControlID="txtAutoComplete"
                ServicePath="AutoComplete.asmx" 
                ServiceMethod="GetCompletionList"
                MinimumPrefixLength="1" 
                CompletionInterval="10"
                EnableCaching="true"
                CompletionSetCount="12"
                CompletionListCssClass=
                "autocomplete_completionListElement"
                CompletionListItemCssClass=
                "autocomplete_listItem"
                CompletionListHighlightedItemCssClass=
                "autocomplete_highlightedListItem"
                onclientpopulating="ShowImage"
                onclientpopulated="HideImage">
           </ajaxToolkit:AutoCompleteExtender>

Complete html source of the page look like
<head runat="server">
<title>Progress Image in AutoComplete TextBox</title>

<script type="text/javascript">
function ShowImage()
{
 document.getElementById('txtAutoComplete')
      .style.backgroundImage  = 'url(images/loader.gif)';
 
 document.getElementById('txtAutoComplete')
                    .style.backgroundRepeat= 'no-repeat';
                    
 document.getElementById('txtAutoComplete')
                    .style.backgroundPosition = 'right';
}
function HideImage()
{
 document.getElementById('txtAutoComplete')
                      .style.backgroundImage  = 'none';
} 
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
</Services>
</asp:ScriptManager>
<br />
<div>
<asp:TextBox ID="txtAutoComplete" runat="server" Width="252px">
</asp:TextBox><br />
<ajaxToolkit:AutoCompleteExtender runat="server" 
                ID="AutoComplete1"
                BehaviorID="autoComplete"
                TargetControlID="txtAutoComplete"
                ServicePath="AutoComplete.asmx" 
                ServiceMethod="GetCompletionList"
                MinimumPrefixLength="1" 
                CompletionInterval="10"
                EnableCaching="true"
                CompletionSetCount="12"
                CompletionListCssClass=
                "autocomplete_completionListElement"
                CompletionListItemCssClass=
                "autocomplete_listItem"
                CompletionListHighlightedItemCssClass=
                "autocomplete_highlightedListItem"
                onclientpopulating="ShowImage"
                onclientpopulated="HideImage">
           </ajaxToolkit:AutoCompleteExtender>
           </div>
    </form>

Hope this helps

12

Add Dynamic CheckBox Handle CheckedChanged Event ASP.NET

Add Dynamic CheckBox And Handle CheckedChanged Event In ASP.NET 2.0,3.5,4.0 Using C# And VB.NET. Several times we need to add dynamic controls in asp.net application using code behind.

In this post i am going to describe how to add dynamic CheckBox and assign CheckChanged event in asp.net using C# and VB.NET


To add a checkbox when page is loaded we need to write this code in page_Load Event

C# Code Behind

public partial class _Default : System.Web.UI.Page 
{
    CheckBox chkDynamic;
    protected void Page_Load(object sender, EventArgs e)
    {
        chkDynamic = new CheckBox();
        chkDynamic.ID = "chkExample";
        chkDynamic.Text = "Check / Uncheck";
        chkDynamic.AutoPostBack = true;
        chkDynamic.CheckedChanged += new EventHandler
                           (chkDynamic_CheckedChanged);
        this.Form.Controls.Add(chkDynamic);
    }

    protected void chkDynamic_CheckedChanged
                 (object sender, EventArgs e)
    {
        if (chkDynamic.Checked)
            lblMessage.Text = "you checked the checkbox";
        else if (!chkDynamic.Checked)
            lblMessage.Text = "checkbox is not checked";
    }
}

VB.NET Code Behind
Public Partial Class _Default
    Inherits System.Web.UI.Page
    Private chkDynamic As CheckBox
    Protected Sub Page_Load
    (ByVal sender As Object, ByVal e As EventArgs)
        chkDynamic = New CheckBox()
        chkDynamic.ID = "chkExample"
        chkDynamic.Text = "Check / Uncheck"
        chkDynamic.AutoPostBack = True
        AddHandler chkDynamic.CheckedChanged, 
         AddressOf chkDynamic_CheckedChanged
        Me.Form.Controls.Add(chkDynamic)
    End Sub
    
    Protected Sub chkDynamic_CheckedChanged
    (ByVal sender As Object, ByVal e As EventArgs)
        If chkDynamic.Checked Then
            lblMessage.Text = "you checked the checkbox"
        ElseIf Not chkDynamic.Checked Then
            lblMessage.Text = "checkbox is not checked"
        End If
    End Sub
End Class

Hope this helps

Read other articles on checkboxes:
Edit or update multiple records/rows in gridview with checkbox
Delete multiple rows records in Gridview with checkbox and confirmation

216

Shopping Cart Example Code In ASP.NET C# VB.NET GridView

Creating Shopping Cart Example Code In Asp.Net 2.0,3.5,40 With Gridview C#.NET,VB.NET. I'm using GridView and DataList controls to create Products page and Product Details page in online shopping cart example

Create Shopping Cart Example In Asp.Net With GridView


First of all we need to create a ShoppingCart class, for this right click on solution explorer and add new class, name it ShoppingCart.cs
Write this code in ShoppingCart.cs class

namespace ShoppingCartExample
{
    /// <summary>
    /// Summary description for ShoppingCart
    /// </summary>
    [Serializable] 
    public class CartItem
    {
        private int _productID;
        private string _productName;
        private string _imageUrl;
        private int _quantity;
        private double _price;
        private double _subTotal;

        public CartItem()
        { 
        }
        public CartItem(int ProductID, string ProductName, 
              string ImageUrl, int Quantity, double Price)
        {
            _productID = ProductID;
            _productName = ProductName;
            _imageUrl = ImageUrl;
            _quantity = Quantity;
            _price = Price;
           _subTotal = Quantity * Price;
        }
        public int ProductID
        {
            get
            {
                return _productID;
            }
            set
            {
                _productID = value;
            }
        }
         public string ProductName
         {
            get { return _productName; }
            set { _productName = value; }
         }
         public string ImageUrl
         {
             get { return _imageUrl; }
             set { _imageUrl = value; }
         }

         public int Quantity
         {
             get { return _quantity; }
             set { _quantity = value; }
         }

         public double Price
         {
             get { return _price; }
             set { _price = value; }
         }

         public double SubTotal
         {
             get { return _quantity * _price; }
            
         }
    }
    [Serializable]
    public class Cart
    {
        private DateTime _dateCreated;
        private DateTime _lastUpdate;
        private List<CartItem> _items;

        public Cart()
        {
            if (this._items == null)
            {
                this._items = new List<CartItem>();
                this._dateCreated = DateTime.Now;
            }
        }

        public List<CartItem> Items
        {
         get { return _items;}
        set { _items = value;}
        }

        public void Insert(int ProductID, double Price, 
        int Quantity, string ProductName, string ImageUrl)
        {
            int ItemIndex = ItemIndexOfID(ProductID);
            if (ItemIndex == -1)
            {
                CartItem NewItem = new CartItem();
                NewItem.ProductID = ProductID;
                NewItem.Quantity = Quantity;
                NewItem.Price = Price;
                NewItem.ProductName = ProductName;
                NewItem.ImageUrl = ImageUrl;
                _items.Add(NewItem);
            }
            else
            {
                _items[ItemIndex].Quantity += 1;
            }
            _lastUpdate = DateTime.Now;
        }

        public void Update(int RowID, int ProductID, 
                         int Quantity, double Price)
        {
            CartItem Item = _items[RowID];
            Item.ProductID = ProductID;
            Item.Quantity = Quantity;
            Item.Price = Price;
            _lastUpdate = DateTime.Now;
        }

        public void DeleteItem(int rowID)
        {
            _items.RemoveAt(rowID);
            _lastUpdate = DateTime.Now;
        }

        private int ItemIndexOfID(int ProductID)
        {
            int index = 0;
            foreach (CartItem item in _items)
            {
                if (item.ProductID == ProductID)
                {
                    return index;
                }
                index += 1;
            }
            return -1;
        }

        public double Total
        {
            get
            {
                double t = 0;
                if (_items == null)
                {
                    return 0;
                }
                foreach (CartItem Item in _items)
                {
                    t += Item.SubTotal;
                }
                return t;
            }
        }
 
    }
}

Now to create Products page, add a new webform and name it Products.aspx, add sqldataSource and configure it for select statement,
read this for how to configure SqlDataSource
Add a DataList Control on the page and make SqlDataSource1 it's source.
Configure Datalist according to below mentioned source
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ProductID], [Name], [Description], 
               [Price], [ImageUrl] FROM [Products]">
</asp:SqlDataSource>
</div>

<asp:DataList ID="DataList1" runat="server" 
              DataSourceID="SqlDataSource1" 
              RepeatColumns="4"
              RepeatDirection="Horizontal">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" 
ImageUrl='<%# Eval("ImageUrl", "Images\\thumb_{0}") %>' 
PostBackUrl='<%# Eval("ProductID", 
"ProductDetails.aspx?ProductID={0}") %>' />
<br />
<asp:Label ID="NameLabel" runat="server" 
           Text='<%# Eval("Name") %>'>
</asp:Label>
<asp:Label ID="PriceLabel" runat="server" 
           Text='<%# Eval("Price", "{0:C}") %>'>
</asp:Label><br />
<br />
<br />
</ItemTemplate>
</asp:DataList><br />
<asp:HyperLink ID="CartLink" runat="server" 
               NavigateUrl="~/UserCart.aspx">
               View Shopping Cart
</asp:HyperLink><br />
</form>

Now add a new webform and name it ProductDetails.aspx , this page is used for showing details for selected product from product catalog page, again add a SqlDataSource and DataList Control on this page and configure them according to source shown below, this time datalist is populated using QueryString Parameters.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ProductID], [Name], [Description], 
               [Price], [ImageUrl] FROM [Products] 
               WHERE ([ProductID] = @ProductID)">
    <SelectParameters>
    <asp:QueryStringParameter Name="ProductID" 
                              QueryStringField="ProductID" 
                              Type="Decimal" />
    </SelectParameters>
</asp:SqlDataSource>
</div>

<asp:DataList ID="DataList1" runat="server" 
              DataSourceID="SqlDataSource1">
<ItemTemplate>
  <asp:Image ID="Image1" runat="server" 
       ImageUrl='<%# Eval("ImageUrl","~/Images\\{0}") %>'/>
  <asp:Label ID="ImageUrlLabel" runat="server" 
             Text='<%# Eval("ImageUrl") %>' 
             Visible="False">
  </asp:Label><br />
  <asp:Label ID="NameLabel" runat="server" 
             Text='<%# Eval("Name") %>'>
  </asp:Label><br />
  <asp:Label ID="DescriptionLabel" runat="server" 
             Text='<%# Eval("Description") %>'>
  </asp:Label><br />
  <asp:Label ID="PriceLabel" runat="server" 
             Text='<%# Eval("Price", "{0:##0.00}" ) %>'>
  </asp:Label><br />
</ItemTemplate>
</asp:DataList><br />
<asp:Button ID="btnAdd" runat="server" OnClick="Button1_Click" 
                        Text="Add to Cart" /><br /><br />
<asp:HyperLink ID="HyperLink1" runat="server" 
               NavigateUrl="~/Products.aspx">
               Return to Products Page
</asp:HyperLink>
Write this code in C# code behind of ProductDetails.aspx page
protected void Button1_Click(object sender, EventArgs e)
{
  double Price = double.Parse(((Label)
    DataList1.Controls[0].FindControl("PriceLabel")).Text);
  string ProductName = ((Label)
    DataList1.Controls[0].FindControl("NameLabel")).Text;
  string ProductImageUrl = ((Label)
   DataList1.Controls[0].FindControl("ImageUrlLabel")).Text;
int ProductID = int.Parse(Request.QueryString["ProductID"]);
if (Profile.SCart == null)
{
  Profile.SCart = new ShoppingCartExample.Cart();
}
  Profile.SCart.Insert
      (ProductID, Price, 1, ProductName, ProductImageUrl);
  Server.Transfer("Products.aspx");
}

Now right click on solution explorer and add new web user control, name it CartControl.ascx
In design view of this control add a new GridView control and a label below gridview, html shource of this control should look like this
<%@ Control Language="C#" AutoEventWireup="true" 
            CodeFile="CartControl.ascx.cs" 
            Inherits="CartControl" %>
<asp:GridView ID="grdCart" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ProductID" 
              OnRowCancelingEdit="grdCart_RowCancelingEdit" 
              OnRowDeleting="grdCart_RowDeleting" 
              OnRowEditing="grdCart_RowEditing" 
              OnRowUpdating="grdCart_RowUpdating">
<Columns>
<asp:TemplateField>
    <ItemTemplate>
    <asp:Image ID="Image1" runat="server" 
    ImageUrl='<%#Eval("ImageUrl","~/Images/thumb_{0}")%>'/>
    </ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductName" 
                HeaderText="Product" ReadOnly="True"/>
<asp:BoundField DataField="Quantity" HeaderText="Quantity"/>
<asp:BoundField DataField="Price" DataFormatString="{0:c}" 
                HeaderText="Price" ReadOnly="True" />
<asp:BoundField DataField="SubTotal" DataFormatString="{0:c}" 
                HeaderText="Total" ReadOnly="True" />
<asp:CommandField ShowDeleteButton="True" 
                  ShowEditButton="True"/>
</Columns>
<EmptyDataTemplate>
Your Shopping Cart is empty, add items
<a href="Products.aspx">Add Products</a>
</EmptyDataTemplate>
</asp:GridView>
<asp:Label ID="TotalLabel" runat="server"></asp:Label>

Open web.config file and add this section for enabling anonymous users to add items to cart

<system.web>
  <authorization>
   <allow users="?" />
   <allow roles="admin" />
  </authorization>
  <roleManager enabled="true" />
  <authentication mode="Forms" />
          <compilation debug="true">
            </compilation>
        </system.web>
  <system.web>
    <anonymousIdentification enabled="true"/>
    <profile enabled="true">
      <properties>
       <add name="SCart" serializeAs="Binary" 
            type="ShoppingCartExample.Cart" 
            allowAnonymous="true"/>
      </properties>
    </profile>
  </system.web>

Now go to code behnd of CartControl.ascx and write this code
protected void Page_Load(object sender, EventArgs e)
    {
        if (Profile.SCart == null)
        {
            Profile.SCart = new ShoppingCartExample.Cart();
        }
        if (!Page.IsPostBack)
        {
            ReBindGrid();
        }
        if(Profile.SCart.Items == null)
        {
            TotalLabel.Visible = false;
        }
    }
    protected void grdCart_RowEditing
                 (object sender, GridViewEditEventArgs e)
    {
        grdCart.EditIndex = e.NewEditIndex;
        ReBindGrid();
    }
    protected void grdCart_RowUpdating
               (object sender, GridViewUpdateEventArgs e)
    {
        TextBox txtQuantity = (TextBox)
        grdCart.Rows[e.RowIndex].Cells[2].Controls[0];
        int Quantity = Convert.ToInt32(txtQuantity.Text);
        if (Quantity == 0)
        {
            Profile.SCart.Items.RemoveAt(e.RowIndex);
        }
        else
        {
            Profile.SCart.Items[e.RowIndex].Quantity 
                                         = Quantity;
        }
        grdCart.EditIndex = -1;
        ReBindGrid();
    }
    protected void grdCart_RowCancelingEdit
             (object sender, GridViewCancelEditEventArgs e)
    {
        grdCart.EditIndex = -1;
        ReBindGrid();
    }
    protected void grdCart_RowDeleting
                 (object sender, GridViewDeleteEventArgs e)
    {
        Profile.SCart.Items.RemoveAt(e.RowIndex);
        ReBindGrid();
    }
    private void ReBindGrid()
    {
        grdCart.DataSource = Profile.SCart.Items;
        DataBind();
        TotalLabel.Text = string.Format("Total:{0,19:C}", 
                                     Profile.SCart.Total);
    }

Now add Global Application Class (Global.asax) by right clicking on solution explorer > add new Item. and write code mentioned below in it.
void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs e)
    {
        ProfileCommon anonymousProfile = Profile.GetProfile(e.AnonymousID);
        if (anonymousProfile.SCart != null)
        {
            if (Profile.SCart == null)
                Profile.SCart = new ShoppingCartExample.Cart();

            Profile.SCart.Items.AddRange(anonymousProfile.SCart.Items);

            anonymousProfile.SCart = null;
        }

        ProfileManager.DeleteProfile(e.AnonymousID);
        AnonymousIdentificationModule.ClearAnonymousIdentifier();
    }
       


Add another webform and name it UserCart.aspx, in design view of this page drag the CartControl we've just created and put a hyperlink for going back to products cataloge page

Tha's it , build and run the application
Have fun

Download the sample code attached



59

Insert Update Edit Delete Rows Record In GridView

In this example i am explaining how to Insert Update Edit Delete Records Rows In GridView With SqlDataSource Using C# VB.NET Asp.Net using SqlDataSource.

For inserting record, i've put textboxes in footer row of GridView using ItemTemplate and FooterTemaplete.


Go to design view of aspx page and drag a GridView control from toolbox, click on smart tag of GridView and choose new datasource
Select Database and click Ok
 
In next screen, Enter your SqlServer name , username and password and pick Database name from the dropdown , Test the connection
 
 
 In next screen, select the table name and fields , Click on Advance tab and check Generate Insert,Edit and Delete statements checkbox , alternatively you can specify your custom sql statements 
 
 
Click on ok to finish 
Check Enable Editing , enable deleting checkbox in gridView smart tag 
Now go to html source of page and define DatakeyNames field in gridview source
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
</asp:GridView>
Remove the boundFields and put ItemTemplate and EditItemTemplate and labels and textboxs respectively, complete html source of page should look like this
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
<Columns>
    <asp:CommandField ShowDeleteButton="True" 
                      ShowEditButton="True" />
    <asp:TemplateField HeaderText="ID" SortExpression="ID">
    <ItemTemplate>
    <asp:Label ID="lblID" runat="server" 
                          Text='<%#Eval("ID") %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:Button ID="btnInsert" runat="server" 
                Text="Insert" CommandName="Add" />
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="FirstName" 
                       SortExpression="FirstName">
    <ItemTemplate>
    <asp:Label ID="lblFirstName" runat="server" 
               Text='<%#Eval("FirstName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtFirstName" runat="server" 
                 Text='<%#Bind("FirstName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtFname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="LastName" 
                       SortExpression="LastName">
    <ItemTemplate>
    <asp:Label ID="lblLastName" runat="server" 
               Text='<%#Eval("LastName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtLastName" runat="server" 
                 Text='<%#Bind("LastName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtLname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Department" 
                       SortExpression="Department">
    <ItemTemplate>
    <asp:Label ID="lblDepartment" runat="server" 
               Text='<%#Eval("Department") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtDepartmentName" runat="server" 
                 Text='<%#Bind("Department") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtDept" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Location" 
                       SortExpression="Location">
    <ItemTemplate>
    <asp:Label ID="lblLocation" runat="server" 
               Text='<%#Eval("Location") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtLocation" runat="server" 
                 Text='<%#Bind("Location") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtLoc" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:DBConString%>"
DeleteCommand="DELETE FROM [Employees] WHERE [ID] = @ID" 
InsertCommand="INSERT INTO [Employees] ([FirstName], 
[LastName],[Department], [Location]) 
VALUES (@FirstName, @LastName, @Department, @Location)"
SelectCommand="SELECT [ID], [FirstName], [LastName], 
[Department], [Location] FROM [Employees]"
UpdateCommand="UPDATE [Employees] SET 
[FirstName] = @FirstName, [LastName] = @LastName, 
[Department] = @Department, [Location] = @Location 
WHERE [ID] = @ID" OnInserted="SqlDataSource1_Inserted">

<DeleteParameters>
    <asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
    <asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
<asp:Label ID="lblMessage" runat="server" 
           Font-Bold="True"></asp:Label><br />
</div>
</form>
Write this code in RowCommand Event of GridView in codebehind
C# code Behind
protected void GridView1_RowCommand
(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Add")
  {
   string strFirstName = ((TextBox)
   GridView1.FooterRow.FindControl("txtFname")).Text;

   string strLastName = 
   ((TextBox)GridView1.FooterRow.FindControl
                         ("txtLname")).Text;

   string strDepartment = 
   ((TextBox)GridView1.FooterRow.FindControl
                            ("txtDept")).Text;
   string strLocation = ((TextBox)GridView1.FooterRow.
                          FindControl("txtLoc")).Text;
   //SqlDataSource1.InsertParameters.Clear();
   //SqlDataSource1.InsertParameters.Add
                       //("FirstName", strFirstName);
   //SqlDataSource1.InsertParameters.Add
                          //("LastName", strLastName);
   //SqlDataSource1.InsertParameters.Add
                         //("Department", strDepartment);
   //SqlDataSource1.InsertParameters.Add
                              //("Location", strLocation);

  SqlDataSource1.InsertParameters["FirstName"].DefaultValue 
                                             = strFirstName;
  SqlDataSource1.InsertParameters["LastName"].DefaultValue 
                                             = strLastName;
  SqlDataSource1.InsertParameters["Department"].DefaultValue 
                                             = strDepartment;
  SqlDataSource1.InsertParameters["Location"].DefaultValue
                                            = strLocation;
  SqlDataSource1.Insert();
  }
}

VB.NET Code Behind

Protected Sub GridView1_RowCommand(ByVal sender As Object, 
                       ByVal e As GridViewCommandEventArgs)
        If e.CommandName = "Add" Then
            Dim strFirstName As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtFname"), TextBox).Text()

            Dim strLastName As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtLname"), TextBox).Text()

            Dim strDepartment As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtDept"), TextBox).Text()
            Dim strLocation As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtLoc"), TextBox).Text()

            'SqlDataSource1.InsertParameters.Clear();
            'SqlDataSource1.InsertParameters.Add
            '("FirstName", strFirstName);
            'SqlDataSource1.InsertParameters.Add
            '("LastName", strLastName);
            'SqlDataSource1.InsertParameters.Add
            '("Department", strDepartment);
            'SqlDataSource1.InsertParameters.Add
            '("Location", strLocation);

            SqlDataSource1.InsertParameters("FirstName").
            DefaultValue = strFirstName
            SqlDataSource1.InsertParameters("LastName").
            DefaultValue = strLastName
            SqlDataSource1.InsertParameters("Department").
            DefaultValue = strDepartment
            SqlDataSource1.InsertParameters("Location").
            DefaultValue = strLocation
            SqlDataSource1.Insert()
        End If
    End Sub


Download the sample code attached


You would also like to read
Edit or update multiple records/rows in gridview with checkbox using C# in ASP.NET

Delete multiple rows records in Gridview with checkbox and confirmation in ASP.NET

57

Edit Update Delete Multiple Records/Rows Gridview With Checkbox

In this example i am going to how to Edit update delete multiple records or rows in Gridview with checkboxe to select rows to be edited with delete confirmation using JavaScript.

In my previous post i explained how to Delete multiple rows in Gridview with checkbox and delete confirmation Javascript

Edit Update Multiple Records/Rows In Gridview With Checkbox ASP.NET


First Method


In this GridView is getting populated from database using SqlDataSource, I've put checkbox in first column of gridview using ItemTemplate and textbox in ItemTemplate to display records

Html SOURCE
<asp:GridView ID="GridView1" runat="server" 
                             AllowPaging="True" 
                             DataSourceID="SqlDataSource1" 
                             AutoGenerateColumns="false">
<Columns>
    <asp:TemplateField HeaderText="Select">
    <ItemTemplate>
    <asp:CheckBox ID="chkSelect" runat="server" 
                  AutoPostBack="true" 
             OnCheckedChanged="chkSelect_CheckedChanged"/>
    </ItemTemplate>
    
    </asp:TemplateField>
    <asp:BoundField DataField="ID" HeaderText="ID" 
                                   SortExpression="ID"/>
                                   
    <asp:TemplateField HeaderText="Name" 
                       SortExpression="Name">
    <ItemTemplate>
    <asp:TextBox ID="txtName" runat="server" 
                 Text='<%# Bind("Name") %>' ReadOnly="true" 
                 ForeColor="Blue" BorderStyle="none" 
                 BorderWidth="0px" >
    </asp:TextBox>
    </ItemTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Location" 
                       SortExpression="Location">
    <ItemTemplate>
    <asp:TextBox ID="txtLocation" runat="server" 
                 Text='<%# Bind("Location") %>' 
                 ReadOnly="true" ForeColor="Blue" 
                 BorderStyle="none" BorderWidth="0px">
    </asp:TextBox>
    </ItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]" 
DeleteCommand="DELETE FROM Details WHERE (ID = @ID)" 
UpdateCommand="UPDATE [Details] SET [Name] = @Name, 
              [Location] = @Location WHERE [ID] = @ID">
        <DeleteParameters>
             <asp:Parameter Name="ID" />
        </DeleteParameters>
        <UpdateParameters>
                <asp:Parameter Name="Name" />
                <asp:Parameter Name="Location" />
                <asp:Parameter Name="ID" />
        </UpdateParameters>
        </asp:SqlDataSource><br />
        
<asp:Button ID="btnUpdate" runat="server" 
            OnClick="btnUpdate_Click" Text="Update" /><br />
            
<asp:Button ID="btnDelete" runat="server" 
            OnClick="btnDelete_Click" 
            OnClientClick="return DeleteConfirmation();"  
            Text="Delete" />

For Delete Confirmation write this JavaScript in head section of page . This script is called by delete button by specifying OnClientClick attribute in html code of button
<script type="text/javascript" language="javascript">
function DeleteConfirmation()
{
 if (confirm("Are you sure, 
     you want to delete selected records ?")==true)
 return true;
 else
 return false;
}
</script>
In the code behnd i've created a StringBuilder to store update commands separated by ; for records to be edited. than looping through gridview rows to find checked rows, then find the value in textbox using findControl.

C# CODE
public partial class _Default : System.Web.UI.Page 
{
 //Define global Connection String
string strConnection=ConfigurationManager.ConnectionStrings
                    ["ConnectionString"].ConnectionString;
    
protected void btnUpdate_Click(object sender, EventArgs e)
{
 //Create stringbuilder to store multiple DML statements 
 StringBuilder strSql = new StringBuilder(string.Empty);

 //Create sql connection and command
 SqlConnection con = new SqlConnection(strConnection);
 SqlCommand cmd = new SqlCommand();

//Loop through gridview rows to find checkbox 
//and check whether it is checked or not 
 for (int i = 0; i < GridView1.Rows.Count; i++)
 {
   CheckBox chkUpdate = (CheckBox)
      GridView1.Rows[i].Cells[0].FindControl("chkSelect");
   if (chkUpdate != null)
   {
    if (chkUpdate.Checked)
     {
    // Get the values of textboxes using findControl
     string strID = GridView1.Rows[i].Cells[1].Text;
     string strName = ((TextBox)
         GridView1.Rows[i].FindControl("txtName")).Text;

     string strLocation = ((TextBox)
         GridView1.Rows[i].FindControl("txtLocation")).Text;

     string strUpdate = 
         "Update Details set Name = '" + strName + "'," + 
         + " Location = '" + strLocation + "'" + 
         + " WHERE ID ='" + strID +"'" +";" ;
    //append update statement in stringBuilder 
     strSql.Append(strUpdate);
      }
   }
 }
   try
     {
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = strSql.ToString();
      cmd.Connection = con;
      con.Open();
      cmd.ExecuteNonQuery();
     }
   catch (SqlException ex)
     {
       string errorMsg = "Error in Updation";
       errorMsg += ex.Message;
       throw new Exception(errorMsg);
     }
   finally
     {
       con.Close();
     }
   UncheckAll();
      
}

This will update all records by connection to database only one time But this method is not considered good as it is vulnerable to sql injection so we can use Sql parameters instead

try
{
  string strUpdate = "Update Details set Name = @Name,"+ 
                   +" Location = @Location WHERE ID = @ID";
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = strUpdate.ToString();
  cmd.Parameters.Clear();
  cmd.Parameters.AddWithValue("@Name", strName);
  cmd.Parameters.AddWithValue("@Location", strLocation);
  cmd.Parameters.AddWithValue("@ID", strID);
  cmd.Connection = con;
  con.Open();
  cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
  string errorMsg = "Error in Updation";
  errorMsg += ex.Message;
  throw new Exception(errorMsg);
}
finally
{
   con.Close();
}
For deleting selected records at once write this code in click event of Delete button
protected void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store IDs of 
//records to be deleted 
StringCollection idCollection = new StringCollection();
string strID = string.Empty;

//Loop through GridView rows to find checked rows 
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
       CheckBox chkDelete = (CheckBox)GridView1.Rows[i].
                        Cells[0].FindControl("chkSelect");
            if (chkDelete != null)
            {
              if (chkDelete.Checked)
              {
               strID = GridView1.Rows[i].Cells[1].Text;
               idCollection.Add(strID);
              }
            }
        }
        if (idCollection.Count > 0)
        {
            //Call the method to Delete records 
            DeleteMultipleRecords(idCollection);

            // rebind the GridView
            GridView1.DataBind();   
        }
        else
        {
         lblMessage.Text = "Please select any row to delete";
        }
        
    }
private void DeleteMultipleRecords(StringCollection idCollection)
{
 //Create sql Connection and Sql Command
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
string IDs = "";

    foreach (string id in idCollection)
    {
      IDs += id.ToString() + ",";
    }

    try
    {
     string test = IDs.Substring
                   (0, IDs.LastIndexOf(","));
     string sql = "Delete from Details"+ 
                  +" WHERE ID in (" + test + ")";
     cmd.CommandType = CommandType.Text;
     cmd.CommandText = sql;
     cmd.Connection = con;
     con.Open();
     cmd.ExecuteNonQuery();
    }
    catch (SqlException ex)
    {
     string errorMsg = "Error in Deletion";
     errorMsg += ex.Message;
     throw new Exception(errorMsg);
    }
    finally
    {
      con.Close();
    }
    }
Write this code in the CheckedChanged Event of CheckBox
protected void chkSelect_CheckedChanged
                            (object sender, EventArgs e)
    {
      CheckBox chkTest = (CheckBox)sender;
      GridViewRow grdRow = (GridViewRow)chkTest.NamingContainer;
      TextBox txtname = (TextBox)grdRow.FindControl
                                          ("txtName");
      TextBox txtlocation = (TextBox)grdRow.FindControl
                                        ("txtLocation");
      if (chkTest.Checked)
        {
            txtname.ReadOnly = false;
            txtlocation.ReadOnly = false;
            txtname.ForeColor = System.Drawing.Color.Black;
            txtlocation.ForeColor = System.Drawing.Color.Black;
        }
        else
        {
            txtname.ReadOnly = true;
            txtlocation.ReadOnly = true;
            txtname.ForeColor = System.Drawing.Color.Blue;
            txtlocation.ForeColor = System.Drawing.Color.Blue;
         }
    }
private void UncheckAll()
{
  foreach (GridViewRow row in GridView1.Rows)
  {
   CheckBox chkUncheck = (CheckBox)
                row.FindControl("chkSelect");
   TextBox txtname = (TextBox)
                  row.FindControl("txtName");
   TextBox txtlocation = (TextBox)
              row.FindControl("txtLocation");
   chkUncheck.Checked = false;
   txtname.ReadOnly = true;
   txtlocation.ReadOnly = true;
   txtname.ForeColor = System.Drawing.Color.Blue;
   txtlocation.ForeColor = System.Drawing.Color.Blue;
  }
}

Second Method:
This is better described here
public partial class _Default : System.Web.UI.Page 
{
    //Define global Connection String
string strConnection = ConfigurationManager.ConnectionStrings
                      ["ConnectionString"].ConnectionString;
     
    private bool tableCopied = false;
    private DataTable originalTable;

    protected void GridView1_RowDataBound
                  (object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (!tableCopied)
            {
                originalTable = ((System.Data.DataRowView)
                         e.Row.DataItem).Row.Table.Copy();
                ViewState["originalValues"] = originalTable;
                tableCopied = true;
            }
        }
    }
  protected void btnUpdate_Click(object sender, EventArgs e)
  {
   originalTable = (DataTable)ViewState["originalValues"];
   foreach (GridViewRow row in GridView1.Rows)
        if(IsRowModified(row))
        {
            GridView1.UpdateRow(row.RowIndex,false);
        }
        tableCopied = false;
        GridView1.DataBind();
    }

    protected bool IsRowModified(GridViewRow row)
    {
        int currentID;
        string currentName;
        string currentLocation;

        currentID = Convert.ToInt32(GridView1.DataKeys
                                [row.RowIndex].Value);

        currentName = ((TextBox)row.FindControl
                                      ("txtName")).Text;
        currentLocation = ((TextBox)row.FindControl
                                  ("txtLocation")).Text;

        System.Data.DataRow newRow = originalTable.Select
                (String.Format("ID = {0}", currentID))[0];

    if (!currentName.Equals(newRow["Name"].ToString())) 
    { return true; }
    if (!currentLocation.Equals(newRow["Location"].ToString())) 
    { return true; }

    return false;

    }
For records deletion
protected void btnDelete_Click(object sender, EventArgs e)
{
 originalTable = (DataTable)ViewState["originalValues"];
 foreach (GridViewRow row in GridView1.Rows)
   {
    CheckBox chkDelete = (CheckBox)row.FindControl
                                        ("chkSelect");
    if(chkDelete.Checked)
      {
      GridView1.DeleteRow(row.RowIndex);
      }
   }
       tableCopied = false;
       GridView1.DataBind();
}

Download the sample code attached



Other Posts:
1. Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate
2. Data Transfer using Query String Session cookies and cross page posting
3. Data Transfer Using Cookies Session Variables Cross page posting and QueryStrings in ASP.NET
4. Cross page posting, Submit Form and Server.Transfer methods
5. Pouplating Multiple DetailsView based on single GridView using DataKeyNames

Find More Articles