Home Other Binding Checkbox to Radgrid
09.09.2010
Main Menu
Programming
.NET Controls
Operating System
Databases
Articles
Add to: Digg Add to: Del.icoi.us Add to: Reddit Add to: StumbleUpon Add to: Slashdot Add to: Yahoo Add to: Technorati Add to: Google
Binding Checkbox to Radgrid

Radgrid is a cool Telerik cotrol however when binding a checkbox to the Radgrid you may be experiencing this error:

Exception Details: System.InvalidCastException: Conversion from type 'DBNull' to type 'Boolean' is not valid.

When updating the record you should be able to do it successfully, however when you are trying to insert a record you may be getting The invalid cast exception. To resolve this error you will need to set the defaut value to avoid the problem. You can set the default value in the Item command event.

Here is a snippet:

if (e.CommandName == RadGrid.InitInsertCommandName) //"Add new" button clicked

 {

                GridEditCommandColumn editColumn = (GridEditCommandColumn)gridSites.MasterTableView.GetColumn("EditCommandColumn");

                editColumn.Visible = false;

                e.Canceled = true;

 

                //Set the default value for the checkbox

                System.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();

                newValues["IsNoticeEnable"] = true;

 

                //Set the default value for the drop down list

 

                //newValues["yourDropDownList"] = "Active";

 

                e.Item.OwnerTableView.InsertItem(newValues);

}

 

Here is the whole ASPX Page:

<%@ Page Language="C#" MasterPageFile="~/SiteEntry.Master" AutoEventWireup="true" CodeBehind="Site.aspx.cs" Inherits="SiteEntryLogs.Site" Title="Untitled Page" %>

 

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <div style="width:100%; text-align:left; padding-left: 100px;">Manage Site</div>

 

    <div style="height: 100%; text-align: left; padding-left: 100px;">

        <telerik:RadAjaxLoadingPanel ID="pnLoading" runat="server" HorizontalAlign="Center"

            IsSticky="false">

            <asp:Image ID="Image1" runat="server" AlternateText="Loading..." Visible="true" ImageUrl="~/Images/Common/loading_small.gif" />

        </telerik:RadAjaxLoadingPanel>

        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">

            <AjaxSettings>

                <telerik:AjaxSetting AjaxControlID="gridSites">

                    <UpdatedControls>

                        <telerik:AjaxUpdatedControl ControlID="gridSites" />

                        <telerik:AjaxUpdatedControl ControlID="divMsgs" />

                    </UpdatedControls>

                </telerik:AjaxSetting>

            </AjaxSettings>

        </telerik:RadAjaxManager>

        <telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" />

        <br />

        <telerik:RadGrid ID="gridSites" Width="700px" runat="server" AutoGenerateColumns="false" Skin="Sunset"

            ShowStatusBar="true" AllowMultiRowSelection="false" OnNeedDataSource="gridSites_NeedDataSource"

            AllowPaging="true" AllowSorting="true" OnItemCommand="gridSites_ItemCommand"

             PageSize="10" OnItemDataBound="gridSites_ItemDataBound">

            <ClientSettings ></ClientSettings>

            <MasterTableView HierarchyDefaultExpanded="false" EditMode="EditForms" HierarchyLoadMode="Client"

                Width="700px" ShowHeadersWhenNoRecords="false" DataKeyNames="SiteID" CommandItemDisplay="TopAndBottom">

                <Columns>

                    <telerik:GridEditCommandColumn ItemStyle-Width="30" ButtonType="ImageButton" EditText="Edit">

                        <ItemStyle HorizontalAlign="Center" CssClass="MyImageButton" />

                    </telerik:GridEditCommandColumn>

                    <telerik:GridBoundColumn DataField="SiteName" ItemStyle-Width="350" HeaderText="Site Name">

                    </telerik:GridBoundColumn>

                    <telerik:GridBoundColumn DataField="Details" ItemStyle-Width="350" HeaderText="Details">

                    </telerik:GridBoundColumn>                  

 

                    <telerik:GridButtonColumn CommandName="Delete" Text="Delete"

                      UniqueName="DeleteColumn" ConfirmText="Delete this site?" ButtonType="ImageButton">

                        <ItemStyle HorizontalAlign="Center" CssClass="MyImageButton" />

                    </telerik:GridButtonColumn>

                </Columns>

                <EditFormSettings EditFormType="Template" PopUpSettings-Modal="false" CaptionFormatString="Manage Site"

                    PopUpSettings-Width="300">

                    <FormTemplate >

 

                        <br />

                        <table>

                            <tr>

                                <td>

                                    Site Name:

                                </td>

                                <td>

                                    <asp:TextBox ID="txtSiteName" Text='<%# Bind( "SiteName") %>' runat="server"></asp:TextBox>

                                </td>

                            </tr>

                            <tr>

                                <td>

                                    Detail:

                                </td>

                                <td>

                                    <asp:TextBox ID="txtDetails" Width="400px" Height="100px" Text='<%# Bind( "Details") %>' runat="server" TextMode="MultiLine"></asp:TextBox>

                                </td>

                            </tr>

                            <tr>

                                <td>

                                    Enable Notice:

                                </td>

                                <td>

                                    <asp:CheckBox ID="ckhIsNoticeEnabled" Text="" Checked='<%# Bind( "IsNoticeEnable") %>' runat="server" />

 

                                </td>

                            </tr>

                            <tr>

                                <td>

                                    Notice Image:

                                </td>

                                <td>

                                    <asp:TextBox ID="txtNoticeImage" Width="400px" Text='<%# Bind( "NoticeImage") %>' runat="server" TextMode="SingleLine"></asp:TextBox>

                                </td>

                            </tr>

                            <tr>

                                <td colspan="2" align="right">

                                    <br />

                                    <asp:Button ID="btnUpdate" Text='<%# (Container is GridEditFormInsertItem) ? "Insert" : "Update" %>'

                                        runat="server" CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'>

                                    </asp:Button>&nbsp;

                                    <asp:Button ID="btnCancel" Text="Cancel" runat="server" CausesValidation="False"

                                        CommandName="Cancel"></asp:Button>

                                </td>

                            </tr>

                        </table>

                        <br />

                    </FormTemplate>

                </EditFormSettings>

            </MasterTableView>

            <ClientSettings AllowExpandCollapse="true" EnableRowHoverStyle="true">

                <Selecting AllowRowSelect="true" />

                <Scrolling AllowScroll="false" ScrollHeight="200" UseStaticHeaders="True" SaveScrollPosition="True"

                    FrozenColumnsCount="1"></Scrolling>

            </ClientSettings>

            <ItemStyle HorizontalAlign="Left" />

            <ActiveItemStyle HorizontalAlign="Left" />

            <AlternatingItemStyle HorizontalAlign="Left" />

        </telerik:RadGrid>

        <p id="divMsgs" runat="server">

            <asp:Label ID="Label1" runat="server" EnableViewState="False" Font-Bold="True" ForeColor="#FF8080"></asp:Label>

            <asp:Label ID="Label2" runat="server" EnableViewState="False" Font-Bold="True" ForeColor="#00C000"></asp:Label>

        </p>

    </div>

</asp:Content>

 

 

Here is the whole CS Page:

 

using System;

using System.Collections;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using Telerik.Web.UI;

using Application.BusinessObjects;

using Application.Facade;

 

 

namespace SiteEntryLogs

{

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

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            Authentication.CheckAdminAccess();        

 

            if (!IsPostBack)

            {

                LoadGridSites();

            }

            gridSites.UpdateCommand += new GridCommandEventHandler(gridSites_UpdateCommand);

            gridSites.InsertCommand += new GridCommandEventHandler(gridSites_InsertCommand);

            gridSites.DeleteCommand += new GridCommandEventHandler(gridSites_DeleteCommand);

        }

 

        void gridSites_DeleteCommand(object source, GridCommandEventArgs e)

        {

            try

            {

                int siteID = int.Parse(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["SiteID"].ToString());

 

                SitesEntity site = SitesFacade.GetSites(siteID);

                SitesFacade.DeleteSites(siteID);              

                DisplayMessage(false, string.Format("Site {0} have been deleted.", site.SiteName));

            }

            catch (Exception ex)

            {

                DisplayMessage(true, ex.Message);

            }

        }

 

        void gridSites_InsertCommand(object source, GridCommandEventArgs e)

        {

            try

            {

                GridEditFormItem gridEditFormItem = (GridEditFormItem)e.Item;

                Hashtable ht = new Hashtable();

                gridEditFormItem.ExtractValues(ht);

 

                SitesEntity site = new SitesEntity();

                site.SiteID = 0;

                site.SiteName = ht["SiteName"].ToString();

                site.Details = ht["Details"].ToString();

 

                site.IsNoticeEnable = (bool)ht["IsNoticeEnable"];

                site.NoticeImage = ht["NoticeImage"].ToString();         

 

                site.ViewInd = true;

                SitesFacade.SaveSites(site);               

 

                DisplayMessage(false, "New site have been added.");

            }

            catch (Exception ex)

            {

                DisplayMessage(true, ex.Message);

            }

        }

 

        void gridSites_UpdateCommand(object source, GridCommandEventArgs e)

        {

            try

            {

                GridEditFormItem gridEditFormItem = (GridEditFormItem)e.Item;

                Hashtable ht = new Hashtable();

                gridEditFormItem.ExtractValues(ht);

 

                int siteID = int.Parse(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["SiteID"].ToString());

 

                SitesEntity site = SitesFacade.GetSites(siteID);

 

                site.SiteName = ht["SiteName"].ToString();

                site.Details = ht["Details"].ToString();

                site.IsNoticeEnable = (bool)ht["IsNoticeEnable"];

                site.NoticeImage = ht["NoticeImage"].ToString();

                site.ViewInd = true;

                SitesFacade.SaveSites(site);

 

                DisplayMessage(false, "Site Updated.");               

            }

            catch (Exception ex)

            {

                DisplayMessage(true, ex.Message);

            }

        }

 

        private void LoadGridSites()

        {

            gridSites.DataSource = LoadGridSitesDataSource();

            gridSites.DataBind();

        }

 

        private List<SitesEntity> LoadGridSitesDataSource()

        {

 

            return (List<SitesEntity>)SitesFacade.GetAllSites();

        }

 

        protected void gridSites_NeedDataSource(object source, GridNeedDataSourceEventArgs e)

        {

            this.gridSites.DataSource = LoadGridSitesDataSource();

        }

 

        private void DisplayMessage(bool isError, string text)

        {

            Label label = (isError) ? this.Label1 : this.Label2;

            label.Text = text;

        }

 

        protected void gridSites_ItemCommand(object source, GridCommandEventArgs e)

        {

            if (e.CommandName == RadGrid.InitInsertCommandName) //"Add new" button clicked

            {

                GridEditCommandColumn editColumn = (GridEditCommandColumn)gridSites.MasterTableView.GetColumn("EditCommandColumn");

                editColumn.Visible = false;

                e.Canceled = true;

 

                //Set the default value for the checkbox

                System.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();

                newValues["IsNoticeEnable"] = true;

 

                //Set the default value for the drop down list

 

                //newValues["yourDropDownList"] = "Active";

 

                e.Item.OwnerTableView.InsertItem(newValues);

            }

            else if (e.CommandName == RadGrid.RebindGridCommandName && e.Item.OwnerTableView.IsItemInserted)

            {

                e.Canceled = true;

            }

            else

            {

                GridEditCommandColumn editColumn = (GridEditCommandColumn)gridSites.MasterTableView.GetColumn("EditCommandColumn");

                if (!editColumn.Visible)

                    editColumn.Visible = true;

            }

        }       

 

        protected void gridSites_ItemDataBound(object sender, GridItemEventArgs e)

        {

            if ((e.Item is GridEditFormItem) && (e.Item.IsInEditMode))

            {

                if (e.Item.DataItem is SitesEntity)

                {

                    //SitesEntity site = (SitesEntity)e.Item.DataItem;

                    //GridEditFormItem editform = (GridEditFormItem)e.Item;

                    //RadColorPicker rcpColor = (RadColorPicker)editform.FindControl("rcpColor");                   

                }

            }

        }

 

    }



Comments (0)
Write comment
Your Contact Details:
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
:D:angry::angry-red::evil::idea::love::x:no-comments::ooo::pirate::?::(
:sleep::););)):0
Security
Please input the anti-spam code that you can read in the image.

!joomlacomment 4.0 Copyright (C) 2009 Compojoom.com . All rights reserved."