Advertisements
Showing posts with label CodeProject. Show all posts
Showing posts with label CodeProject. 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

Saturday, February 1, 2014

// // 9 comments

HTTP Error 500.23 - Internal Server Error in Visual Studio 2013

Hi,

I have installed Visual Studio 2013 in my system. Due to some problems, I got the release after few months. So I was excited to use it and taste its new features. One thing I like about Visual Studio 2013 is it has a theme which turns it like Visual Studio 2010, which was simply awesome.

HTTP Error 500.23

I opened a existing website and tried to run that website. The website was using ASP.NET framework 4.0. However, the website has no errors and working fine in previous version of Visual Studio. But when I started with debugging (F5), this produced following error.
HTTP Error 500.23 - Internal Server Error

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

Solution

I can not understand the problem in a single view, as it suggest to change some configuration different methods in things you can try section. While there is not handler configured in web.config system for Web Server. Instead there was no system.webServer node.
So I searched in Internet and found some suggestion to make changes in Application Pool setting in IIS Manager. I tried that too but that was also a failed trial. Then suddenly I got a click in my mind and tried a setting which worked immediately.
How can the change done in Internet Information Service (IIS) Manager reflect in Development server. When we run the website from Visual Studio it loads in development server instead of IIS. So we have to make change in Development server which will automatically solve all the problems.
I thought, some time you might have same situation and solution must be there before problem.
Step 1: Open visual studio and click in the name of Website Project currently opened. Click on Property pane
.
Step 2: Double click on Managed Pipeline Mode. This will toggle between Classic and Integrated Mode. You have to switch to Classic mode because the error was "An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode"
.
Now hit the F5 button, here goes output as usual.

You have solved the problem. If you find this post helpful, do not forget to share with friends or simply say thanks in comment below or you can share your feedback by leaving comment below.
+Prithvi Raj Bhatt 
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

Thursday, January 16, 2014

// // 1 comment

Export to Word from GridView in ASP.NET

Hi,

Today, I am going to continue our GridView tricks series ahead and posting a nice and useful feature. For all list of GridView articles we have written here, you can search for GridView in search box. As I have previously written about Exporting data to Excel from GridView, this is about exporting GridView to Microsoft Word which is another most used document format and needed in most cases.
Lets create a design as below.
I have just dragged and dropped a gridview control and used autoformat to make GridView look some better. 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            text-align: justify;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1 class="auto-style1">
        Export to Word 
    </h1>
        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" Width="590px">
            <FooterStyle BackColor="White" ForeColor="#000066" />
            <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
            <RowStyle ForeColor="#000066" />
            <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#007DBB" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#00547E" />
        </asp:GridView>
        <br />
        <asp:Button ID="Button1" runat="server" Font-Bold="True" OnClick="Button1_Click" Text="Export to Word" />
    </div>
    </form>
</body>
</html>

Now bind data to this gridview from backend.

 protected void Page_Load(object sender, EventArgs e)
    {
        string ConString = "Server=.\\sqldb;database=Store;integrated security=true;";
        SqlConnection con = new SqlConnection(ConString);
        string QueryText = "SELECT DISTINCT Products.ProductName, Brands.BrandName, Category.CategoryName, 
Products.UnitPrice, Products.UnitsInStock from products,brands,Suppliers,Category 
where Products.BrandID=Brands.BrandID and Products.CategoryID=Category.CategoryID;";

        SqlDataAdapter adp = new SqlDataAdapter(QueryText, con);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();
    }
Let's view page in Browser. You must see data from your database. Mine query has resulted below data in grid.
Perfect, now its time to do the important stuff. Lets write code for Export Button. Double click in button to create a method and automatically bind event with control. Now write below code in backend.

 public override void VerifyRenderingInServerForm(Control control)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment;filename=Products.doc"));        
        Response.ContentType = "application/vnd.ms-word ";
        StringWriter WriterForWord = new StringWriter();
        HtmlTextWriter HTMLWriter = new HtmlTextWriter(WriterForWord);
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        GridView1.RenderControl(HTMLWriter);
        Response.Output.Write(WriterForWord.ToString());
        Response.Flush();
        Response.End();
    }

Its time to check our code, Click on Export to Word button. I have attached snapshot of Firefox because it prompts user.
You can save file or just click on Open with your word processor software. I am using Microsoft Word here.
Did you read our previous Export to Excel tutorial? What are the similarities between exporting to Word and Excel?
I am leaving with a question, if you know, leave a reply below.
Thanks for reading . Do not forget to say thanks or plus1 or provide feedback.
+John Bhatt 
Read More

Wednesday, January 15, 2014

// // Leave a Comment

Custom Message when no rows in GridView

Hi,
Lets get back to ASP.NET series and work with GridView once again. We have previously done following jobs with GridView.
You are suggested to read above posts before reading this post.

Objective

 If you are a ASP.NET developer, you have to work with GridView control every day. In a SQL powered website, this is a must have control and almost every developer uses it. It grabs data from Data Source defined and show in tabular format with added CSS and other features.
But some features are disabled by default, you have to turn them on. Suppose you have no data to display, GridView control simply disappears, your user will not see any design or message. To overcome this, GridView control has a builtin feature that can tell user that there is no data in that case, we have to just turn it on and customize message.

Design

Lets see a below design.
Lets create a SQL Table as below structure.
--Create a Database for temporary purpose.
CREATE DATABASE TestDatabase;
--Use newly created database for forther queries.
USE testdatabase;
--Create a Simple table with 4 columns
CREATE TABLE TestTable
(
StudentID int PRIMARY KEY Identity(100,1),
StudentName nvarchar(150),
CourseName nvarchar(100),
ContactDetails nvarchar(500) 
);
And bind gridview with above table which is empty. Double click on any empty location of Page to go to Page_Load event or just press F7 key to switch between aspx page and Code behind page.
Code as below is suffcient for this task, you can also go for graphical method.
//Include namespaces for DataTable and SQL access.
using System.Data;
using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)
    {
        string ConString = "Server=.\\sqldb;database=testdatabase;integrated security=true;";
        SqlConnection con = new SqlConnection(ConString);
        SqlDataAdapter adp = new SqlDataAdapter("SELECT * from TestTable", con);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();
    }
Lets view it on browser.
  • Question : Where is our GridView? We have added and binded it with database. 
  • Answer   : Oh! There is no data in table, so it is blank and hidden to free space.  
  • Question : Does user knows about this?
  • Answer   : No, every user might not be familier to ASP.NET and web programming. He will just think some fool has designed page and he forgot to add content in this place. 
So the requirement is to tell user in a familier language that there is no data. So that he can tell you are smart and feel happy with website/application. 

Putting Error Message

We have a attribute property of GridView called EmptyDataText inside Appearance section. Lets have a look at below screenshot.
You can write your error message in case of Empty Data in that textbox or you can simply add a property in GridView code and write its value as below.
<asp:GridView ID="GridView1" runat="server"  
    EmptyDataText="Sorry! There is no data present. Please add or wait for others to enter record."
    EmptyDataRowStyle-ForeColor="Red"  EmptyDataRowStyle-BorderStyle="Solid">

I have added two more attributes named EmptyDataRowStyle-ForeColor which will assign "Red" color as its text color and also EmptyDataRowStyle-BorderStyle attribute which will put a solid border around table. Now save page and view in browser. This will display output as below.


I think this is the actually we wanted to do. Now lets add a record in SQL table and refresh page.
INSERT INTO TestTable VALUES ('John Bhatt','M. Tech','john@johnbhatt.com');

Conclusion

So we can say that, adding EmptyDataText and style for EmptyDataRow does not affect any or our design for normal view.

Do not forget to share and like if you found this helpful. Saying a thank will encourage me. If you find are mistakes and errors in above code and tutorial, please report by leaving a comment here. We will try to rectify and help other members.

+John Bhatt 
Read More

Wednesday, December 4, 2013

// // 2 comments

GridView with Fixed Header & Scroll Bar

Hi,

In previous posts, I have completed two important topics of GridView.
  1. Paging in GridView
  2. Scroll Bars in GridView
Today, Lets learn another new and important trick with GridView, i.e. Fixed Headers. When we have to scroll through GridView, then there is must have feature that is Fixed Header. On recent post I have written about Fixed Headers in Excel, did you get chance to read them. We are doing exactly same task here. But here we do not have "Fix Pane" as in Excel anywhere. Lets do this with simple CSS and some enhance with code-behind.

Also, Today I am using Manual method of GridView creation, in previous demos and posts, I have used Drag & Dropped GridView control. Today here is manually coded GridView. 
Lets see code for ASPX page.
            <h2 align="center">GridView with Fixed Header</h2>
            <div style="height: 400px; overflow: auto" align="center">
                <asp:GridView ID="gvDistricts" runat="server" HeaderStyle-CssClass="FixedHeader" HeaderStyle-BackColor="YellowGreen" 
                    AutoGenerateColumns="false" AlternatingRowStyle-BackColor="WhiteSmoke" OnRowDataBound="gvDistricts_RowDataBound">
                    <Columns>
                        <asp:TemplateField HeaderText="District ID" HeaderStyle-Width="80px" ItemStyle-Width="80px">
                            <ItemTemplate>
                                <asp:Label ID="lblDistID" runat="server" Text='<%#Eval("DistID")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="District Name" HeaderStyle-Width="120px" ItemStyle-Width="120px">
                            <ItemTemplate>
                                <asp:Label ID="lblDistName" runat="server" Text='<%#Eval("DistName")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <Columns>
                        <asp:TemplateField HeaderText="Description" HeaderStyle-Width="200px" ItemStyle-Width="200px">
                            <ItemTemplate>
                                <asp:Label ID="lblDistDesc" runat="server" Text='<%#Eval("DistDesc")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>

In above design, Notable code is style for DIV which will make this GridView scrollable if its height exceeds than 400px. Another notable code is HeaderStyle-CssClass="FixedHeader". This line of code will apply a custom CSS Class named FixedHeader which we will create in while to do the task required. Before doing this lets bind this GridView with Data. Lets move to Back-end.
I am using data from a SQL table, which simply contains, DistrictID, DistName, DistDesc as its field and approx 25 records filled.

We have nothing to do more here. So simply write the databind code inside Page_Load Event.

protected void Page_Load(object sender, EventArgs e)
    {
        string ConStr = "Data Source=.\\sqldb;Initial Catalog=ShikshaNet;Integrated Security=True";
        if (!IsPostBack)
        {
            string Query = "SELECT * FROM Districts";
            SqlConnection con = new SqlConnection(ConStr);
            SqlDataAdapter adp = new SqlDataAdapter(Query, con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            gvDistricts.DataSource = dt.DefaultView;
            gvDistricts.DataBind();
        }
    }
Now lets loot at browser to know how it looked.
 Perfect as designed. Lets scroll it and look for headers.

Oh! no, Headers are not visible. Lets start what we left at beginning. Add some style to GridView. Just navigate inside Head section of HTML and then add below code. This is stylesheet, you can customize as your requirement, but remember to change your Class name in GridView also if you are changing class name here.
<style type="text/css">
        .FixedHeader {
            position: absolute;
            font-weight: bold;
        }      
    </style>

OK, Lets refresh browser to see the changes.
 On scrolling,
Perfect, Headers are on top. But there is some problem. If you noticed, First record of GridView is not visible. It has dis-appeared. To make that record visible. Lets use a trick. Write some code in RowDataBound Event of GridView.

   protected void gvDistricts_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex == 0)
                e.Row.Style.Add("height", "50px");
        }
    }
We just told Server to add some space if the RowIndex is 0 means first row of GridView should have atleast double space so that the value can be visible.
Lets see the output.

Bingo! You have created a perfect and complete GridView with Fixed Headers. You can use this code and it works fine even used with Paging across multiple browsers.

Thanks to +Amit Jain for the Top row fix which he has posted in his blog at Scrollable GridView With Fixed Headers Asp.Net.
If you found this post useful or helpful, or you have some suggestions to make, please post as comment or send me message on Google+ also.
+John Bhatt 


Tags: Gridview, ASP.NET, Tutorials by John Bhatt, P.Yar.B Complex, Fixed, Freeze, Headers, CSS, C-Sharp, Scrollbar, Tricks
Read More

Wednesday, November 13, 2013

// // Leave a Comment

Pagination in GridView

Hi,
Simply we will learn here how to Apply Pagination in ASP.NET GridView Control.
Directly to Code:
In ASPX page, enable paging in GridView.

<asp:GridView ID="gvAllPOD" runat="server" AutoGenerateColumns="false" 
AlternatingRowStyle-BackColor="LightSeaGreen" HeaderStyle-Font-Bold="true" 
AllowPaging="true" PageSize="20" onpageindexchanging="gvAllPOD_PageIndexChanging">

In Above Code, we Automatically Generated Columns from DataSource Then AllowPaging = True, so that GridView Data can be Paged, Also We defined PageSize that what amount of Records whould display in Page.
To Apply Pagination, RIght Click in GridView and Choose Properties > Events. Choose PageIndexChanged event and Place Following code in ASPX.CS Page.
protected void gvAllPOD_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvAllPOD.PageIndex = e.NewPageIndex;
        BindGVAllPOD();
    }

Now Check on your Page. What is Happening on Clicking Page Number. You can comment if some queries on above code.
John Bhatt
Glad to Know, Free to Share

Tags: Pagination, Paging, GridView, ASP.NET, Disply data in Page, Tutorial bt John Bhatt
Read More

Monday, October 28, 2013

// // Leave a Comment

GridView with Scrollbars

Hi,

Today I am here to share something to you. This is simpler as never but I bet, you are searching for this since long.

If you have developed any web application using ASP.NET, you must have used GridView, if you are beginner and learning ASP.NET, this will tell you how to make GridView scrollable. As we know, we can Paginate data in GridView, but putting a Scrollbar is really confusing as it is not in default properties of GridView control.

Lets design a web form and insert a GridView. I am using no designs and just a form and dragged and auto formatted GridView control in this tutorial.

Lets see the code for this web form.
 <div align="center">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="DistID" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" Height="240px" Width="667px">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:BoundField DataField="DistID" HeaderText="DistID" InsertVisible="False" ReadOnly="True" SortExpression="DistID" />
                <asp:BoundField DataField="StateID" HeaderText="StateID" SortExpression="StateID" />
                <asp:BoundField DataField="DistName" HeaderText="DistName" SortExpression="DistName" />
                <asp:BoundField DataField="DistDesc" HeaderText="DistDesc" SortExpression="DistDesc" />
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" SelectCommand="SELECT * FROM [Districts]"></asp:SqlDataSource>
    </div>

I have bind data from one of my projects, this is schema of Address and table is District List. Lets run the Web form, our output is:

This is how it will list record and entire page will have GridView data. To fix this, I have added just a style tag to Div and some code inside that tag. Below is code.
..style="height:400px; overflow:auto"..
//You can change overflow:auto to overflow:scroll but that will show both Scrollbar and always. Above will show Vertical Scrollbar only when the Height of GridView exceeds than assigned height.

After adding above code, I refreshed the browser, Now this is the new and required layout of GridView.

You can download the source code from JohnBhatt.com for free.
Enjoy. Till then subscribe our feeds and get updated. You can also drop a comment below to suggest us improving. 
Read More

Sunday, October 7, 2012

// // 2 comments

Accordion Panel with CSS

Greetings from John!,
Hope you all are enjoying.
Friends I am back with a new thing for you. Today I am going to show you, how to make a Good Accordion Panel.

Do you know, what is Accordion Panel? You must have seen some tables or Div's in website, that are collapsing and expanding on just Click. You can also call them Collapsible Div or Table.

ASP.NET Ajax Tools make it so Simpler for ASP.NET. You just need to link AjaxControlToolkit.dll to your bin folder and use it in the Page.
Let's add a new Web Form in Solution, this is the Page, where you want to add your collapsible div or table what may contain anything.

Source Code for Design above is here.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Accordian with CSS >> P.Yar.B Complex</title>
    <%--<link href="Accordian.css" rel="stylesheet" />--%>
</head>

<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <table width="100%" border="0">
            <tr>
                <td colspan="2" align="center">
                    <h1>Accordian with CSS</h1>
                </td>
            </tr>
            <tr>
                <td colspan="3" align="center">
                    <asp:Accordion ID="Accordion1" runat="server" HeaderCssClass="accordionHeader" HeaderSelectedCssClass="accordionHeaderSelected" ContentCssClass="accordionContent" Width="490px">
                        <Panes>
                            <asp:AccordionPane ID="pane1" runat="server">
                                <Header>Hardwares</Header>
                                <Content>
                                    Mouse<br />
                                    KeyBoard<br />
                                    Monitor
                                    <br />
                                    Printer<br />
                                    CPU<br />
                                    Speakers<br />
                                    Camera
                                </Content>
                            </asp:AccordionPane>
                            <asp:AccordionPane ID="pane2" runat="server">
                                <Header>Operating System</Header>
                                <Content>
                                    MS Windows<br />
                                    Linux<br />
                                    Android<br />
                                    Mac<br />
                                    Unix
                                </Content>
                            </asp:AccordionPane>
                            <asp:AccordionPane ID="pane3" runat="server">
                                <Header>.NET IDE</Header>
                                <Content>
                                    Visual Studio<br />
                                    Visual Web Developer<br />
                                    SharpDevelop<br />
                                    MonoDevelop
                                </Content>
                            </asp:AccordionPane>
                            <asp:AccordionPane ID="pane4" runat="server">
                                <Header>John Bhatt</Header>
                                <Content>
                                    <a href="http://www.johnbhatt.com" target="_blank">Portal Home</a><br />
                                    <a href="http://blog.johnbhatt.com" target="_blank">Blog of P.Yar.B</a><br />
                                    <a href="http://media.johnbhatt.com" target="_blank">Download Center</a><br />
                                </Content>
                            </asp:AccordionPane>
                        </Panes>
                    </asp:Accordion>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Now Let's See the CSS, what is on CSS.
.accordionHeader {
    border: 1px solid #2F4F4F;
    color: white;
    background-color: #2E4d7B;
    font-family: Arial, Sans-Serif;
    font-size: 12px;
    font-weight: bold;
    padding: 5px;
    margin-top: 5px;
    cursor: pointer;
}

#master_content .accordionHeader a {
    color: #FFFFFF;
    background: none;
    text-decoration: none;
}

    #master_content .accordionHeader a:hover {
        background: none;
        text-decoration: underline;
    }

.accordionHeaderSelected {
    border: 1px solid #2F4F4F;
    color: white;
    background-color: #5078B3;
    font-family: Arial, Sans-Serif;
    font-size: 12px;
    font-weight: bold;
    padding: 5px;
    margin-top: 5px;
    cursor: pointer;
}

#master_content .accordionHeaderSelected a {
    color: #FFFFFF;
    background: none;
    text-decoration: none;
}

    #master_content .accordionHeaderSelected a:hover {
        background: none;
        text-decoration: underline;
    }

.accordionContent {
    background-color: #D3DEEF;
    border: 1px dashed #2F4F4F;
    border-top: none;
    padding: 5px;
    padding-top: 10px;
}
Now Run the Page again. Lets See, how it looked. Check this at your machine. Best of Luck!
Read More

Wednesday, September 19, 2012

// // Leave a Comment

File Upload Control with File Type Filter

Hi,

We are going to learn how to upload a File using FileUpload Control in ASP.NET.

ASPX Code

We Placed a FileUpload Control and a button to Click.
<asp:FileUpload ID="FileUpload1" runat="server"  /> 
<asp:Button ID="BtnUpload" runat="server" Text="Upload File" onclick="BtnUpload_Click" />

Back-end Code

Now BtnUpload_Click event in .cs page.
We are going to Upload only Picture (.JPG file or .BMP file).
 
protected void BtnUpload_Click(object sender, EventArgs e)
    {
       string sSiteFolder = "ResumeFolder";
       string sRealPath = Server.MapPath(sSiteFolder);
       if (!Directory.Exists(sRealPath))
           Directory.CreateDirectory(sRealPath);
       string CompletePath = sRealPath + FileUpload1.FileName;
       string FileExt = CompletePath.Substring(CompletePath.IndexOf("."));
       switch (FileExt)
         { 
          case ".jpg":
                FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
                break;
          case ".JPG":
                FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
                break;
          case ".bmp":
                FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
                break;
          case ".BMP":
                FileUpload1.SaveAs(sRealPath + FileUpload1.FileName);
                break;
         }
     }
Enjoy...
John Bhatt
Read More

Wednesday, September 12, 2012

// // Leave a Comment

Pagination with DataList

Hi,
As we know, DataList is the most versatile Data Bound Control available in ASP.NET. Where you can display data as per your need in your required style, direction etc.
But there is some problem also. There is no option to Paginate the Data Loaded in DataList directly. In case we have too many records, we can not display all them in One Page without paginating.

To escape from this situation, Developers move to GridView, which has easy support for Paginating data.

Today, we will learn How to Paginate DataList data in Simple steps.


First create a DataList as per your requirement. I made like below which is quite simple.





Lets place Next and Previous Buttons for Navigation. Code for above design is below:

Code in ASPX Page (Design)

<asp:DataList ID="DataList1" runat="server" Height="194px" Width="174px"
oneditcommand="DataList1_EditCommand"
oncancelcommand="DataList1_CancelCommand"
onupdatecommand="DataList1_UpdateCommand" DataKeyField="eno">
<HeaderTemplate>

<table width="450" border="2">
<tr>
<th>Employee Name </th>
<th>Designation </th>
<th>Salary </th>
<th>
Edit
</th>
</tr>

</HeaderTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="txtEname" Text='<%#Eval("ename")%>' runat="server" />
</td>
<td>
<asp:TextBox ID="txtJOb" Text='<%#Eval("job")%>' runat="server" />
</td>
<td>
<asp:TextBox ID="txtSal" Text='<%#Eval("sal")%>' runat="server" />
</td>
<td>
<asp:LinkButton ID="lnk2" runat="server" Text="Update" CommandName ="Update" />
</td>
<td>
<asp:LinkButton ID="LinkButton1" runat="server" Text="Cancel"
CommandName ="Cancel" />
</td>
</tr>

</EditItemTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("ename")%></td>
<td><%#Eval("job")%></td>
<td><%#Eval("sal")%></td>
<td>
<asp:LinkButton ID="lnk1" CommandName="Edit" Text="Edit !" runat="server" />
</td>
</tr>

</ItemTemplate>

<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
<br />
<table class="style1">
<tr>
<td class="style2">
<asp:LinkButton ID="LinkButton2" runat="server" onclick="LinkButton2_Click">Next</asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="LinkButton3" runat="server" onclick="LinkButton3_Click">Previous</asp:LinkButton>
</td>
</tr>
</table>




Now Lets to to Backend. ASPX.CS Page (Code Behind):





protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CurrentPageIndex = 0;
showData();
}
}
int pg = 0;
void showData()
{
PagedDataSource pgd = new PagedDataSource();
SqlDataAdapter da = new SqlDataAdapter("select * from emp", "Data Source=.\\SQLDB;Database=Test1;Integrated Security=True");
DataSet ds = new DataSet();
da.Fill(ds);

pgd.DataSource = ds.Tables[0].DefaultView;
pgd.CurrentPageIndex = CurrentPageIndex ;
pgd.AllowPaging = true;
pgd.PageSize = 5;

LinkButton2.Enabled = !(pgd.IsLastPage);
LinkButton3.Enabled = !(pgd.IsFirstPage);


DataList1.DataSource = pgd;
DataList1.DataBind();

}

protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = e.Item.ItemIndex;
showData();
}
protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = -1;
showData();
}
protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{

}

public int CurrentPageIndex
{
get
{
if (ViewState["pg"] == null)
return 0;
else
return Convert.ToInt16(ViewState["pg"]);
}
set
{
ViewState["pg"] = value;
}
}

protected void LinkButton2_Click(object sender, EventArgs e) {
CurrentPageIndex++;
showData();
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
CurrentPageIndex--;
showData();
}




Now Let me Describe things happened in above code:




Move to showData() function.








We created a new object of PagedDataSource. Paged data source as name stands clear, paginated data.





Now we wrote Query, Passed in Adapter, Filled DataSet which should be all clear, because it was Basic Task in ADO.NET. Now we gave it CurrentPageIndex. means where is page now.








For this, just look below to a class CurrentPageIndex which is returning value of CurentPageIndex =0 if page is beling Loaded. To check whether page is loaded or postback, we take help of ViewState. If ViewState["pg"] == null, On Page load this will be null because it is just being initiated. On Postback it will pass the Int value stored in it to CurrentPageIndex.








We set Pagination in PagedDataSource true and Define Page size of 5 records per page.


Now Passed PagedDataSource object as Datasource of Datalist.








Now Linkbutton click events, We increased and Decreased value of CurrentPageIndex.








Hope this must be helpful to you. In case of Any problem, correction in code and help, feel free to comment below.





John Bhatt




Glad to Know, Free to Share.....





http://www.johnbhatt.com





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

Wednesday, August 29, 2012

// // Leave a Comment

Implement Same WebMethod for AutoComplete in Multiple Textbox

Hi,


While Answering a question at Forum, I wrote this post.


Suppose We have Multiple Textbox in Same Page and we want to Implement AutoSuggest/AutoComplete feature in All Textbox and of same type. Suppose Multiple Google Search Boxes.


For that case, we have separate Textboxs, Separate AutoComplete Extenders and Separate Methods. We are trying to Consume same PageMethod in All Textbox.


Front End Code:

Product One:


DelimiterCharacters="" Enabled="True" ServiceMethod="GetProducts" MinimumPrefixLength="2"
ServicePath="" TargetControlID="TextBox1" UseContextKey="True">

Product Two:


DelimiterCharacters="" Enabled="True" ServicePath="" TargetControlID="TextBox2"
ServiceMethod="GetProducts" MinimumPrefixLength="2" UseContextKey="True">

Product Three:


DelimiterCharacters="" Enabled="True" ServicePath="" TargetControlID="TextBox3"
ServiceMethod="GetProducts" MinimumPrefixLength="2" UseContextKey="True">




BackEnd Code:


[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetProducts(string prefixText, int count, string contextKey)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConToStore"].ConnectionString);
SqlDataAdapter adp = new SqlDataAdapter("Select * from Products where UnitsInStock>0 and ProductName like '%" + prefixText + "%'", con);
DataSet ds = new DataSet();
adp.Fill(ds);
string[] Products = new string[ds.Tables[0].Rows.Count];
for (int j = 0; j <= ds.Tables[0].Rows.Count - 1; j++)
{
Products.SetValue(ds.Tables[0].Rows[j][1].ToString(), j);
}
return Products;
}
Lets Look at the Output.

Hope this will be Helpful.
John Bhatt
Glad to Know, Free to Share.....
http://www.johnbhatt.com

Read More

Saturday, August 18, 2012

// // Leave a Comment

Populate DropDownList Dynamically in ASP.NET (Country-State-District-City)

How to Make a Complete Dropdown and Prevent Inserting Dummy Data from Form.
Disable other Controls when Clicked back to Parent Control:
Drop Down Sequence:
OnLoad
Load Country
On-Change
Load State according to Country
On-Change
Load Dists in State
On-Change
List Cities in Dist.

Code:
 protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
  {
   ddlState.DataSource = res.States(Convert.ToInt16(ddlCountry.SelectedValue));
   ddlState.DataTextField = "StateName";
   ddlState.DataValueField = "StateID";
   ddlState.DataBind(); 
   ddlState.Items.Insert(0, "Select");
   ddlDist.Enabled = false;
   ddlCity.Enabled = false;
  }
 protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{ ddlDist.DataSource = res.Districts(Convert.ToInt16(ddlState.SelectedValue)); ddlDist.DataTextField = "DistName"; ddlDist.DataValueField = "DistID"; ddlDist.DataBind(); ddlDist.Items.Insert(0, "Select"); ddlDist.Enabled = true; ddlCity.Enabled = false; } protected void ddlDist_SelectedIndexChanged(object sender, EventArgs e) { ddlCity.DataSource = res.Cities(Convert.ToInt16(ddlDist.SelectedValue)); ddlCity.DataTextField = "CityName"; ddlCity.DataValueField = "CityID"; ddlCity.DataBind(); ddlCity.Items.Insert(0, "Select"); ddlCity.Enabled = true; }
Preview:
John Bhatt
Glad to Know, Free to Share.....
http://www.johnbhatt.com
Read More

Sunday, July 15, 2012

// // 2 comments

Installing ASP.NET in IIS

Hi,
Today we will learn how to Install .NET in IIS.
By default IIS is turned Off. To Turn on we will go to Control panel > programs > turn windows feature on or off.

Check all options by Expanding and Make sure that you got the Internet Information Services checked fully as in Above screen. Then you need not to install any more scripts to host asp.net websites.

Now If ASP.NET Websites are not running and throwing error like

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

Module StaticFileModule
Notification ExecuteRequestHandler
Handler StaticFile
Error Code 0x80070032
Requested URL http://localhost:80/JOHNSAPP/DEFAULT.ASPX
Physical Path C:\inetpub\wwwroot\John\Default.aspx
You should Install ASP.NET (configure IIS for ASP.NET).

Here are some basic steps to do so,
Open Command Prompt as Administrator
Navigate to C:\
C:\>cd Windows

C:\Windows>cd Microsoft.NET

C:\Windows\Microsoft.NET>cd Framework

Now you will be at

C:\Windows\Microsoft.NET\Framework\

First Decide what version are you using. ASP.NET 1.0, 1.1, 2.0, 3, 3.5 , 4 or 4.5 (if Installed).
Then type following code in Command Prompt
C:\Windows\Microsoft.NET\Framework>cd v4.*      //installing ASP.NET V4.0 here.

C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -i

 Command Prompt will Install Code and You are now Ready to Access your ASP.NET Site with Localhost.

Best of Luck....
John Bhatt
Read More

Sunday, July 8, 2012

// // Leave a Comment

State Management in ASP.NET part-1 (Cookies)

Hi,

I am Back with State Management Series.

In this post we are going to Talk about Cookies. After Reading this, you must be able to do following things:
  • Create Cookie
  • Access Cookie
  • Can answer Some Basic Q & A about Cookie
What is Need of Cookie?

Cookies are Required to Store Temporary data in Users system which may be Required during Session or after Session.

How Many Type of Cookie are there?
Cookies are generally of Two Type. Session wide or Persistent. Sessional cookies Expire as soon as User Closed Session means Browser. Persistent cookies expire after Defined Time. This can be Defined at the Time of Creation.

Who Make Cookies?

Cookie is always made by Application (Server) in Users/ Clients Browser and stored in Hard Disk of User. These are used to store Users Customized Appearance, other Values , Login Time etc for future Retrieval so that website can server him better.

Limitations of Cookie?

Cookies are open Invitations to Hackers.

Cookies can only store Little and Only String Type Data.



Now Lets Learn with Coding. First We will Create a Cookie named myCookie and Solve Earlier Problem with the Help of Cookie.
Now Code is Like Below:
protected void Page_Load(object sender, EventArgs e)
{

}
int x; // Made a Variable with Datatype Int for Future Use
HttpCookie myCookie; // Defined a Cookie named myCookie.
protected void Button1_Click(object sender, EventArgs e)
{
x = Convert.ToInt32(TextBox1.Text); // Converted textbox Value which we earlier Did.
myCookie = new HttpCookie("txtValue"); // Assigned Variable myCookie.
myCookie.Value = Convert.ToString(x); // Value assigned to myCookie.
Response.Cookies.Add(myCookie); //This Simple Made a Cookie that will Expire in Session End.
myCookie.Expires = DateTime.Now.AddMinutes(15); // We made is Persistent and stored it for Next 15 minutes.

}
protected void Button2_Click(object sender, EventArgs e)
{

HttpCookie storedCook = Request.Cookies["txtValue"]; // Requested from Server for Cookie
if (storedCook != null)
x = Convert.ToInt32(storedCook.Value); // Converted to Integer again.
TextBox1.Text = Convert.ToString(x * x); // Now Printed Value in Textbox.
}
Now Check....

Don't forget to add me on Google+, +John Bhatt .
Read More
// // Leave a Comment

State Management in ASP.NET

Hi Everybody,


I am once back with a blog/article/tutorial whatever you think/call it.


State Management :


HTTP Protocol is State less protocol. In Simple Language, Each and Every time We send a request to server, this is New to server.

To Understand this ,Suppose you took One Textbox and Two Buttons like in Image below:



Now, the task is To Enter Number in Textbox and Click in First Button to Convert to Integer format and then Click Second button to Print Square of Converted Integer in Textbox. What will you do. Lets look at code what I did here.

protected void Page_Load(object sender, EventArgs e)
{

}
int x;

protected void Button1_Click(object sender, EventArgs e)
{
x = Convert.ToInt32(TextBox1.Text);
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text = Convert.ToString(x * x);
}


Now what would I get Result on Second Button Click event. Textbox Result will be 0 even I have entered any number. Don't agree, try this at home.


This is Because, at the time of Button2 Click new request is send to server and Initial Value of X is picked from server which is 0.


To Prevent the Loose of Data each time we send request to server, ASP.NET have implemented concept of State Management.

State Management is divided into 2 parts according to Functionality.

1) User Based State Management
  • Cookies
  • QueryStrings
  • ViewState
  • Controls
  • Hidden Fields
2) Server Based State Management
  • Session
  • Application
  • Profile


I am going to Describe all these States step by step in Different Posts.

All the Series has been posted on DotNetSpider at below Link Resources > Keep Reading.
Read More

Thursday, July 5, 2012

// // Leave a Comment

AutoCompleteExtender in Textbox

Hi,

We will learn how to enable AutoCompleteExtender in Textbox Control.


Here, We will learn to Map data from SQL Database to Textbox within Same Page. WebMethod in .cs Page.

Directly to Code:
ASPX Page Code



Vehicle No :










Now Code in ASPX.CS Page

Add these Namespages for below Code.
using System.Data; // For Dataset
using System.Data.SqlClient; // For SQlConnection/Adaptor
using System.Configuration; // Access Consting from Web.Config.
using System.Collections.Generic;



[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetVehicleList(string prefixText, int count, string contextKey)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConToJohn"].ConnectionString);
SqlDataAdapter adp = new SqlDataAdapter("Select distinct VehicleNo from VehicleDispatch where VehicleNo like '%" + prefixText + "%'", con);
DataSet ds = new DataSet();
adp.Fill(ds, "Vehicles");
string[] VehicleNo = new string[ds.Tables["Vehicles"].Rows.Count];
for (int i = 0; i <= ds.Tables["Vehicles"].Rows.Count - 1; i++)
{
VehicleNo.SetValue(ds.Tables["Vehicles"].Rows[0][0].ToString(), i);
}
return VehicleNo;
}
I have Selected Only Unique Value from Database using SELECT DISTINCT .... command. If you want all records, Simply Change SQL Query to SELECT ..... Will be glad to hear from you... This Post is copied from DotNetFunda where I wrote in Code section.
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