Change RadWindow’s Title from Javascript or from Client-side


As per my scenario, I have RadGrid which contains Add and Edit button for Adding new record and Updated existing record respectively. On click of any of these button it will open a RadWindow which contains all my page controls. And I have a requirement to set the Title of RadWindow accordinly. I mean when user click Add button at that time RadWindow’s Title should be Add Mode and for Edit button click it should be Edit Mode.

And I found an easy way to set the Title of RadWindow from client-side, which I am going to share with you.

On Button, I have a ClientClick() event from where I am opening RadWindow, so now I am going to pass the Mode of the RadWindow in which it is going to be opened. Say for example,

OnClientClick=”openFileBuilderDialog(‘Add’);”

Here, openFileBuilderDialog is my Javascript Function, which is shown as below.

function openFileBuilderDialog(Mode) {

var wnd = $find(‘<%=RadWindow1.ClientID %>’);

if (Mode == “View”) {

wnd.set_title(“View File Information”);

}

elseif (Mode == “Edit”) {

wnd.set_title(“Edit File Information”);

}

elseif (Mode == “Add”) {

wnd.set_title(“Add File Information”);

}

wnd.show();

}

 In this function,

  1. Get the RadWindow using its ClientID.
  2. Find the current mode of the RadWindow, which I have supply on appropriate button’s onClientClick event.
  3. Then use the “set_title” method to set the Title that we want.
  4. And finally called, “show” method to open the RadWindow.

That’s it.

If the content page has its own title set in the @Page directive or in the <head> section, this title will override the RadWindow’s one.

To find more methods of RadWindow and examples please follow the below link,

http://www.telerik.com/help/aspnet-ajax/window-programming-radwindow-methods.html

Advertisements

Export to Excel or PDF in RadGrid


Introduction:

RadGrid has a built-in facility to export the grid’s data into different formats like Excel, CSV, Word or PDF and we can export the same as per the system requierement. Here I will show you how to export grid’s data in PDF or Excel format.

Code:

First of all in RadGrid, place the ExportSettings tag as below in the code. Here I have set properties like IgnorePaging equal to True to export all grids data and OpenInNewWindow equal to true to open the export data in a seperate window. Also in ExportSettings section I have defined the width of the PDF page.

<ExportSettingsIgnorePaging=”true”OpenInNewWindow=”true”>

<PdfPageWidth=”1500px”/>

</ExportSettings>

Now in RadAjaxManager of your page add the following event:

ClientEvents-OnRequestStart=”requestStart”

Then, add the following javascript function in your aspx page:

function requestStart(sender, args) {

if (args.get_eventTarget().indexOf(“btnExportToPDF”) > 0 ||

args.get_eventTarget().indexOf(“btnExportToExcel”) > 0)

args.set_enableAjax(false);

}

And then add the command name for the button as like following for PDF or Excel.

CommandName=”ExportToPdf”

and it’s done.

GROUPING in RadGrid


Introduction:

RadGrid supports grouping of items based on the value of a particular column. You can even have multilevel grouping based on different criteria.

To group the data in a grid, specify grouping criteria by setting the GroupByExpressions property of a table view in the grid

Code:

<MasterTableView Width=”100%” CommandItemDisplay=”Top” GroupLoadMode=”Server” ShowGroupFooter=”true”>

<GroupByExpressions>

<telerik:GridGroupByExpression>

<SelectFields>

<telerik:GridGroupByField FieldAlias=”Security” FieldName=”SEC_CODE” SortOrder=”Ascending” />

</SelectFields>

<GroupByFields>

<telerik:GridGroupByField FieldAlias=”Security” FieldName=”SEC_CODE” SortOrder=”Ascending” />

</GroupByFields>

</telerik:GridGroupByExpression>

</GroupByExpressions>

</MasterTableView>

Change RadGrid PageSize Dropdown


Introduction:

Telerik’s RadGrid provides in-built functionality for paging. User have to select the number of records from the Page Size combo box (default is 10, 20 and 50) and selected number of records is going to display in RadGrid. But we can also change the Page Size in combo box as per our requirement. Following is the code to do the same:

Code:

protectedvoid grdViewReport_ItemDataBound(object sender, GridItemEventArgs e)

{

if (e.Item isGridPagerItem)

{

RadComboBox PageSizeCombo = (RadComboBox)e.Item.FindControl(“PageSizeComboBox”);

PageSizeCombo.Items.Clear();

PageSizeCombo.Items.Add(newRadComboBoxItem(“100”));

PageSizeCombo.FindItemByText(“100”).Attributes.Add(“ownerTableViewId”, grdViewReport.MasterTableView.ClientID);

PageSizeCombo.Items.Add(newRadComboBoxItem(“200”));

PageSizeCombo.FindItemByText(“200”).Attributes.Add(“ownerTableViewId”, grdViewReport.MasterTableView.ClientID);

PageSizeCombo.Items.Add(newRadComboBoxItem(“500”));

PageSizeCombo.FindItemByText(“500”).Attributes.Add(“ownerTableViewId”, grdViewReport.MasterTableView.ClientID);

PageSizeCombo.FindItemByText(e.Item.OwnerTableView.PageSize.ToString()).Selected = true;

}

}

Firefox and the FileUpload control in ASP.NET


I’ve been pretty annoyed about the fact that FireFox ignores the width property of the ASP.NET FileUpload control. It doesn’t matter if you set it by CSS or even in JavaScript, Firefox always ignores it and that results in a crippled layout since you have no control over the width of the upload input field. This actually has nothing to do with the FileUpload control, but with the rendered output of that control, which is just a standard field.

Here the width is set to 400px. The FileUpload control renders the Width attribute to the correct CSS style value of 400px at runtime.

FileUpload runat=”server” ID=”txtUpload” Width=”400″ />

But as mentioned, Firefox totally ignores that. Then I remembered a forum thread I read some years ago about a size attribute. The only thing I could find was this list of available HTML attributes, but I gave it a try.

This is what I ended up with. The size attribute actually works in Firefox and IE ignores it, but adheres to the Width attribute instead.

FileUpload runat=”server” ID=”txtUpload” Width=”400″ size=”50″ />

The size attribute determines the number of characters should be visible and then adjusts the width accordingly. It is not the same as setting a maximum length of the file name, so it doesn’t break anything.

You should think that since a size of 50 generates the same width as 400px that you could always just divide the width in pixels with 8 to find the equivalent size. That is not the case. You have to manually adjust every time until you find the right size value that matches the pixel width

Simple way to Show/Hide Filter in RadGrid


Description:

Telerik’s RadGrid provides in-built search functionality. You can find the search functionality at top of the grid just below the header columns. But user should be able to hide the same to save unnecessary space all the time from the grid.

RadGrid Example when Filter is not visible to the user:

Radgrid without Filter

Radgrid without Filter

RadGrid Example when Filter is visible to the user:

RadGrid With Filter

RadGrid With Filter


Code:

First of all in RadGrid’s MasterTableView tag, add following checkbox:

<MasterTableView Width=”100%” CommandItemDisplay=”Top” GroupLoadMode=”Server”>

<CommandItemTemplate>

<asp:CheckBox ID=”CheckBox2″ AutoPostBack=”true” CssClass=”CheckBox” runat=”server”

ForeColor=”White” Text=”Show Filter” />

</CommandItemTemplate>

After that add the ItemCreated event in the RadGrid as following code does:

protected void grdManageTransType_ItemCreated(object sender, GridItemEventArgs e)

{

if (e.Item.ItemType == GridItemType.CommandItem)

{

GridCommandItem commandItem = e.Item as GridCommandItem;

CheckBox chkFilter2 = (CheckBox)commandItem.FindControl(“CheckBox2”);

chkFilter2.AutoPostBack = true;

chkFilter2.ForeColor = System.Drawing.Color.White;

chkFilter2.Checked = grdManageTransType.AllowFilteringByColumn;

//Adding the event handler

chkFilter2.CheckedChanged += new EventHandler(chkFilter2_CheckedChanged);

}

if (e.Item.ItemType == GridItemType.SelectedItem)

e.Item.BackColor = Color.FromName(“#FFEDC1”);

}

In above portion of code we are creating CheckedChanged event of the checkbox. So now create the CheckedChanged event of the checkbox as per following code:

protected void chkFilter2_CheckedChanged(object sender, EventArgs e)

{

grdManageTransType.AllowFilteringByColumn = !grdManageTransType.AllowFilteringByColumn;

grdManageTransType.Rebind();

}

As per the above code portions, we can the checkbox at the top of the RadGrid. On click of that checkbox RadGrid’s filter should be visible on or off.

Count items in Telerik’s RadComboBox


Description:

It is general requirement to show and count number of items in Telerik’s RadComboBox. And we can do that by using a simple javascript function.

Code:

In javasript:

function UpdateItemCountField(sender, args) {

//set the footer text

sender.get_dropDownElement().lastChild.innerHTML = “A total of “ + sender.get_items().get_count() + ” items”;

}

In aspx page:

add footer template as shown below code.

<FooterTemplate>

A total of

<asp:Literal runat=”server” ID=”RadComboItemsCount” />

items

</FooterTemplate>

Compare two data tables in c#


Description:

Comparing two datatable and get the final table with difference in it, this kind of requirement is generally arise generally when we are doing multiple insert or update. I have scenario like get the two different tables data, compare it and if there is difference in output then insert that data into the third table. So use the approach to get the data from database into different table and then insert the difference output using SqlBulkCopy in to the third table.

 

Code:

Following is the code to compare two datatable. Just copy and paste this class into your code and its working.

 

using System;

using System.Data;

 

namespace [Namespace Name]

{

public class CompareDataTables

{

public static DataTable CompareTables(DataTable first, DataTable second)

{

first.TableName = “FirstTable”;

second.TableName = “SecondTable”;

 

//Create Empty Table

DataTable table = new DataTable(“Difference”);

 

try

{

//Must use a Dataset to make use of a DataRelation object

using (DataSet ds = new DataSet())

{

//Add tables

ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });

 

//Get Columns for DataRelation

//DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];

DataColumn[] firstcolumns = new DataColumn[2];

firstcolumns[0] = ds.Tables[0].Columns[1];

firstcolumns[1] = ds.Tables[0].Columns[7];

 

//for (int i = 0; i < firstcolumns.Length; i++)

//{

// firstcolumns[i] = ds.Tables[0].Columns[i];

//}

 

//DataColumn[] secondcolumns = new DataColumn[ds.Tables[1].Columns.Count];

DataColumn[] secondcolumns = new DataColumn[2];

secondcolumns[0] = ds.Tables[1].Columns[1];

secondcolumns[1] = ds.Tables[1].Columns[7];

 

//for (int i = 0; i < secondcolumns.Length; i++)

//{

// secondcolumns[i] = ds.Tables[1].Columns[i];

//}

 

//Create DataRelation

DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);

 

ds.Relations.Add(r);

 

//Create columns for return table

for (int i = 0; i < first.Columns.Count; i++)

{

table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);

}

 

//If First Row not in Second, Add to return table.

table.BeginLoadData();

 

foreach (DataRow parentrow in ds.Tables[0].Rows)

{

DataRow[] childrows = parentrow.GetChildRows(r);

if (childrows == null || childrows.Length == 0)

table.LoadDataRow(parentrow.ItemArray, true);

}

 

table.EndLoadData();

 

}

}

catch (Exception ex)

{

throw ex;

}

 

return table;

}

}

}

 

Code Explanation:

 

  1. CompareTables method is static, so you can call it directly from your class. Just add the appropriate reference.
  2. Pass the two data tables in this method.
  3. Then creates the dataset.
  4. Add two tables into the dataset.
  5. Then important part, define the columns two compare the data table. In my case i just want to check the column 1 & 7. If there is a mismatch between this two then inserts the record. You can modify the code as per your requirement or just uncomment the line above and below my code , which adds all columns.
  6. Creates data relation on that column(s).
  7. Add relation two the dataset.
  8. Create the target or difference table colums
  9. Then load the difference data in it and return the difference table.

CSV or Excel file download in asp.net


Many systems have requirement to download the file in different format like Excel, CSV, etc. For that we are using HttpContext.Current.Response class in System.Web namespace.

Following is the code to download the CSV file:

try

{

HttpContext.Current.Response.Clear();

HttpContext.Current.Response.ClearHeaders();

HttpContext.Current.Response.ClearContent();

HttpContext.Current.Response.AddHeader(“content-disposition”, “attachment; filename = FileName.csv”);

HttpContext.Current.Response.ContentType = “text/csv”;

HttpContext.Current.Response.AddHeader(“Pragma”, “public”);

Response.WriteFile(Server.MapPath(“~/ExcelFiles/FileName.csv”));

HttpContext.Current.Response.End();

Response.Flush();

}

catch (Exception ex)

{

throw ex;

}
We can download the excel file by just changing the HttpContext.Current.Response.ContentType to Application/x-msexcel.

Prevent duplicate entry when using SqlBulkCopy


As we know, the fastest way to insert data in Database is to insert bulk data. SqlBulkCopy Class in System.Data.SqlClient Namespace provides simplest and fastest way to copy large amounts of data to SqlServer. Instead of inserting all data row by row, SqlBulkCopy process all data at once, thus making the insertions fast.

An example should be given below:

public void CopyData(DataTable TableToCopy, string SqlTableName)

{

        SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["conStr"].ToString());

if (con.State == ConnectionState.Open)

{

con.Close();

}

con.Open();

SqlBulkCopy bc = new SqlBulkCopy(con);

bc.ColumnMappings.Add(0, 0);

bc.ColumnMappings.Add(1, 1);

bc.ColumnMappings.Add(2, 2);

bc.ColumnMappings.Add(3, 3);

bc.ColumnMappings.Add(4, 4);

bc.ColumnMappings.Add(5, 5);

if (SqlTableName != “DBTable”)

{

bc.ColumnMappings.Add(6, 6);

bc.ColumnMappings.Add(7, 7);

bc.ColumnMappings.Add(8, 8);

}

bc.DestinationTableName = SqlTableName;

bc.WriteToServer(TableToCopy);

con.Close();

}

Here, WriteToServer() method, do bulk insert in database. So SqlBulkCopy is very useful in the case that when we want to insert number rows in the Database at the same time not one by one. But in some situation we are in need to check for Duplicate records while doing multiple insertion. But SqlBulkCopy does not provide any built-in method or event to do that.

One possible solution is to make the column(s) of the table unique. And for that we have to create a Index on the Table with column names that we want to check for Uniqueness.

Following is the example for the same:

 

CREATE INDEX myIndex on [Table Name]

(

[Column name1],  [Column name2], ..

)

WITH (IGNORE_DUP_KEY = ON)

 

This index would create a unique index for the columns specified and it checks automatically that if any duplicate rows are when we do BulkCopy. If yes then do nothing else inserts bulk data into the Database.