Sunday, January 17, 2010

DropDownList RadioButtonList CheckBox CheckBoxList in GridView Edit Mode in Asp.Net




Please visit my new Web Site https://coderstechzone.com



Most of the Asp.net (C# or VB.Net) developers faced a problem when they want to implement edit functionality within a GridView. The problem was developers can not understand how to populate DropDownList RadioButtonList CheckBox CheckBoxList in GridView Edit Mode. The another problem is after populating how to display or show current database value by default in DropDownList RadioButtonList CheckBox CheckBoxList controls in edit mode. In this example i will give you the below solutions:

1. How to populate DropDownList while loading gridview.
2. How to set current database value as primarily selected value in DropDownList.
3. How to populate RadioButtonList while loading gridview.
4. How to set current database value as primarily selected value in RadioButtonList.
5. How to populate CheckBox while loading gridview.
6. How to set current database value as primarily selected value in CheckBox.
7. How to populate CheckBoxList while loading gridview.
8. How to set current database value as primarily selected value in CheckBoxList.

SO lets go to describe how to implement DropDownList RadioButtonList CheckBox CheckBoxList in Edit mode of GridVIew using EditItemTemaplate in ASP.NET C#. DropDownList RadioButtonList CheckBox CheckBoxList were selected in edit mode based on value saved in your SQL Server DataBase.

The output will be like this:


To do that i have followed the below table structure:


Now add a page in your project & copy the below HTML Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Edit.aspx.cs" Inherits="GridView_Edit" %>

<!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>Radobutton Dropdownlist in GridView Edit Mode</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" DataKeyNames="ID"  Width="100%"
            AutoGenerateColumns="False" DataSourceID="SqlDataSource1" 
            onrowdatabound="GridView1_RowDataBound" onrowupdating="GridView1_RowUpdating">
        <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
        <RowStyle BackColor="Gray" />
        <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
             <asp:BoundField DataField="Description" HeaderText="Description" />
             <asp:BoundField DataField="Color" HeaderText="Color" />
             
             <asp:TemplateField HeaderText="Size">
             <ItemTemplate>
             <asp:Label ID="lblSize" runat="server" Text='<%#Eval("Size") %>'>
             </asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:DropDownList ID="cboSize" runat="server">
             <asp:ListItem>Family</asp:ListItem>
             <asp:ListItem>Regular</asp:ListItem>
             <asp:ListItem>Standard</asp:ListItem>
             </asp:DropDownList>
             </EditItemTemplate>
             </asp:TemplateField>
             
             <asp:TemplateField HeaderText="Is Kit?">
             <ItemTemplate>
             <asp:Label ID="lblIsKit" runat="server" Text='<%#Eval("IsKit") %>'></asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:RadioButtonList ID="rdoIsKit" runat="server">
             <asp:ListItem>Product</asp:ListItem>
             <asp:ListItem>Kit</asp:ListItem>
             </asp:RadioButtonList>
             </EditItemTemplate>
             </asp:TemplateField>
             
             <asp:TemplateField HeaderText="Active?">
             <ItemTemplate>
             <asp:Label ID="lblActive" runat="server" Text='<%#Eval("Active") %>'></asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:CheckBox ID="chkActive" runat="server" Text="Active" />
             </EditItemTemplate>
             </asp:TemplateField>

             <asp:TemplateField HeaderText="Vendor Name">
             <ItemTemplate>
             <asp:Label ID="lblVendor" runat="server" Text='<%#Eval("Vendor_Name") %>'></asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:CheckBoxList ID="chkVendors" runat="server">
             <asp:ListItem>Sonali Traders</asp:ListItem>
             <asp:ListItem>Linkers</asp:ListItem>
             <asp:ListItem>Asma Associates</asp:ListItem>
             <asp:ListItem>Chameli Traders</asp:ListItem>
             </asp:CheckBoxList>
             </EditItemTemplate>
             </asp:TemplateField>

             <asp:CommandField ShowEditButton="True" />            
        </Columns>
        </asp:GridView>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:LocalConnection %>"
        
            SelectCommand="SELECT [ID], [Name], [Color], [Description], [Size], [IsKit],[Vendor_Name],[Active] FROM [Product]"
            UpdateCommand="Update Product Set [Name]=@Name,[Description]=@Description,[Color]=@Color,[Size]=@Size, [IsKit]=@IsKit,Vendor_Name=@Vendor_Name,[Active]=@Active Where [ID]=@ID">
           <UpdateParameters>
               <asp:Parameter Name="ID" />
               <asp:Parameter Name="Name" />
               <asp:Parameter Name="Description" />
               <asp:Parameter Name="Color" />
               <asp:Parameter Name="Size" />
               <asp:Parameter Name="IsKit" />
               <asp:Parameter Name="Vendor_Name" />
               <asp:Parameter Name="Active" />
           </UpdateParameters>
        </asp:SqlDataSource>    
    </div>
    </form>
</body>
</html>
Now we need to populate the controls under RowDataBound event of GridView plus need to supply update parameter while user updating the GridView. The complete server side code is given below:
using System;
using System.Data;
using System.Web.UI.WebControls;

public partial class GridView_Edit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                DropDownList cboSize = (DropDownList)e.Row.FindControl("cboSize");
                RadioButtonList rdoIsKit = (RadioButtonList)e.Row.FindControl("rdoIsKit");
                CheckBox chkActive = (CheckBox)e.Row.FindControl("chkActive");
                CheckBoxList chkVendors = (CheckBoxList)e.Row.FindControl("chkVendors");
                cboSize.SelectedValue = ((DataRowView)e.Row.DataItem)["Size"].ToString();
                if (!Convert.ToBoolean(((DataRowView)e.Row.DataItem)["IsKit"]))
                    rdoIsKit.SelectedValue = "Product";
                else
                    rdoIsKit.SelectedValue = "Kit";
                chkActive.Checked =Convert.ToBoolean(((DataRowView)e.Row.DataItem)["Active"]);
                string[] strSplitArr = ((DataRowView)e.Row.DataItem)["Vendor_Name"].ToString().Split(',');
                // Loop through all checkboxlist items
                // If matched with database table value then checked
                foreach (ListItem oItem in chkVendors.Items)
                {
                    for (int i = 0; i < strSplitArr.Length; i++)
                    {
                        if (oItem.Value == strSplitArr[i].Trim())
                        {
                            oItem.Selected = true;
                            break;
                        }
                    }
                }
            }
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        DropDownList cboSize = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cboSize");
        RadioButtonList rdoIsKit = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("rdoIsKit");
        CheckBox chkActive = (CheckBox)GridView1.Rows[e.RowIndex].FindControl("chkActive");
        CheckBoxList chkVendors = (CheckBoxList)GridView1.Rows[e.RowIndex].FindControl("chkVendors");
        SqlDataSource1.UpdateParameters["Size"].DefaultValue = cboSize.SelectedValue;
        if(rdoIsKit.SelectedValue=="Product")
            SqlDataSource1.UpdateParameters["IsKit"].DefaultValue = "0";
        else
            SqlDataSource1.UpdateParameters["IsKit"].DefaultValue = "1";
        SqlDataSource1.UpdateParameters["Active"].DefaultValue = chkActive.Checked.ToString();
        string sVendors = "";
        foreach (ListItem oItem in chkVendors.Items)
        {
            if (oItem.Selected)
            {
                if (sVendors.Length == 0)
                    sVendors = oItem.Value;
                else
                    sVendors = sVendors + "," + oItem.Value;
            }
        }
        // Here i just show you an example
        // Its not applicable in real life
        // You need to insert multiple vendor into another details table
        // Hope now you can do
        SqlDataSource1.UpdateParameters["Vendor_Name"].DefaultValue = sVendors;
    }
}
Hope now you can control DropDownList RadioButtonList CheckBox CheckBoxList within GridView in Edit Mode.

3 comments:

Anonymous said...

I wish I could see how this was done using a ListView.

Rubi said...

Could i use this code to validate checkbox in gridview mode

Saion Roy said...

Yes you can use any validator controls. Also can use Javascript or Jquery validation.

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash