Friday, November 25, 2011

RadImage in RadGrid

Problem: How to bind and insert a RadImage in RadGrid  From Server Side using RadAsyncUpload.

Solution:
Here Is The Sample Code.
ASPX

<%@ Page Title="Home Page" Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"
    Inherits="_Default" %>

<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<!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 id="Head1" runat="server">
</head>
<body class="BODY">
    <form id="form1" runat="server">
    <telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server">
    </telerik:RadStyleSheetManager>
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">
            var uploadedFilesCount = 0;
            var isEditMode;
            function validateRadUpload(source, e) {
                debugger;
                if (isEditMode == null || isEditMode == undefined) {
                    e.IsValid = false;

                    if (uploadedFilesCount > 0) {
                        e.IsValid = true;
                    }
                }
                isEditMode = null;
            }

            function OnClientFileUploaded(sender, eventArgs) {
                uploadedFilesCount++;
            }
            function conditionalPostback(sender, eventArgs) {
                var theRegexp = new RegExp("\.UpdateButton$|\.PerformInsertButton$", "ig");
                if (eventArgs.get_eventTarget().match(theRegexp)) {
                    var upload = $find(window['UploadId']);

                    //AJAX is disabled only if file is selected for upload
                    if (upload.getFileInputs()[0].value != "") {
                        eventArgs.set_enableAjax(false);
                    }
                }
            }
       
        </script>
    </telerik:RadCodeBlock>
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
        </Scripts>
    </telerik:RadScriptManager>
    <table width="100%">
        <tr>
            <td>
            </td>
        </tr>
        <tr>
            <td align="center" width="90%">
                <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
                    <AjaxSettings>
                        <telerik:AjaxSetting AjaxControlID="RadGrid1">
                            <UpdatedControls>
                                <telerik:AjaxUpdatedControl ControlID="RadGrid1" />
                            </UpdatedControls>
                        </telerik:AjaxSetting>
                    </AjaxSettings>
                </telerik:RadAjaxManager>
                <telerik:RadGrid ID="RadGrid1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
                    CellSpacing="0" GridLines="None" OnInsertCommand="RadGrid1_InsertCommand" OnItemCreated="RadGrid1_ItemCreated"
                    OnNeedDataSource="RadGrid1_NeedDataSource" PageSize="3" ShowStatusBar="True"
                    Skin="Web20" Width="900px">
                    <PagerStyle AlwaysVisible="true" Mode="NumericPages" />
                    <MasterTableView CommandItemDisplay="Top" Width="900px">
                        <Columns>
                            <telerik:GridTemplateColumn HeaderStyle-Width="190px" HeaderText="Image Name" SortExpression="Name"
                                UniqueName="ImageName">
                                <ItemTemplate>
                                    <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <telerik:RadTextBox ID="txbName" runat="server" Text='<%# Eval("Name") %>' Width="190px" />
                                    <asp:RequiredFieldValidator ID="Requiredfieldvalidator1" runat="server" ControlToValidate="txbName"
                                        Display="Dynamic" ErrorMessage="Please, enter a name!" SetFocusOnError="true" />
                                </EditItemTemplate>
                                <HeaderStyle Width="190px" />
                                <ItemStyle VerticalAlign="Top" Width="190px" />
                            </telerik:GridTemplateColumn>
                            <telerik:GridTemplateColumn DataField="Description" HeaderStyle-Width="200px" HeaderText="Description"
                                UniqueName="Description">
                                <ItemTemplate>
                                    <telerik:RadTextBox ID="lblDescription" runat="server" BorderColor="White" Height="60px"
                                        ReadOnly="true" Text='<%# TrimDescription(DirectCast(IIF(Eval("Description") IsNot DBNull.Value,Eval("Description"),string.Empty),String)) %>'
                                        TextMode="MultiLine" Width="200px" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <telerik:RadTextBox ID="txbDescription" runat="server" Height="60px" Text='<%# Eval("Description") %>'
                                        TextMode="MultiLine" Width="180px" />
                                </EditItemTemplate>
                                <HeaderStyle Width="200px" />
                                <ItemStyle VerticalAlign="Top" Width="180px" />
                            </telerik:GridTemplateColumn>
                            <telerik:GridTemplateColumn HeaderStyle-Width="220px" ItemStyle-Width="220px" HeaderText="Image"
                                UniqueName="Upload">
                                <ItemTemplate>
                                    <telerik:RadBinaryImage ID="RadBinaryImage1" runat="server" AlternateText='<%#Eval("Name", "Photo of {0}") %>'
                                        AutoAdjustImageControlSize="false" DataValue='<%#Eval("Image") %>' Height="140px"
                                        ToolTip='<%#Eval("Name", "Photo of {0}") %>' Width="220px" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <telerik:RadAsyncUpload ID="AsyncUpload1" runat="server" AllowedFileExtensions="jpg,jpeg,png,gif"
                                        MaxFileSize="5048576" OnClientFileUploaded="OnClientFileUploaded" OnValidatingFile="RadAsyncUpload1_ValidatingFile">
                                    </telerik:RadAsyncUpload>
                                </EditItemTemplate>
                            </telerik:GridTemplateColumn>
                        </Columns>
                        <EditFormSettings>
                            <EditColumn ButtonType="ImageButton" />
                        </EditFormSettings>
                        <PagerStyle AlwaysVisible="True" />
                    </MasterTableView>
                    <FilterMenu EnableImageSprites="False">
                    </FilterMenu>
                    <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Web20">
                    </HeaderContextMenu>
                </telerik:RadGrid>
            </td>
        </tr>
    </table>
</body>
</form>
</html>

VB Code.
Imports System.Data
Imports Telerik.Web.UI
Imports System.Data.SqlClient
Partial Class _Default
    Inherits System.Web.UI.Page 
Const MaxTotalBytes As Integer = 1024 ' 1 MB
    Dim totalBytes As Integer
    Dim ConnString As String = "data source=localDataSource;Initial Catalog=database;User Id=User;Password=*****;"

    Dim sqlconn As New SqlConnection(ConnString)


    Public Property IsRadAsyncValid() As System.Nullable(Of Boolean)
        Get
            If Session("IsRadAsyncValid") Is Nothing Then
                Session("IsRadAsyncValid") = True
            End If

            Return Convert.ToBoolean(Session("IsRadAsyncValid").ToString())
        End Get
        Set(ByVal value As System.Nullable(Of Boolean))
            Session("IsRadAsyncValid") = value
        End Set
    End Property
    Protected Function TrimDescription(ByVal description As String) As String
        If Not String.IsNullOrEmpty(description) AndAlso description.Length > 200 Then
            Return String.Concat(description.Substring(0, 200), "...")
        End If
        Return description
    End Function

 
    Protected Sub RadGrid1_InsertCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs)
        If Not IsRadAsyncValid.Value Then
            e.Canceled = True
            RadAjaxManager1.Alert("The length of the uploaded file must be less than 1 MB")
            Return
        End If

        Dim insertItem As GridEditFormInsertItem = TryCast(e.Item, GridEditFormInsertItem)
        Dim imageName As String = TryCast(insertItem("ImageName").FindControl("txbName"), RadTextBox).Text
        Dim description As String = TryCast(insertItem("Description").FindControl("txbDescription"), RadTextBox).Text
        Dim radAsyncUpload As RadAsyncUpload = TryCast(insertItem("Upload").FindControl("AsyncUpload1"), RadAsyncUpload)

        Dim file As UploadedFile = radAsyncUpload.UploadedFiles(0)
        Dim fileData As Byte() = New Byte(file.InputStream.Length - 1) {}
        file.InputStream.Read(fileData, 0, CInt(file.InputStream.Length))
        sqlconn.Open()
        Dim Insert As New SqlCommand("Insert into [Test1].[dbo].[Test_Img] ([ImageID],[Name],[Description],[Image]) values ('3','" + imageName + "','" + description + "',  @image  )", sqlconn)
        Dim imageParam As SqlParameter = Insert.Parameters.Add("@image", SqlDbType.Image)
        imageParam.Value = fileData
        imageParam.Size = fileData.Length
        Insert.ExecuteNonQuery()
        sqlconn.Close()

      End Sub

    Protected Sub RadGrid1_NeedDataSource(ByVal source As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource

        Dim SqlCommand As New SqlCommand("Select [ImageID],[Image],[Name],[Description] from [Test1].[dbo].[Test_Img]", sqlconn)
        sqlconn.Open()
        Dim sqladap As New SqlDataAdapter
        sqladap.SelectCommand = SqlCommand
        Dim ds As New DataSet
        sqladap.Fill(ds, "ImageSet")

        RadGrid1.DataSource = ds.Tables(0)
        sqlconn.Close()

    End Sub

    Public Sub RadAsyncUpload1_ValidatingFile(ByVal sender As Object, ByVal e As Telerik.Web.UI.Upload.ValidateFileEventArgs)
        If (totalBytes < MaxTotalBytes) AndAlso (e.UploadedFile.ContentLength < MaxTotalBytes) Then
            e.IsValid = True
            totalBytes += e.UploadedFile.ContentLength
            IsRadAsyncValid = True
        Else
            e.IsValid = False
            IsRadAsyncValid = False
        End If
    End Sub
    Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs)
        If TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode Then
            Dim upload As RadAsyncUpload = TryCast(DirectCast(e.Item, GridEditableItem)("Upload").FindControl("AsyncUpload1"), RadAsyncUpload)
            Dim cell As TableCell = DirectCast(upload.Parent, TableCell)

            Dim validator As New CustomValidator()
            validator.ErrorMessage = "Please select file to be uploaded"
            validator.ClientValidationFunction = "validateRadUpload"
            validator.Display = ValidatorDisplay.Dynamic
            cell.Controls.Add(validator)
        End If

    End Sub
End Class

C# Code.
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using Telerik.Web.UI;
using System.Data.SqlClient;
partial class _Default : System.Web.UI.Page
{

  // 1 MB
 const int MaxTotalBytes = 1024;
 int totalBytes;

 string ConnString = "data source=localDataSource;Initial Catalog=database;User Id=User;Password=*****;";

 SqlConnection sqlconn = new SqlConnection(ConnString);

 public System.Nullable<bool> IsRadAsyncValid {
  get {
   if (Session["IsRadAsyncValid"] == null) {
    Session["IsRadAsyncValid"] = true;
   }

   return Convert.ToBoolean(Session["IsRadAsyncValid"].ToString());
  }
  set { Session["IsRadAsyncValid"] = value; }
 }
 protected string TrimDescription(string description)
 {
  if (!string.IsNullOrEmpty(description) && description.Length > 200) {
   return string.Concat(description.Substring(0, 200), "...");
  }
  return description;
 }


 protected void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
 {
  if (!IsRadAsyncValid.Value) {
   e.Canceled = true;
   RadAjaxManager1.Alert("The length of the uploaded file must be less than 1 MB");
   return;
  }

  GridEditFormInsertItem insertItem = e.Item as GridEditFormInsertItem;
  string imageName = (insertItem("ImageName").FindControl("txbName") as RadTextBox).Text;
  string description = (insertItem("Description").FindControl("txbDescription") as RadTextBox).Text;
  RadAsyncUpload radAsyncUpload = insertItem("Upload").FindControl("AsyncUpload1") as RadAsyncUpload;

  UploadedFile file = radAsyncUpload.UploadedFiles(0);
  byte[] fileData = new byte[file.InputStream.Length];
  file.InputStream.Read(fileData, 0, Convert.ToInt32(file.InputStream.Length));
  sqlconn.Open();
  SqlCommand Insert = new SqlCommand("Insert into [Test1].[dbo].[Test_Img] ([ImageID],[Name],[Description],[Image]) values ('3','" + imageName + "','" + description + "',  @image  )", sqlconn);
  SqlParameter imageParam = Insert.Parameters.Add("@image", SqlDbType.Image);
  imageParam.Value = fileData;
  imageParam.Size = fileData.Length;
  Insert.ExecuteNonQuery();
  sqlconn.Close();

 }


 protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
 {
  SqlCommand SqlCommand = new SqlCommand("Select [ImageID],[Image],[Name],[Description] from [Test1].[dbo].[Test_Img]", sqlconn);
  sqlconn.Open();
  SqlDataAdapter sqladap = new SqlDataAdapter();
  sqladap.SelectCommand = SqlCommand;
  DataSet ds = new DataSet();
  sqladap.Fill(ds, "ImageSet");

  RadGrid1.DataSource = ds.Tables[0];
  sqlconn.Close();

 }

 public void RadAsyncUpload1_ValidatingFile(object sender, Telerik.Web.UI.Upload.ValidateFileEventArgs e)
 {
  if ((totalBytes < MaxTotalBytes) && (e.UploadedFile.ContentLength < MaxTotalBytes)) {
   e.IsValid = true;
   totalBytes += e.UploadedFile.ContentLength;
   IsRadAsyncValid = true;
  } else {
   e.IsValid = false;
   IsRadAsyncValid = false;
  }
 }
 protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
 {
  if (e.Item is GridEditableItem && e.Item.IsInEditMode) {
   RadAsyncUpload upload = (GridEditableItem)e.Item("Upload").FindControl("AsyncUpload1") as RadAsyncUpload;
   TableCell cell = (TableCell)upload.Parent;

   CustomValidator validator = new CustomValidator();
   validator.ErrorMessage = "Please select file to be uploaded";
   validator.ClientValidationFunction = "validateRadUpload";
   validator.Display = ValidatorDisplay.Dynamic;
   cell.Controls.Add(validator);
  }

 }
}


No comments:

Post a Comment