Advertisements
Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Wednesday, March 12, 2014

// // Leave a Comment

Print GridView only in ASP.NET

Hi,

Lets come back to ASP.NET tips and trick series. We are once again going to learn new trick related to GridView. Previously I have posted following articles related to GridView.

Requirement

Suppose, you have a page where you are displaying any kind of data to user. You want to add a functionality to print these records. But problem with Browsers Default Print options (Ctrl+P) is that, it will print whole page. All header images, footer, sidebar and colors will printed, which is not required. You have two options, either create a new page for print view and redirect user to that page or just print the required area, in our case it is GridView. 
Most of developer working in a web applications have MasterPage for their web-application. MasterPage are similar to templates in normal HTML having some advanced functionality and customized code for maintaining easier and common look of website or application.
Lets have a look at below screen to make our requirement more clear.

Code for Default.aspx

This is the code for GridView.
   <asp:GridView runat="server" ID="gvProducts" AutoGenerateColumns="false" AllowPaging="false" AlternatingRowStyle-BackColor="Linen" HeaderStyle-BackColor="SkyBlue" Width="100%" OnPageIndexChanging="gvProducts_PageIndexChanging" EmptyDataText="Sorry! No Products to List. First Add from Add Product Link.">
                    <Columns>
                        <asp:TemplateField HeaderText="Product ID">
                            <ItemTemplate>
                                <asp:Label ID="lblProductID" runat="server" Text='<%#Eval("ProductID")%>' ToolTip="ID of Product as stored in Database."></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Product Name">
                            <ItemTemplate>
                                <asp:Label ID="lblProductName" runat="server" ToolTip="Name of Product" Text='<%#Eval("ProductName")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Brand">
                            <ItemTemplate>
                                <asp:Label ID="lblBrandName" runat="server" ToolTip="Brand of Product" Text='<%#Eval("BrandName")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Category">
                            <ItemTemplate>
                                <asp:Label ID="lblProductCat" runat="server" ToolTip="Category of Product" Text='<%#Eval("CategoryName")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="In Stock">
                            <ItemTemplate>
                                <asp:Label ID="lblProductinStock" runat="server" ToolTip="Quantity available in Stock"
                                    Text='<%#Eval("UnitsInStock")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

Code for Default.aspx.cs

We do not have much more at backend, we are just going to bind data to GridView.
 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConToStore"].ConnectionString);
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Products,Brands,Category where Products.BrandID=Brands.BrandID and Products.CategoryID=Category.CategoryID", con);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            gvProducts.DataSource = ds.Tables[0];
            gvProducts.DataBind();
        }
    }

Printing Page.

Lets press Ctrl+P key combination to print page, before printing see the Preview.

Printing GridView Only

We need to make following change to print GridView only. Lets start with HTML.
Wrap the GridView inside a Table or Panel. I am using Table. You can also go with Panel.
  <table width="70%" id="pnlGridView" runat="server" align="center" class="ContentTable">
        <tr>
            <td colspan="2" align="center">
                <h1>All Products in Store</h1>
            </td>
        </tr>
        <tr>
            <td> </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:GridView runat="server" ID="gvProducts" AutoGenerateColumns="false" AllowPaging="false" 
    AlternatingRowStyle-BackColor="Linen" HeaderStyle-BackColor="SkyBlue" Width="100%" 
    OnPageIndexChanging="gvProducts_PageIndexChanging" 
    EmptyDataText="Sorry! No Products to List. First Add from Add Product Link.">
                    ...............
     .............
                </asp:GridView>
            </td>
        </tr>
        <tr>
            <td align="right">
                <asp:LinkButton ID="lnkPrint" runat="server" ToolTip="Click to Print All Records" Text="Print Data" OnClick="lnkPrint_Click"></asp:LinkButton>     
                <asp:LinkButton ID="lnkExportAll" runat="server" ToolTip="Export this List" Text="Export to Excel" OnClick="lnkExportAll_Click"></asp:LinkButton>
                     
                <asp:LinkButton ID="lnkAddNew" runat="server" ToolTip="Add New Product"
                    Text="Add New" OnClick="lnkAddNew_Click"></asp:LinkButton>
            </td>
        </tr>
    </table>
Now just add following JavaScript function in head section and assign that function to Print linkbutton.
    <script language="javascript" type="text/javascript">
        function PrintPage() {
            var printContent = document.getElementById('<%= pnlGridView.ClientID %>');
            var printWindow = window.open("All Records", "Print Panel", 'left=50000,top=50000,width=0,height=0');
            printWindow.document.write(printContent.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
        }
    </script>
Now lets click on Print Link button which we have created. Following will be output for above code.

Bingo! It was the requirement.
Hope you enjoyed reading. If you have any feedback or suggestions, please send us as comment or using contact options. Keep sharing.
John Bhatt
Read More

Thursday, January 30, 2014

// // Leave a Comment

Adding CommentLuv in Blogger

Hi,
Once again, a new post for all blogger friends. As you are aware, the quality back-link has great value in website ranking. Most of blogger want to increase their ranking on various measurement tools and follow many tricks. They use many tools available over internet.

CommentLuv / IntenseDebate

In case of blog, one of the most used and must have feature is comment system. You should know what your visitor think about your post, so there should be a commenting system which is powerful, can protect spam, give you ability to control them and other administration features. Disqus is one of the most used commenting system. Another powerful and most used commenting platform is CommentLuv from IntenseDebate. This is an Automattic product. Automattic is company which made WordPress, JetPack, Askimet and other web products which are used by approx 70-80 % of web-masters. So by default, CommenLuv comes with Askimet spam protection which is actually powerful and blocks spam without any extra effort. Best thing about IntenseDebate is it is free. We will learn how to integrate CommentLuv comments with blogger template so that our blog can display and work with IntenseDebate commenting system.

Procedure

  1. Open http://intensedebate.com/signup.
  2. Fill the required details, If you have already got a WodPress.com account, you can login using WordPress API.
  3. If you are registering for first time, you must confirm your email id. Check you inbox and confirm email.
  4. Login to intensedebate.com using your username/password.
  5. Click on Sites menu and choose Add Blog/Site or navigate to https://intensedebate.com/install

  6. Put the domain of your blog. They have great support for Blogger. You can put your custom domain or blogger.com domain name and click next.
  7. This is choose your platform screen. Currently they have automated tools for WordPress.org, TypePad, tumblr and Blogger. Click on Blogger button. Remember, classic blogger is not supported.
     
  8. Now the next step is to login to blogger. Remember, you are using Modern version of Blogger. Navigate to Template section.
  9. Click on Backup/Restore button on right top corner. 
  10. You will be asked to download the template or upload. Click on "Download Full Template" button.
  11. Save this XML file (blogger template) to hard disc. Now navigate back to IntenseDebate website.
  12. Next screen is installer screen for blogger. There are some steps. They will ask you either you want to put commenting system in all posts or in new posts only. Selecting All posts will delete all older comments made using Blogger comment system. So this is not recommended if you have lots of comments in website earlier.
  13. There is a File Upload button in Step 5, click on button, upload your newly saved XML template. The rest is on IntenseDebate.
  14. Once file is uploaded, they read content and place all settings and codes themselves in template and write all code in a textbox.
  15. Now copy all that text and navigate to blogger. Click on Edit HTML button. 

  16. Replace all content in editor and click on Save Template button. Your all existing script customizations, texts, widgets will remain same and as per your settings, you can see the IntenseDebate commending system enabled in your blog posts.
You have successfully completed the installation of IntenseDebate commending system in your blogger powered blog. Leave feedback about your reading experience. Your feedback will help us to improve.

Thanks for reading.
Read More

Thursday, January 23, 2014

// // 3 comments

RichTextBox in a single textbox among multiple TinyMCE

Hi,
Some time ago, I have written an post about integration of TinyMCE editor in ASP.NET website. The same was also published in CodeProject and most visited article of mine. While answering comments there, I got a request from one of reader.
His question is, "I have used TinyMCE Rich TextBox in my application but in my web form i have mulitple mulitiline TextBox. what I want that Rich TextBox should be bind to only one text box not all TextBoxes."

Situation

So the solution is here. Lets create a scene as below.

Here we have to convert TextArea for about to Rich Text Editor (WYSIWYG). Lets view source code of above design. I have tried to use simple HTML5 tags. So that other users can also get advantage of this tutorial.
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title>Rich Text Editor in Single TextArea among many</title>
</head>
<body>
    <form id="form1" runat="server">
        <h1>Rich Text Editor in Single TextArea among many</h1>
        <fieldset>
            <legend>Profile Update</legend>
            <p>
                <label>Name</label>
                <input type="text" id="txtName" runat="server" />
            </p>
            <p>
                <label>Gender</label>
                <input type="radio" name="Gender" id="radioMale" runat="server" value="Male" />
                <input type="radio" name="Gender" id="radioFemale" runat="server" value="Female" />
            </p>
            <p>
                <label>Email ID</label>
                <input type="text" id="txtEmail" runat="server" />
            </p>

            <p>
                <label>About</label>
                <textarea rows="5" cols="50" id="txtAbout" class="Editor" runat="server"></textarea>
            </p>
            <p>
                <label>Remarks</label>
                <textarea rows="2" cols="50" id="txtremarks" runat="server"></textarea>               
            </p>
            <p>
                <asp:Button ID="btnSubmit" Text="Submit" runat="server" />
                <input type="reset" value="Clear Form" runat="server" />

            </p>
        </fieldset>

    </form>
</body>
</html>
Here we are using TinyMCE version 4.0.xx. This version is major upgrade and has completely different look and internal architecture compared to version 3.xx. So here is some difference in its integration.
If you are not familiar with this process, please read our previous post, that will describe you about Copying required files in project directory and inserting script in more details. Insert below code before closing of head tag in your HTML page.
<script src="script/tinymce/tinymce.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        tinymce.init({
            selector: ".Editor",
            theme: "modern",
            plugins: ["lists link image charmap print preview hr anchor pagebreak"],                        
        });
    </script>
</head>

Notable

Notable and new code in above integration script is selector tag. This is new included tag in TinyMCE version 4.0.xx. This gives us below options.
Do not forget to change the path to Script as per you folder structure.
  • selector : "textarea"

    : This option will convert all TextAreas in visual editor. 
  • selector : "textarea.Editor"

    : This option will select all TextAreas with CSS Class Editor applied.
  • selector : h1.Editor

    or div.Editor : This option will change this to Inline editor for H1 or DIV with CSS class name of Editor.
As you see in code of scene designed above. you can see that we have applied class Editor which we did not created in any css file to one of the TextArea. Here we used this method.

Older Version

If you are working with TinyMCE version 3.xx, here is the code to be inserted in Head section of HTML page. 
 <script type="text/javascript" 
src="script/tiny_mce/tiny_mce.js"></script>
    <script type="text/javascript" language="javascript">
        tinyMCE.init({
            // General options
            
            // mode: "textareas",
    
    // Set mode to Exact.                       
            mode: "exact",  
            
            // Write the name of ID of TextArea where you want editor to appear in element property.
            elements : "txtRemarks", 

            theme: "advanced",
            plugins: "pagebreak,style,layer,table,save,
            advhr,advimage,advlink,emotions,iespell,inlinepopups",
           
        });
    </script>

Output


Now, the output of above work is below.
Its perfect.
If you find this article helpful, drop a comment or share with your friend.
+John Bhatt

Read More

Monday, January 20, 2014

// // Leave a Comment

Add SyntaxHighlighter to your blog

Hi,
This post is about all Blogger, who write code and want to share their code on their website of community. If the code is in HTML, JavaScript or other browser understandable language, browser renders and displays output instead of code. Visitor will see nothing instead of garbage while in case of other programming languages, formatting, wrapping, alignment and other styles are lost and user is confused about its actual structure.

To remove this we are going to implement SyntaxHighlighter functionality in our blog. Here we will work with Blogger blog, the method is same for html webpage. SyntaxHighlighter is a JavaScript library written by Alex Gorbatchev in year 2004. Because of its feature, it becomes more famous and still maintained at his website.

Procedure

Include the JavaScript files in head section of your website code using External Script linking method. For blogger, open your Template and search for closing of head tag.
</head>
Then paste these links for including files. You can also download latest version from http://alexgorbatchev.com/SyntaxHighlighter/ and use in your own web host also but blogger does not allow you to upload JavaScript files.
<link href='http://www.johnbhatt.com/SharedResources/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://www.johnbhatt.com/SharedResources/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script src='http://www.johnbhatt.com/SharedResources/scripts/shCore.js' type='text/javascript'/>
<script src='http://www.johnbhatt.com/SharedResources/scripts/shBrushCss.js' type='text/javascript'/>
<script src='http://www.johnbhatt.com/SharedResources/scripts/shBrushJScript.js' type='text/javascript'/>
<script src='http://www.johnbhatt.com/SharedResources/scripts/shBrushXml.js' type='text/javascript'/>
<script src='http://www.johnbhatt.com/SharedResources/scripts/shBrushCSharp.js' type='text/javascript'/>
<script src='http://www.johnbhatt.com/SharedResources/scripts/shBrushPhp.js' type='text/javascript'/>
<script src='http://www.johnbhatt.com/SharedResources/scripts/shBrushSql.js' type='text/javascript'/>
You need to include file that you are going to use. Above links are of default CSS style sheets and CSS, JavaScript, XML, CSharp, Php, SQL languages. XML includes HTML, XHTML and XML. Next step is to write a simple JavaScript function and tell browser to run the code.
<script type='text/javascript'>
  SyntaxHighlighter.config.bloggerMode = true;
  SyntaxHighlighter.all();
</script>
Now you are all set to write code in your post. Open editor in HTML mode and write code inside HTML pre (Pre formatted) tag with a class attribute (stylesheet identifier) defining its programming language. Lets see below example to get clear view. 
<pre class="brush:html"> // Replace your brush with your own.
<html>
<head>
<title>Adding SyntaxHighlighter to Blogger Blog by John Bhatt</title>
</head>
<body>
Body can contain codes also, that too highlighted and formatted, well aligned. Congrats.
</body>
</html>

</pre>
Important: You may have to change html tags < and > to html ISO codes. Simply open any code editor Notepad will also rock. Open Replace box using Ctrl+H shortcut or from Edit menu and search for < (Less than) and replace with <. Once again search for > (Greater than) and replace with > using Replace all method. This will not produce any error in case of HTML and other html tags.

Output is in your page. We have done this using this plugin. You have many themes (styles) to make it look better. You can include CSS as per your requirement. 
Do not forget to share and post suggestions.
+John Bhatt 
Read More

Monday, December 16, 2013

// // Leave a Comment

Conversion Tool for all Number System

Hi,

If you are student of computer science, you must have required this feature sometime. You have to study and make calculation on different number systems. Mostly on Binary, Octal or Hexadecimal and Decimal number system are most used in Computer programming language.
We have collected and uploaded a application to help you. This will calculate the number of your choice to another system and also describe how this happened and actual answers.

As you can see in above snapshot, we tried to convert Decimal Number 100 to Binary number system (that is Base: 2). Answer is 1100100 but we have "Explain Answer" button, which explained the each and every step.

Go to Number Conversion Tool.

All the Best.
+John Bhatt 
Read More

Sunday, September 29, 2013

// // Leave a Comment

Redirect User to same Location on Different Domain

Hi,

Recently, I have changed my Blog address. Due to this, I have to face a lot of Traffic Loss.

My situation was, I have a Blogger blog and a domain. A lot of Links have been shared and If I change the Blog address and create a Permanent Redirect by changing DNS, but existing Bookmarks and Shared Links will not load properly. So, I kept the Existing Domain running and created a New Blog. Exported Template and Blog, Uploaded both to New Domain and just keep both domain running up. Now I have to redirect all visitors to Previous Domain to New Domain.


Here I came with a solution.

I have created a Simple JavaScript function.

<script>
    function redirect()
    {
    //You change your Domain name just in place of "http://www.pyarb.com".
    
  window.location = "http://www.pyarb.com/" + window.location.pathname;
    }
</script>

Description:

1. windows.location - This will set the Location of Window (i.e. Address of Browser.)
2. "http://www.pyarb.com" - This is your New Domain. Where you have kept all File structure same. Means Links are same for All files except Domain Name.
3. windows.location.pathname - This will get the Path of Window Location (i.e. Address of Browser except Domain Name.)

Then Executed this function on PageLoad event.

......
.......
</head>
<body onload="redirect();">
.........
.........

That's It. Your location remains same.

Enjoy,
+John Bhatt 
Read More

Thursday, September 6, 2012

// // 1 comment

Rich Text Editor with ASP.NET


Introduction


As we know, ASP.NET lack a Control, that we need most, RichText Editor. 

If you are trying to create a application or website with Admin Panel or Blog or Forum Website or something such project for Web in ASP.NET platform, we need RickText Editor. 

To overcome from this, we can use Many open source JavaScript based editors, like Tiny MCE, FCKEditor, etc.

Content:

In this Article, we would learn how to Implement Free RichText Editor into ASP.NET website. We are using TinyMCE editor here.

We are using TinyMCE, which is One of most popular and Open Source project. Download latest version of TinyMCE from Download Page, and Extract the Zip File.


Browse the Extracted Location and go to ..\tinymce_3.5.6\tinymce\jscripts folder.

Now Copy the tinymce folder from above Location to your Solution in Visual Studio.


Add a Page where you want to Implement RichTextbox and Design the Page.


Now lets Move to Topic. How to Add TinyMCE in Page and Richtext box Control placed for Content of Blog in above sample.

Insert JavaScript file tiny_mce.js in Web Page and some also initialize this function.

This Code into head Section.

 
<script type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
    <script type="text/javascript" language="javascript">
        tinyMCE.init({
            // General options
            mode: "textareas",
            theme: "advanced",
            plugins: "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups",
        });
    </script>
Note: You can so many settings, look in Samples and Help Doc of TinyMCE.

Now Run the Page. Look, how it looked.



Without any additional Practice, our TextBox with Multiline turned into RichText Editor.

Now, its ok as per Requirement. No, when you will send Command to Server, it will return Error Like below.


We have to add just One Line of Code in Web.config file and one property in Default.aspx form (Page with Rich Text Editor).

That is : 

in web.config:
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <httpRuntime requestValidationMode="2.0"/>
  </system.web>
</configuration>

and in Page directive:

ValidateRequest = "false"
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false" %> 

Now, you can save the Data in Database, Do postback, retrieve same in Rich Text box and do anything you want.

Conclusion


IT is Jugad. So enything is possible here. Don't be worry about things that are not available. Just modify and make use of things those are available. Tiny MCE is one of the most known and Popular Rich Text editor (WYSIWYG).

You can find many more articles written by me on Dotnetspider also. Have a look at them.
You can add me to your Circle on Google+ at +John Bhatt

Hope this will be helpful to you. 
Read More

Friday, June 29, 2012

// // Leave a Comment

Opening a Webpage according to Textbox Value

Hi,

Today I am going to tell you, how to Open a Web Page according to TextBox Value in ASP.NET. You can implement same in Plain HTML Page. This will use a Simple JavaScript Function which we will create according to our need.
Lets Look at the Code. We are using ASP.NET Ajax AutoCompleteExtender for more enhancement in Code (This will only work in ASP.NET).
Code for ASPX Page (HTML Design Part - ASP.NET)

 






If you are using Plain HTML, Just use this code.
 


Now JavaScript Code which is Inserted Directly in Head Section. (JavaScript)





Now code for C# page if you are using AutoComplete Extender.
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]

public static string[] GetCompletionList(string prefixText, int count, string contextKey)

{

string[] Brands = { "hp", "acer", "dell", "lenovo" };

return (from m in Brands where m.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();

}
Enjoy...
Read More