Telerik Forums
UI for ASP.NET AJAX Forum
5 answers
467 views
Here is some code that I whpped together which shows how to create a pdf or xls document from a RadGrid and  attach it to an email.

I only had time to draft the basics, but you should get the idea and I thought that I would share since members like Princy helped me get here.
<telerik:RadGrid ID="RadGrid1"  
               AllowSorting="false"
               AutoGenerateColumns="false"
               AlternatingItemStyle-HorizontalAlign="center"
               AlternatingItemStyle-BackColor="#ffffff"               
               GroupingEnabled="true"
               OnExcelExportCellFormatting="RadGrid1_ExcelExportCellFormatting"
               OnGridExporting="RadGrid1_GridExporting"
               OnPdfExporting="RadGrid1_PdfExporting"
               ExportSettings-Excel-Format="Html"
               ExportSettings-ExportOnlyData="true"
               Width="100%"
               runat="server">  
               <MasterTableView  Width="99%">                
               <Columns>  ...

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mec.CommonLibrary.Cryptography;
using MEC.EMA.BLL;
using Microsoft.Security.Application;
using Telerik.Web.UI;
 
 
public class EmailRadGridAttachment
{
 
    List<Person> _userList = new List<Person>();
    UserBLL _userBLL = new UserBLL();
 
    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }
 
    protected void BindGrid()
    {
        _userList = _userListBLL.GetUserById(_userId);
        RadGrid1.DataSource = _userList;
    }
 
    // aspx page with a button that fires this event for Excel
    protected void ButtonExcel_Click(object sender, EventArgs e)
    {
        ConfigureExport();
        RadGrid Grid1 = (RadGrid)Page.Master.FindControl("Main").FindControl("RadGrid1");
        Grid1.MasterTableView.ExportToExcel();
    }
 
    // aspx page with a button that fires this even for PDF
    protected void ButtonPdf_Click(object sender, System.EventArgs e)
    {
        ConfigureExport();
        RadGrid Grid1 = (RadGrid)Page.Master.FindControl("Main").FindControl("RadGrid1");
        Grid1.ExportSettings.Pdf.AllowPrinting = true;
        Grid1.ExportSettings.Pdf.AllowModify = true;
        Grid1.ExportSettings.Pdf.AllowCopy = true;
        Grid1.ExportSettings.Pdf.AllowAdd = true;
        // I found that if I don't use postscript fonts the data does not make it to the attachment
        Grid1.ExportSettings.Pdf.DefaultFontFamily = "Helvetica";
        Grid1.ExportSettings.Pdf.PageLeftMargin = new Unit(2, UnitType.Mm);
        Grid1.ExportSettings.Pdf.PageRightMargin = new Unit(2, UnitType.Mm);
        Grid1.ExportSettings.Pdf.PageHeaderMargin = new Unit(0, UnitType.Mm);
        Grid1.ExportSettings.Pdf.PaperSize = GridPaperSize.Legal;
        // to get lanscape orientation     
        Grid1.ExportSettings.Pdf.PageHeight = Unit.Parse("210mm");
        // Width based on TOU and NON-TOU Columns and the smaller parse the more room for data
        Grid1.ExportSettings.Pdf.PageWidth = Unit.Parse("420mm");
 
        foreach (GridColumn col in RadGrid1.MasterTableView.RenderColumns)
        {
            // We have the ability to control the width of columns in the export here
            if (col.UniqueName != "MiddleInitial")
            {
                col.HeaderStyle.Width = Unit.Pixel(50);
            }
        }
        Grid1.MasterTableView.ExportToPdf();
    }
 
    protected void RadGrid1_PdfExporting(object sender, GridPdfExportingArgs e)
    {
        // I have added some more information that will be included in the PDF above the RadGrid here
        StringBuilder customHTML = new StringBuilder();
        customHTML.Append("<p style='color: red; font-weight: bold; font-size: 10pt;'>Title Page</p>");
        customHTML.Append("<table style='font-family:Helvetica;font-size:9pt;width:500px;'>");
        // Very Important to make sure you have a colgroup and the same number of "<col>" as "<td>"
        customHTML.Append("<colgroup><col style='width: 200px; white-space:nowrap;' /><col style='text-align:left;' /></colgroup>");
        // ColGroup = Number of <td> in a row is needed for Telerik export to PDF
        customHTML.Append("<tr><td>Customer: " + CustomerName.Text + "</td><td>Date: " + LabelDate.Text + " </td></tr>");
        customHTML.Append("<tr><td>Address: " + LabelAddress.Text + "</td><td>Email: " + LabelEmail.Text + " </td></tr>");
        customHTML.Append("<tr><td>City: " + LabelCity.Text + "</td><td>Phone: " + LabelPhone.Text + " </td></tr>");
        customHTML.Append("<tr><td>State: " + LabelState.Text + "</td><td>Zip: " + LabelZipCode.Text + " </td></tr>");
        customHTML.Append("</table>");      
        e.RawHTML = customHTML + e.RawHTML;
    }
       
 
   
 
    public void ConfigureExport()
    {
        RadGrid Grid1 = (RadGrid)Page.Master.FindControl("Main").FindControl("RadGrid1");
        Grid1.ExportSettings.ExportOnlyData = true;
        Grid1.ExportSettings.IgnorePaging = true;
        // We don't want the Open, Save or Cancel prompt to open for a new window when calling this page
        Grid1.ExportSettings.OpenInNewWindow = false;
    }
 
    protected void RadGrid1_GridExporting(object source, GridExportingArgs e)
    {             
        StringBuilder customHTML = new StringBuilder();
        MemoryStream gridMemoryStream = new MemoryStream(new ASCIIEncoding().GetBytes(e.ExportOutput));
        if (e.ExportType == ExportType.Excel)
        {
            SendEMailWithAttachment(gridMemoryStream, "attachment.xls");          
        }
        // Stuff the Grid in a memory stream and pass it to the email method
        if (e.ExportType == ExportType.Pdf)
        {
            SendEMailWithAttachment(gridMemoryStream, "attachment.pdf");          
        }
        gridMemoryStream.Close();
        // Redirect to the same page so the alert does not pop-up
        Response.Redirect(Request.Url.AbsoluteUri);
    }
 
    public void SendEMailWithAttachment(Stream attachmentStream, string fileName)
    {
        //settings from the web.config
        SmtpClient smtpClient = new SmtpClient(Convert.ToString(ConfigurationManager.AppSettings["SERVER_EMAIL"]));
        string authType = "Basic";
        MailMessage email = new MailMessage();
        StringBuilder body = new StringBuilder();
        string emaURL = Convert.ToString(ConfigurationManager.AppSettings["BASE_URL"]);
        email.From = new MailAddress("From@gmail.com");
        email.To.Add("To@gmail.com");
        email.Subject = "This is the subject";
        body.Append("<table style='font-family:Helvetica;font-size:9pt;width:600px;'>");
        body.Append("<tr><td>You can put in whatever you want here</td></tr>");
        body.Append("</table>");
        // Attachment goes here
        email.Attachments.Add(new Attachment(attachmentStream, fileName));
        email.Body = body.ToString();
        email.IsBodyHtml = true;
        NetworkCredential nc = new NetworkCredential(Convert.ToString(ConfigurationManager.AppSettings["CredentialU"]), Convert.ToString(ConfigurationManager.AppSettings["CredentialP"]));
        smtpClient.Credentials = nc.GetCredential(Convert.ToString(smtpClient), 25, authType);
        smtpClient.Send(email);
    }
}

Marin Bratanov
Telerik team
 answered on 28 Dec 2018
1 answer
180 views

I was trying to create a User Control for standardizing the Grid Control across all the forms. Surely all the forms will have different columns but the layout is the same across except for few properties here and there. How do I expose the Column Collection?

My Code would be:

<telerik:RadGrid ID="grid" runat="server" AllowCustomPaging="false" AllowPaging="False" AllowSorting="False" AutoGenerateColumns="False" CellPadding="0" CellSpacing="0" CssClass="gridCandidate" Height="100%" Width="100%">
        <ClientSettings EnableAlternatingItems="false" EnableRowHoverStyle="true">
            <Scrolling AllowScroll="true" UseStaticHeaders="true" />
            <Selecting AllowRowSelect="True" />
            <ClientEvents OnRowDataBound="function() {}" OnCommand="function(){}" />
        </ClientSettings>
        <MasterTableView AllowFilteringByColumn="False" AllowNaturalSort="false" ClientDataKeyNames="ID" DataKeyNames="ID" EnableColumnsViewState="False" EnableViewState="False" HierarchyLoadMode="Client"
            NoMasterRecordsText="<div class='noRec'>No records to display.</div>" TableLayout="Auto">
            <Columns></Columns>
<HeaderStyle Height="0px" />
            <PagerStyle Visible="False" />
        </MasterTableView>
    </telerik:RadGrid>

 

 

[MergableProperty(false), DefaultValue((string)null),
PersistenceMode(PersistenceMode.InnerProperty)]
public GridColumnCollection Columns
{
    get
    {
        return grid.Columns;
    }
    set
    {
        foreach (GridColumn column in value)
        {
            grid.MasterTableView.Columns.Add(column);
        }
        //grid.MasterTableView.Columns.Add()
    }
}

 

Any idea how to expose the Columns property?

Marin Bratanov
Telerik team
 answered on 27 Dec 2018
8 answers
535 views
Hi.

I have a project thats contain RadColorPicker. I need to change text color according the chosen one. inspect shows me the wrong color. Process steps;

     1)Choose color and close the RadColorPicker,

     2)Inspect still shows me the previous color that i chosen,

     3)Inspect has been updated when i clicked second time to RadColorPicker.

I don't know why is happening and need your help.

Thanks a lot.
Caner
Top achievements
Rank 1
 answered on 27 Dec 2018
12 answers
870 views
I just wanted to open document in RADEditor through C# code, instead of navigating File->Open link in RADEditor. If this is possible, I'll display the document link in my web application to open the respective document in RADEditor.So that, can edit the word document in RADEditor and save it on the server which is hosted. Let me know the case is possible.
Eyup
Telerik team
 answered on 27 Dec 2018
3 answers
118 views
No formatting is being stripped when the user is using IE11.  Works fine on other browsers.

Does anyone know the fix?

thanks!
baojian
Top achievements
Rank 1
 answered on 25 Dec 2018
3 answers
547 views

Hi,

 

I am trying to access a control in InsertItemTemplate.

 

On EditTemplate is fine, I use:

var Ctlcst_costru_civmec_note = (RadTextBox)CtlCstCostruzione.EditItems[0].FindControl("Ctlcst_costru_civmec_note");

 

But I am not able to find the same control on insert one. How can I do?

 

Thx,

Valerio

Marin Bratanov
Telerik team
 answered on 24 Dec 2018
1 answer
368 views

I have a requirement to dynamically build a table on server side and fill it with either textbox(for entering strings) or textbox with a small drop down next to it to enter numbers and unit of measure.  My problem is that if I add both text and drop down to the same cell drop down overlaps text box for few pixels and is not aligned with other controls in rows above.normal text box size is 200(from CSS) and short is 150(from CSS). List box width is set to 50, so I expect controls to be aligned, but they are not. Screen shot attached.  How this can be fixed?

Here is my code :

CSS:

.myLabelCss {
            color: Red !important;
            width: 20px !important;
        }

        .myLabelCssDD {
            color: Red !important;
            width: 10px !important;
        }

        .CustomClass {
            width: 200px !important;
        }

        .CustomClass .riSingle .riTextBox {
                width: 200px !important;
            }

            .CustomClassShort{
            width: 150px !important;
        }

Table declaration

<asp:Table ID="tblParms" runat="server" Font-Names="Arial"        ForeColor="Black"  CellSpacing="10" BorderColor="Black" Width="100%"
                                                    EnableViewState="False" BorderStyle="None"   meta:resourcekey="tblParmsResource1">  </asp:Table>

 

VB code:

Private Sub buildControls()
        Dim tRow As New TableRow()
        tRow.ID = "MyRow1"
        Dim tCell As New TableCell()
        ' cell 1, label
        tCell.Text = "MyLabel1"
        tCell.VerticalAlign = VerticalAlign.Top
        tCell.Width = New Unit("30%")
        tRow.Cells.Add(tCell)
        'cell 2, controls
        tCell = New TableCell()
        tCell.VerticalAlign = VerticalAlign.Top
        tCell.HorizontalAlign = HorizontalAlign.Left
        tCell.Width = New Unit("30%")
        Dim txtBox = New RadTextBox()
        txtBox.ID = "MyText1"
        txtBox.CssClass = "CustomClassShort"
        txtBox.Label = "*"
        txtBox.LabelCssClass = "myLabelCss"
        txtBox.MaxLength = 15
        tCell.Controls.Add(txtBox)
        Dim ddUOMList As RadDropDownList = New RadDropDownList
        ddUOMList.ID = "MyList1"
        ddUOMList.Width = 50
        ddUOMList.CausesValidation = False
        Dim UOMItem As New DropDownListItem()
        UOMItem.Text = "A"
        UOMItem.Value = "A"
        ddUOMList.Items.Add(UOMItem)
        UOMItem = New DropDownListItem()
        UOMItem.Text = "mA"
        UOMItem.Value = "mA"
        ddUOMList.Items.Add(UOMItem)
        tCell.Controls.Add(ddUOMList)
        tRow.Cells.Add(tCell)
        tblParms.Rows.Add(tRow)
        tRow = New TableRow()
        tRow.ID = "MyRow2"
        tCell = New TableCell()
        ' cell 1, label
        tCell.Text = "MyLabel2"
        tCell.VerticalAlign = VerticalAlign.Top
        tCell.Width = New Unit("30%")
        tRow.Cells.Add(tCell)
        'cell 2, controls
        tCell = New TableCell()
        tCell.VerticalAlign = VerticalAlign.Top
        tCell.HorizontalAlign = HorizontalAlign.Left
        tCell.Width = New Unit("30%")
        txtBox = New RadTextBox()
        txtBox.ID = "MyText2"
        txtBox.CssClass = "CustomClass"
        txtBox.Label = "*"
        txtBox.LabelCssClass = "myLabelCss"
        txtBox.MaxLength = 15
        tCell.Controls.Add(txtBox)
        tRow.Cells.Add(tCell)
        tblParms.Rows.Add(tRow)
    End Sub

 

Marin Bratanov
Telerik team
 answered on 23 Dec 2018
1 answer
297 views

Hi

I have a problem in scrolling radgrid in chrome using  <Scrolling AllowScroll="True" UseStaticHeaders="True"  FrozenColumnsCount="7" ></Scrolling>

whenever my scrollbar goes to end it resets itself to first column. and i just have this problem in chrome 

what should I do?

Marin Bratanov
Telerik team
 answered on 23 Dec 2018
3 answers
226 views

hi

I'm using radtreeview  for my page and i set treeview direction " right to left"

i want to be able to drag a node and drop it under another node

but the problem is when i set tree direction right to left my grabbed ( selected) node disappears and page width keep growing

i don't have this problem when i set tree direction to left to right

does telerik support treeview drag and drop for rtl treeview ?

this is the code that i'm using

<div style="direction:rtl;">
<telerik:RadTreeView PersistLoadOnDemandNodes="true" runat="server"                             ID="rtvTables" EnableDragAndDrop="True" ClientIDMode="AutoID"                             OnClientNodeExpanded="onTreeViewExpanded"                             OnClientNodePopulating="nodePopulating"                             OnClientNodeDropping="onClientNodeDropped"  
                            OnClientContextMenuShowing="OnClientContextMenuShowing"                             OnClientNodeDragStart="OnClientNodeDragStart">                             <WebServiceSettings Path="frmReporting.aspx" Method="OnNodeExpanded">                             </WebServiceSettings>                             <%--   <WebServiceSettings Path="Services/frmReporting.asmx" Method="OnNodeExpanded">
                                    </WebServiceSettings>    --%>                         </telerik:RadTreeView>

</div>

 

 

thank you

 

 

Marin Bratanov
Telerik team
 answered on 23 Dec 2018
2 answers
862 views
I had to replace the RadUpload controls in my app with RadAsyncUpload versions rather quickly and I may have missed out on a few details.

In my old system (while using RadUpload) I had code to delete the uploaded files once processed (inserted into a database field).

It looks to me like the simplest thing to do with the RadAsyncUpload would be to leave the files alone and rely on the control's TemporaryFileExpiration setting to do the job.

My question is this.  Am I missing anything?  Is there any real drawback to using the default App_Data\RadUploadTemp path and relying on automatic deletion of these temp files?  (In fact, why should I even need a Target Folder?)
Sean
Top achievements
Rank 1
 answered on 21 Dec 2018
Narrow your results
Selected tags
Tags
+? more
Top users last month
Simon
Top achievements
Rank 2
Iron
Iron
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Marco
Top achievements
Rank 4
Iron
Iron
Iron
Grant
Top achievements
Rank 3
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Simon
Top achievements
Rank 2
Iron
Iron
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Marco
Top achievements
Rank 4
Iron
Iron
Iron
Grant
Top achievements
Rank 3
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?