RSS

Monthly Archives: June 2010

ASP.NET 4.0 : Manipulate ClientID using ClientIDMode


In this article I will discuss how you can manipulate the ClientId of each control being rendered in the browser. The article also demonstrates how you can use Predictable ClientId for data bound controls.

Introduction

ClientID of a control is one of the feature in ASP.NET which always hunts me in the past. It is very hard to predict what client id the page is going to render when it is put in the client side. ASP.NET has an unique naming system, which generates the client ids and sends to the browser based on certain logic. With the introduction of ASP.NET 4.0, the work become very easier. Handling with the client ids are now very easy.

In this article I am going to discuss how you can take benefit of the feature to manipulate the client id generated in the client side.

The Problem

Before I start discussing about the Solution, let us discuss what exactly the problem is when writing an ASP.NET application.

There is a wide difference between the id of the html and the id on a server control. ASP.NET page renders itself to produce HTML output. Every server control has an ID which uniquely identifies the control in the class. Now this control can render quite different html ids based on certain scenarios.

Lets I have a simple page :

<asp:Label Id="lblName" runat="server" Text="Select Name : " />
  <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
  <asp:Button runat="server" OnClick="Submit_Click" OnClientClick="javascript:return validateName();" Text="PostPage" />

Here I have a TextBox control which is set runat=”server” that means the control is not an html control and the server will render it.  While it renders, it creates a

<input type="text" id="txtName" />

I have defined one javascript which looks like :

 function validateName() {
        var element = document.getElementById("txtName");
        if (element.value.length > 0)
            return true;
        return false;
    }

This will work Fine. But say after a certain while I add one MasterPage for this Html. Here comes the problem.

If you place the any control inside the contentplaceholder (with name MainContent) of a masterpage, its id will be generated as ctl00$MainContent$txtName.

The id can be divided into 3 sections which are separated using $ signs.

1. ctl00 : This is a random id generated for every masterpage you nest. Its ctl00, ctl01 …
2. MainContent : It represents the id of the MasterPage. Here I have specified the id of the MasterPage as MainContent.
3. txtName : This is the actual Id of the control in the serverside.

Thus you can see, depending on the MasterPage id, the id of all the control will change.  So after placing it inside the masterpage, my javascript will not work and will always return false, as element will be null.

In case of this problem, either I can write

var element = document.getElementById("ctl00$MainContent$txtName");

Or more precisely I might go for :

var element = document.getElementById("<%=this.txtName.ClientID %>");

Both the scenario will work, but both of them has certain limitations.

Limitation of 1st Approach

  • Laborious job to modify all the clientid reference if I have to change the name of the MasterPage and /or Nest the masterpage inside another masterpage to change layout.
  • Need to change the javascript files that are referenced from the page, and hence the javascript will be totally dependent on the current page.

Limitation of 2nd Approach

  • In spite of limitations of the first approach, it is also not full proof to use the second approach, even though it is better to use the second.
  • Javascript should be placed with the page. It cant replace the server tags to the external js file.
  • Page size will increase, as each page will have lots of javascript blocks which just interface between client side scripts.
  • Mix of Server side and client side blocks which should always be avoided in ASP.NET (unlike Classic ASP)

New Approach to Solve the Issue

ASP.NET 4.0 comes with a new feature that allows you to specify the mode of the client id for each control. So you will get full control of what id to be rendered in the client side and hence it becomes easier to handle the problems that I have discussed previously.

Every Control of ASP.NET 4.0 comes with a new property called ClientIDMode. It determines how the ClientID will be rendered. Let us discuss about the different modes of ClientID rendering and see how you can use it :

ClientIDMode.Static

In this mode, the control will render the ID of the client side as it is defined in the server side. It comes handy when you dont want to change the id of the client side html controls. In this case, as ASP.NET doesn’t takes care of the uniqueness of the control id rendered in the client side, it will be the responsibility of the programmer to uniquely identify each control it defines.

In the above example, I can use

<asp:Label Id="lblName" runat="server" Text="Select Name : " />
        <asp:TextBox ID="txtName" runat="server" ClientIDMode="Static"></asp:TextBox><br />
        <asp:Button runat="server" OnClick="Submit_Click" OnClientClick="javascript:return validateName();" Text="PostPage" />

In this case the client html will be as :

 <input name="ctl00$MainContent$txtName" type="text" id="txtName" /><br />
        <input type="submit" name="ctl00$MainContent$ctl00" value="PostPage" onclick="javascript:return validateName();" />

So I can now easily refer to the control in javascript only using txtName even from external javascript files. Ahh… The problem solved.

ClientIDMode.AutoId

AutoId is the default ClientIDMode when it is not defined anywhere in the page. It comes handy when you have configured all the ControlIDMode of the page or of the whole application as Static or any other value, and you want only a specific control to have Inherit value.

If I place the ClientIDMode=”AutoId” in the above code, the html will look like

<input name="ctl00$MainContent$txtName" type="text" id="ctl00_MainContent_txtName" /><br />
        <input type="submit" name="ctl00$MainContent$ctl00" value="PostPage" onclick="javascript:return validateName();" />

You can see the ID of the control is modified to refer the ContentPlaceHolder name with an AutoId just before the Id. AutoId mode is best when you don’t want to handle the uniqueness of the control id yourself and want to rely totally on ASP.NET.

ClientIDMode.Inherit

Inherit is slightly different than the AutoId. AutoId places one Unique Sequence page id of the controls using ctl00, ctl01 .. In case of Inherit mode, it only places the inherited control id for each controls.

As I am within the masterpage, it will give you  “MainContent_txtName”. So the only difference between inherit mode and AutoId is that AutoId places the unique PageId while Inherits doesnt.

ClientIDMode.Predictable

The modes that I have discussed earlier works when we are going to use static controls on the page. Predictable mode comes handy when we are going to use DataBound controls which renders more than one control with same id. So using Predictable we can predict the id that the control will generate when it rendered in the client side.

Let us take the example of a ListView to demonstrate how you can easily use this. For simplicity I am using XmlDataSource to define the Data.

<asp:XmlDataSource ID="xdsStudent" runat="server">
        <Data>
            <Students>
                <Student id="1" name="Abhijit" />
                <Student id="2" name="Sheo" />
                <Student id="3" name="Puneet" />
                <Student id="4" name="Kunal" />
            </Students>
        </Data>
    </asp:XmlDataSource>

Say this is my DataSource and I define a ListView using this DataSource.

<asp:ListView runat="server" ID="lvShowNames" DataSourceID="xdsStudent" ClientIDMode="Predictable">
            <ItemTemplate>
                <asp:Label runat="server" Text='<%# Eval("name") %>' ID="lblStudentName"/> </br>
            </ItemTemplate>
            
        </asp:ListView>

Now as I defined the ClientIDMode as predictable, the span which is rendered in the client side will look like :

<span id="MainContent_lvShowNames_lblStudentName_0">Abhijit</span>
<span id="MainContent_lvShowNames_lblStudentName_1">Sheo</span>
<span id="MainContent_lvShowNames_lblStudentName_2">Puneet</span>
<span id="MainContent_lvShowNames_lblStudentName_3">Kunal</span>

Therefore you can see the ids will be generated. It has 4 parts(each separated using underscores). The first part represents ContentPage Name, Next shows ListViewId, and then Control Id and then a unique number for each record.

Now say I don’t want the uniqueness to be implied automatically by ASP.NET. I would like to render the suffix with the same id that is present for each student. There is another property for each databound controls that I can make use of which is called ClientIDRowSuffix which enables you to use a proper suffix for each control.

<asp:ListView runat="server" ID="lvShowNames" DataSourceID="xdsStudent" ClientIDRowSuffix="id">
   <ItemTemplate>
       <asp:Label runat="server" Text='<%# Eval("name") %>' ID="lblStudentName"/> </br>
   </ItemTemplate>
</asp:ListView>

Thus the html will seem like :

<span id="MainContent_lvShowNames_lblStudentName_1">Abhijit</span>
<span id="MainContent_lvShowNames_lblStudentName_2">Sheo</span>
<span id="MainContent_lvShowNames_lblStudentName_3">Puneet</span>
<span id="MainContent_lvShowNames_lblStudentName_4">Kunal</span>

So the suffix will be the same as the record id of each student.

Similarly, you can use as many suffix as you want. Each of them should be separated using comma. So if I write ClientIDRowSuffix=”id,name” it will be like :

<span id="MainContent_lvShowNames_lblStudentName_1_Abhijit">Abhijit</span> </br>
<span id="MainContent_lvShowNames_lblStudentName_2_Sheo">Sheo</span> </br>            
<span id="MainContent_lvShowNames_lblStudentName_3_Puneet">Puneet</span> </br>
<span id="MainContent_lvShowNames_lblStudentName_4_Kunal">Kunal</span> </br>

Thus you can see, now the id which is rendered in the client will possess the name of each students.

Note

You can also configure the ClientIDMode to a page. This will modify the default ClientIDMode of the page in which it is configured. Similarly you can also set the ClientIDMode in Web.config to apply this to every control in the current web site.

Conclusion

It is a common problem for every ASP.NET developer to handle with ClientIds. With the introduction of ASP.NET 4.0, the problem is cured, and you can get a better approach to handle the client end control ids easily.

I hope this would help you.

 
Leave a comment

Posted by on June 29, 2010 in Java Script

 

Using CASE Expressions


Using CASE Expressions

by Craig S. Mullins

CASE expressions are often over-looked but can be extremely useful to change very complex query requirements into simpler, and sometimes more efficient SQL statements. The CASE expression enables many forms of conditional processing to be placed into a SQL statement. By using CASE, more logic can be placed into SQL statements instead of being expressed in a host language or 4GL program.

Microsoft’s implementation of CASE expressions in SQL Server is compliant with the ANSI SQL-92 standard.

A Quick Example

Sometimes a quick example is worth several hundred descriptive words, so let’s take a look at a sample SQL statement using a CASE expression on the title table in the sample pubs database:

SQL Statement #1

SELECT title, price,
Budget = CASE price
WHEN price > 20.00 THEN ‘Expensive’
WHEN price BETWEEN 10.00 AND 19.99 THEN ‘Moderate’
WHEN price < 10.00 THEN ‘Inexpensive’
ELSE ‘Unknown’
END,
FROM titles

This statement would return results similar to these:

Title                  Price       Budget
———————- ———– —————
Cooking with Computers 11.95       Moderate
Straight Talk About Co 19.99       Moderate
The Busy Executive’s D 19.99       Moderate
You Can Combat Compute 2.99        Inexpensive
Silicon Valley Gastron 19.99       Moderate
The Gourmet Microwave  2.99        Inexpensive
But Is It User Friendl 22.95       Expensive
Secrets of Silicon Val 20.00       Moderate
Net Etiquette          (null)      Unknown

This output is not comprehensive but shows enough detail to help describe the effects of the CASE expression.  The CASE expression is exercised on each row returned.  It categorizes the contents of the price column into four different groups: expensive, moderate,  inexpensive, and unknown. This is easier and more efficient than writing a SQL statement that uses UNION to combine the results of the four categories. The following UNION statement would return equivalent results:

SQL Statement #2

SELECT title, price, ‘Expensive’
FROM titles
WHERE price > 20.00
UNION ALL
SELECT title, price, ‘Moderate’
FROM titles
WHERE price BETWEEN 10.00 AND 19.99
UNION ALL
SELECT title, price, ‘Inexpensive’
FROM titles
WHERE price < 10.00
UNION ALL
SELECT title, price, ‘Unknown’
FROM titles
WHERE price IS NULL
go

UNION ALL is used instead of just UNION because no duplicates need to be removed. Each SELECT in the UNION returns a distinct result set.

You can see where this UNION formulation would be less efficient than the previous CASE formulation. In the UNION example SQL Server would have to make four passes through the data—one for each SELECT used. In the CASE example, one pass through the data is sufficient to return the correct results. Obviously, the CASE formulation will outperform the UNION formulation.

Another very useful capability of CASE expressions is to transform a result set from multiple rows into a summary row. Consider the situation where sales data is stored in a table by month. One row is stored per month with a table structure that looks like the following:

CREATE TABLE prodsales
(product char(3),
mnth    smallint,
sales   money)
In this table, sales amounts (sales) are stored by month (mnth) and product code (product). The mnth column stores an integer value ranging from 1 (for January) to 12 (for December). You can use the following single SQL statement to product one row per product with 12 totals, one for each month:

SQL Statement #3

SELECT product,
SUM(CASE mnth WHEN 1 THEN sales ELSE NULL END) AS jan,
SUM(CASE mnth WHEN 2 THEN sales ELSE NULL END) AS feb,
SUM(CASE mnth WHEN 3 THEN sales ELSE NULL END) AS mar,
SUM(CASE mnth WHEN 4 THEN sales ELSE NULL END) AS apr,
SUM(CASE mnth WHEN 5 THEN sales ELSE NULL END) AS may,
SUM(CASE mnth WHEN 6 THEN sales ELSE NULL END) AS jun,
SUM(CASE mnth WHEN 7 THEN sales ELSE NULL END) AS jul,
SUM(CASE mnth WHEN 8 THEN sales ELSE NULL END) AS aug,
SUM(CASE mnth WHEN 9 THEN sales ELSE NULL END) AS sep,
SUM(CASE mnth WHEN 10 THEN sales ELSE NULL END) AS oct,
SUM(CASE mnth WHEN 11 THEN sales ELSE NULL END) AS nov,
SUM(CASE mnth WHEN 12 THEN sales ELSE NULL END) AS dec
FROM prodsales
GROUP BY product

This statement generates a row for each product with twelve monthly sales totals. The CASE expression causes the sales amount to by added to the appropriate bucket by checking the mnth column. If the month value is for the appropriate “month bucket”, then the sales amount is added using SUM; if not, then NULL is specified, thereby avoiding adding anything to the SUM. Using CASE expressions in this manner simplifies aggregation and reporting. It provides a quick way of transforming normalized data structures into the more common denormalized formats that most business users are accustomed to viewing on reports.

This same basic idea can be used to create many types of summary rows. For example, to produce a summary row by quarter instead of by month, simply modify the CASE expressions as shown below:

SQL Statement #4

SELECT product,
SUM(CASE WHEN mth BETWEEN 1 AND 3 THEN sales
ELSE NULL END) AS q1,
SUM(CASE WHEN mth BETWEEN 4 AND 6 THEN sales
ELSE NULL END) AS q2,
SUM(CASE WHEN mth BETWEEN 7 AND 9 THEN sales
ELSE NULL END) AS q3,
SUM(CASE WHEN mth BETWEEN 10 AND 12 THEN sales
ELSE NULL END) AS q4
FROM prodsales
GROUP BY product

A More Complicated Example

Using searched CASE expressions and nested subqueries in SELECT statements very complex processing can be accomplished with a single SQL statement. Consider, once again, the sample pubs database. The following query checks the royalty percentage by title and places the percentage into a category based on its value:

SQL Statement #5

SELECT au_lname, au_fname, title, Category =
CASE

WHEN (SELECT AVG(royaltyper) FROM titleauthor ta

WHERE t.title_id = ta.title_id) > 65
THEN ‘Very High’

WHEN (SELECT AVG(royaltyper) FROM titleauthor ta

WHERE t.title_id = ta.title_id)
BETWEEN 55 and 64

THEN ‘High’

WHEN (SELECT AVG(royaltyper) FROM titleauthor ta

WHERE t.title_id = ta.title_id)
BETWEEN 41 and 54

THEN ‘Moderate’

ELSE ‘Low’

END

FROM authors a,
titles t,
titleauthor ta

WHERE a.au_id = ta.au_id
AND   ta.title_id = t.title_id

ORDER BY Category, au_lname, au_fname

Within a SELECT statement, the searched CASE expression allows values to be replaced in the results set based on comparison values. In this example, the royalty percentage (royaltyper) in the titleauthor table is checked and a category is specified for each author based on the royalty percentage returned.

Usage and Syntax

CASE expressions can be used in SQL anywhere an expression can be used. This provides great flexibility because expressions can be used in a wide number of places. Example of where CASE expressions can be used include in the SELECT list, WHERE clauses, HAVING clauses, IN lists, DELETE and UPDATE statements, and inside of built-in functions.

There are two basic formulations that a CASE expression can take: simple CASE expressions and searched CASE expressions. A simple CASE expression checks one expression against multiple values. Within a SELECT statement, a simple CASE expression allows only an equality check; no other comparisons are made. A simple CASE expression operates by comparing the first expression to the expression in each WHEN clause for equivalency. If these expressions are equivalent, the expression in the THEN clause will be returned.

The basic syntax for a simple CASE expressions is shown below:

CASE expression
WHEN expression1 THEN expression1
[[WHEN expression2 THEN expression2] […]]
[ELSE expressionN]
END

A searched CASE expression is more feature-laden. It allows comparison operators, and the use of AND and/or OR between each Boolean expression. The simple CASE expression checks only for equivalent values and can not contain Boolean expressions. The basic syntax for a searched CASE expressions is shown below:

CASE
WHEN Boolean_expression1 THEN expression1
[[WHEN Boolean_expression2 THEN expression2] […]]
[ELSE expressionN]
END

You have seen samples of each type of CASE expression in the SQL examples depicted previously in this article. SQL statements #1 and #3 are simple CASE expressions; SQL statements #4 and #5 are searched CASE expressions.

Using CASE Expressions When Modifying Data

CASE expressions can also be used with data modification statements. Using CASE in conjunction with a SQL UPDATE statement enables developers to conditionally modify large amounts of data using a single SQL statement. Consider the following example:

SQL Statement #6

UPDATE titles
SET price =
CASE
WHEN (price < 5.0 AND ytd_sales > 999.99)
THEN price * 1.25
WHEN (price < 5.0 AND ytd_sales < 1000.00)
THEN price * 1.15
WHEN (price > 4.99 AND ytd_sales > 999.99)
THEN price * 1.2
ELSE price
END

This statement examines book title criteria to determine whether prices should be modified. The CASE expression uses a combination of current price and year-to-date sales to specify a price increase percentage. Any criteria that can be expressed in terms of SQL predicates in CASE expressions can be used to update rows conditionally.

General Usage Guidelines

All data types used in the THEN clause of CASE expressions must be compatible data types. If the data type used is not compatible then SQL Server will return an error because implicit data type conversion is not supported.

Be sure that all possibilities are covered within the CASE expressions. For example, consider a CASE expression that must be coded on numeric data that can range from -1 to 100, and then an outlying value of 1000. Do not omit or overlap any of the possible data values. Furthermore, be aware of the data type of the values being examined in the CASE expression. Do not leave gaps in the range of possible values by not using appropriate values. For example, if the data is decimal (instead of integer, say) do not ignore the portion of the number to the right of the decimal point. A good example of this is shown in the previous SQL statement #6. If the value for 999.99 is changed to 999.0 then any values between 999.01 and 999.99 will be lumped in with the ELSE condition – which is clearly not the desired intent of this statement.

The bottom line is that CASE expressions are very powerful, yet often neglected. Favor using CASE expressions under the following circumstances:

  • when data needs to be converted from one type to another for display and no function exists to accomplish the task
  • when a summary row needs to be created from detail data
  • when conditional processing needs to be executed to determine results
  • when using UNION to “glue together” different subsets of a single table

One final usage guideline is to use the COALESCE function with your CASE expressions when you wish to avoid NULLs. Consider an employee table that contains three columns for wages: salary, commission, and retainer_fee. Any single employee can only receive one of these types of wages. So, two of the columns will contain NULLs, but one will always contain a value. The following statement uses the COALESCE function to return only the non-NULL value:

SELECT COALESCE(salary, commission, retainer_fee, 0)

FROM employee

The COALESCE function will go through the list of expressions (in this case columns and constants) and return the first non-NULL value encountered. In this case, the numeric constant 0 is added at the end of the list to provide a default value if all of the columns should happen to be NULL.

Summary

CASE expressions bring a vast degree of power and control to SQL Server programmers. A working knowledge of CASE expressions can make accessing and updating SQL Server data easier and perhaps, even more efficient. Additionally, CASE expressions enable more work to be accomplished using a single SQL statement, which should also improve efficiency and decrease development time. As such, CASE expressions should be a component of every SQL Server developer’s arsenal of programming techniques.

 
Leave a comment

Posted by on June 26, 2010 in SQL Query

 

sequence number Add in sql server Query


Query

select au_id,authors_name from Mytable1 order by au_id

Results

12 Sidney Sheldon
76 David Taylor
100 Mathew Arnold
127 Agatha Christy
140 Keith Davis

au_id is unique in this table, so it is easy to use a co-related sub-query to generate sequential numbers.

Query

SELECT (SELECT count(au_id) FROM Mytable1 AS x WHERE x.au_id<= y.au_id) AS
Sequence, au_id,authors_name
FROM Mytable1 AS y order by au_id

Results

1 12 Sidney Sheldon
2 76 David Taylor
3 100 Mathew Arnold
4 127 Agatha Christy
5 140 Keith Davis

Note: “au_id” is a unique column.

Example 2:

Generate unique sequence numbers for a table that has no unique column.

Let us consider the table shown below. For tables with no unique columns, it is easy to use the identity function to generate unique sequence numbers.

Use tempdb
go
Create table Mytable2 (au_id int, authors_name varchar(100))
Go
insert into MyTable2 select 100,'Mathew Arnold'
insert into MyTable2 select 140,'Keith Davis'
insert into MyTable2 select 76,'David Taylor'
insert into MyTable2 select 127,'Agatha Christy'
insert into MyTable2 select 12,'Sidney Sheldon'
insert into MyTable2 select 12,'Mcarthur'
insert into MyTable2 select 76,'Alan Smiles'
insert into MyTable2 select 100,'Kreisler'
go

Query

select * from mytable2 order by au_id

Results

12 Sidney Sheldon
12 Mcarthur
76 Alan Smiles
76 David Taylor
100 Mathew Arnold
100 Kreisler
127 Agatha Christy
140 Keith Davis

Query

select identity(int,1,1) as Sequence, au_id,authors_name into #x from Mytable2 order by au_id
go
select * from #x
go
drop table #x
go

Results

1 12 Sidney Sheldon
2 12 Mcarthur
3 76 Alan Smiles
4 76 David Taylor
5 100 Mathew Arnold
6 100 Kreisler
7 127 Agatha Christy
8 140 Keith Davis
 
Leave a comment

Posted by on June 26, 2010 in SQL Query

 

Merge GridView Cells Or Columns in Row ASP.NET C# VB.NET


In this example i am going to describe how to merge GridView cells or Columns in gridview rows containing same data or content using C# and VB.NET in ASP.NET

For this i m using DataBound Event of gridview, counting total rows and then checking each cells value against value of same cell in previous row and then setting the RowSpan of cells.

For this i have created a table containing Counties ,states and respective cities and country and state cells / columns are merged in rows having same country or states.

Html source of the page look like this

<asp:GridView ID="GridView1" runat="server"
    AutoGenerateColumns="False"
    BorderStyle="None" BorderWidth="1px" CellPadding="4"
    GridLines="Horizontal" ForeColor="Black"
    Height="119px" DataSourceID="SqlDataSource1"
    OnDataBound="GridView1_DataBound1">
            <Columns>
            <asp:BoundField DataField="Country"
                            HeaderText="Country"
                            SortExpression="Country" />
            <asp:BoundField DataField="State"
                            HeaderText="State"
                            SortExpression="State" />
            <asp:BoundField DataField="City"
                            HeaderText="City"
                            SortExpression="City" />
        </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Country], [State], [City]
               FROM [Details] ORDER BY [State]">
</asp:SqlDataSource>
C# code behind
protected void GridView1_DataBound1(object sender, EventArgs e)
{
  for (int rowIndex = GridView1.Rows.Count - 2;
                                     rowIndex >= 0; rowIndex--)
  {
    GridViewRow gvRow = GridView1.Rows[rowIndex];
    GridViewRow gvPreviousRow = GridView1.Rows[rowIndex + 1];
    for (int cellCount = 0; cellCount < gvRow.Cells.Count;
                                                  cellCount++)
    {
     if (gvRow.Cells[cellCount].Text ==
                            gvPreviousRow.Cells[cellCount].Text)
     {
       if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
       {
         gvRow.Cells[cellCount].RowSpan = 2;
       }
       else
       {
        gvRow.Cells[cellCount].RowSpan =
            gvPreviousRow.Cells[cellCount].RowSpan + 1;
       }
       gvPreviousRow.Cells[cellCount].Visible = false;
    }
   }
 }
}

VB.NET code behind 
Protected Sub GridView1_DataBound1
           (ByVal sender As Object, ByVal e As EventArgs)

For rowIndex As Integer = GridView1.Rows.Count - 2 To 0 Step -1
    Dim gvRow As GridViewRow = GridView1.Rows(rowIndex)
    Dim gvPreviousRow As GridViewRow = GridView1.Rows(rowIndex + 1)
    For cellCount As Integer = 0 To gvRow.Cells.Count - 1
    If gvRow.Cells(cellCount).Text =
                         gvPreviousRow.Cells(cellCount).Text Then
    If gvPreviousRow.Cells(cellCount).RowSpan < 2 Then
    gvRow.Cells(cellCount).RowSpan = 2
    Else
    gvRow.Cells(cellCount).RowSpan =
                       gvPreviousRow.Cells(cellCount).RowSpan + 1
    End If
    gvPreviousRow.Cells(cellCount).Visible = False
    End If
    Next
  Next
End Sub
 
Leave a comment

Posted by on June 26, 2010 in Uncategorized

 

Image Rotator in Javascript


mage Rotator in Javascript

There are many ways to create Image Rotator in JavaScript .I write two simple examples to create an Image rotator in JavaScript.

1. My first Program:->

Step 1:-> First we create an image(img1) with the help of <img> tag. and place it in the <body> tag:->

<body onload=”show()”>
<img id=”img1″  width=”120px” />

</body>

Note:->Here we call a js function(show()) on the onload event.

Step 2:->Create a javascript function(show())  in the <head> tag:->

<script language=’javascript’>
function show()
{
document.getElementById(‘img1’).src=”Water lilies.jpg”;
setTimeout(“show2()”,1000);
}
function show2()
{
document.getElementById(‘img1’).src=”Winter.jpg”;
setTimeout(“show3()”,1000);
}
function show3()
{
document.getElementById(‘img1’).src=”Sunset.jpg”;
setTimeout(“show4()”,1000);
}
function show4()
{
document.getElementById(‘img1’).src=”Blue hills.jpg”;
setTimeout(“show()”,1000);
}
</script>

Here we get the Id of the image(img1) with the help of getElementById (The getElementById() method accesses the element with the specified id).

and sets the source(src) of the img1. Here we create many functions and call it with the help of setTimeout Method of javascript.

2. My second Program:->

Here we sets the imge on the basis of the onmouseover event of the particular Table’s Text and sets the image and there description on the basis of it.

Step 1:->First We create a table in the <body> tag and sets an image(img1) and multiple <p> tags in the table rows:->

<table style=”border:1px solid Black”>
<tr>
<td>
<table>
<tr>
<td>
<img id=”img1″ src=”Sunset.jpg”  width=”120px” />
</td>
</tr>
<tr>
<td>
<p id=”pmain”> </p>
</td>
</tr>
</table>
</td>
<td>
<table style=”width:140px”>
<tr>
<td id=”td1″ align=”center” style=”border:1px solid Black” onmouseover=”show1()” onmouseout=”hide1()”>
<p id=”p1″>Image1</p>
</td>
</tr>
<tr>
<td id=”td2″  align=”center”  style=”border:1px solid Black” onmouseover=”show2()” onmouseout=”hide2()”>
<p id=”p2″>Image2</p>
</td>
</tr>
<tr>
<td id=”td3″  align=”center”  style=”border:1px solid Black” onmouseover=”show3()” onmouseout=”hide3()”>
<p id=”p3″>Image3</p>
</td>
</tr>
<tr>
<td id=”td4″  align=”center”  style=”border:1px solid Black” onmouseover=”show4()” onmouseout=”hide4()”>
<p id=”p4″>Image4</p>
</td>
</tr>
</table>
</td>

</tr>
</table>

Here we set the style and call functions on the onmouseover and onmouseout event.

Step 2:->Create javascript functions  in the <head> tag:->

<script language=’javascript’>
function show1()
{
document.getElementById(‘img1’).src=”Winter.jpg”;
document.getElementById(“p1″).style.fontStyle=”italic”;
document.getElementById(“td1″).style.background=”Red”;
document.getElementById(“pmain”).innerHTML=”Image1″;

}
function hide1()
{
document.getElementById(“p1″).style.fontStyle=”normal”;
document.getElementById(“td1″).style.background=”White”;
document.getElementById(“pmain”).innerHTML=””;

}

function show2()
{
document.getElementById(‘img1’).src=”Sunset.jpg”;
document.getElementById(“p2″).style.fontStyle=”italic”;
document.getElementById(“td2″).style.background=”Red”;
document.getElementById(“pmain”).innerHTML=”Image2″;
}
function hide2()
{
document.getElementById(“p2″).style.fontStyle=”normal”;
document.getElementById(“td2″).style.background=”White”;
document.getElementById(“pmain”).innerHTML=””;
}
function show3()
{
document.getElementById(‘img1’).src=”Water lilies.jpg”;
document.getElementById(“p3″).style.fontStyle=”italic”;
document.getElementById(“td3″).style.background=”Red”;
document.getElementById(“pmain”).innerHTML=”Image3″;
}
function hide3()
{
document.getElementById(“p3″).style.fontStyle=”normal”;
document.getElementById(“td3″).style.background=”White”;
document.getElementById(“pmain”).innerHTML=””;
}

function show4()
{
document.getElementById(‘img1’).src=”Blue hills.jpg”;
document.getElementById(“p4″).style.fontStyle=”italic”;
document.getElementById(“td4″).style.background=”Red”;
document.getElementById(“pmain”).innerHTML=”Image4″;
}
function hide4()
{
document.getElementById(“p4″).style.fontStyle=”normal”;
document.getElementById(“td4″).style.background=”White”;
document.getElementById(“pmain”).innerHTML=””;

}
</script>

Here we sets the src property of image(img1) with the help of id and sets the style of <td> and <p> tags and the innerHTML property of <p> tag on the basic of Id .Here we get the Id with the help of getElementById (The getElementById() method accesses the element with the specified id).

 
1 Comment

Posted by on June 26, 2010 in ASP Dot Net C#

 

Way of adding items in Drop Down List or List Box using Javascript


<script type=”text/javascript”>

function AddItem(Text,Value)

{

// Create an Option object

var opt = document.createElement(“option”);

// Add an Option object to Drop Down/List Box

document.getElementById(“DropDownList”).options.add(opt);

// Assign text and value to Option object

opt.text = Text;

opt.value = Value;

}

<script />

 
Leave a comment

Posted by on June 26, 2010 in ASP Dot Net C#

 

way of calling “javascript function of parent window from child window.”


i am  explain how to call the javascript function of a parent window from the child window(pop-Up).

Parent Java Script Function:

<script language=”Javascript” type=”text/javascript”>

function CallAlert()

{

alert(“This is parent window’s alert function.”);

}

</script>

Child window’s Java Script Function:

<script language=”Javascript” type=”text/javascript”>

function SetParentWindowsHiddenFieldValue()

<script language=”Javascript” type=”text/javascript”>

function SetParentWindowsHiddenFieldValue()

{

window.opener.document.getElementById(“HiddenField1”).value =

document.getElementById(“TextBox1”).value;

return false;

}

function CallParentWindowFunction()

{

window.opener.CallAlert();

return false;

}

</script>

 
Leave a comment

Posted by on June 26, 2010 in ASP Dot Net C#

 

Highlight gridview row on mouse hover in asp.netHighlight gridview row on mouse hover in asp.net


Gridview control is a customizable and flexible control used to display data in tabular format. It has some nice features. But lacks of some client side features that makes web users happy. We can easily add these features with few lines of code.

For example, a common task is to highlight gridview row on mouse over which is not provided with gridview control. Here we will see how easily we can do the task.

In order to change gridview row color we need to add/remove style attributes to that specific row using JavaScript onmouseover and onmouseout client event. We can do it on RowDataBound or RowCreated gridview event.

Code Snippet:

protected void gvHrEmploye_RowDataBound(object sender, GridViewRowEventArgs e)        {            if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)            {
// when mouse is over the row, save original color to new attribute, and change it to highlight color                e.Row.Attributes.Add(“onmouseover”, “this.originalstyle=this.style.backgroundColor;this.style.backgroundColor=’#EEFFAA'”);
// when mouse leaves the row, change the bg color to its original value                   e.Row.Attributes.Add(“onmouseout”, “this.style.backgroundColor=this.originalstyle;”);

}        }
or,

protected void gvHrEmploye_RowCreated(object sender, GridViewRowEventArgs e)        {            if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)            {
// when mouse is over the row, save original color to new attribute, and change it to highlight color                e.Row.Attributes.Add(“onmouseover”, “this.originalstyle=this.style.backgroundColor;this.style.backgroundColor=’#EEFFAA'”);
// when mouse leaves the row, change the bg color to its original value                   e.Row.Attributes.Add(“onmouseout”, “this.style.backgroundColor=this.originalstyle;”);

}        }
It works properly even if you set AlternatingRowStyle property or the row is previously selected.

 
Leave a comment

Posted by on June 26, 2010 in ASP Dot Net C#

 

Custom Paging of GridView,DataListView and Repeater Control of Asp.net With C#


Custom Paging Img

Custom Paging of GridView or DataListview or Repeater

Code-Behind Code

//Page Load Event

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

BindMngRegistration();

}

}

//Load or Bind the Data to Dataset with gridview or Datalist

public void BindMngRegistration()

{

DataSet ds = BLLRegisrationOnline.ViewManageRegistration();

_PageDataSource.DataSource = ds.Tables[0].DefaultView;

_PageDataSource.AllowPaging = true;

_PageDataSource.PageSize = Convert.ToInt32(GVRegView.PageSize);

_PageDataSource.CurrentPageIndex = CurrentPage;

ViewState[“TotalPages”] = _PageDataSource.PageCount;

this.lblPageInfo.Text = “Page ” + (CurrentPage + 1) + ” of ” + _PageDataSource.PageCount;

this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;

this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;

this.lbtnFirst.Enabled = !_PageDataSource.IsFirstPage;

this.lbtnLast.Enabled = !_PageDataSource.IsLastPage;

//Bind With Control

this.GVRegView.DataSource = _PageDataSource;

this.GVRegView.DataBind();

this.doPaging();

}

//Write This Code For the Number of Record to display at Lable

protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)

{

if (e.Item.ItemType != ListItemType.Separator)

{

LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl(“lnkbtnPaging”);

if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())

{

lnkbtnPage.Enabled = false;

lnkbtnPage.Style.Add(“fone-size”, “14px”);

lnkbtnPage.Font.Bold = true;

}

}

}

//display the current page of the number of page like (5 of 15)

protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)

{

if (e.CommandName.Equals(“Paging”))

{

CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());

this.BindMngRegistration();

}

}

// Page Datasource Object for pagging

#region PagedDataSource

PagedDataSource _PageDataSource = new PagedDataSource();

#endregion

//Properties of Paging for next,first ,last,previous

#region Private Properties

private int CurrentPage

{

get

{

object objPage = ViewState[“_CurrentPage”];

int _CurrentPage = 0;

if (objPage == null)

{

_CurrentPage = 0;

}

else

{

_CurrentPage = (int)objPage;

}

return _CurrentPage;

}

set { ViewState[“_CurrentPage”] = value; }

}

private int fistIndex

{

get

{

int _FirstIndex = 0;

if (ViewState[“_FirstIndex”] == null)

{

_FirstIndex = 0;

}

else

{

_FirstIndex = Convert.ToInt32(ViewState[“_FirstIndex”]);

}

return _FirstIndex;

}

set { ViewState[“_FirstIndex”] = value; }

}

private int lastIndex

{

get

{

int _LastIndex = 0;

if (ViewState[“_LastIndex”] == null)

{

_LastIndex = 0;

}

else

{

_LastIndex = Convert.ToInt32(ViewState[“_LastIndex”]);

}

return _LastIndex;

}

set { ViewState[“_LastIndex”] = value; }

}

#endregion

//Events of Paging

#region “Custom Paging”

protected void lbtnFirst_Click(object sender, EventArgs e)

{

CurrentPage = 0;

this.BindMngRegistration();

}

protected void lbtnPrevious_Click(object sender, EventArgs e)

{

CurrentPage -= 1;

this.BindMngRegistration();

}

protected void lbtnNext_Click(object sender, EventArgs e)

{

CurrentPage += 1;

this.BindMngRegistration();

}

protected void lbtnLast_Click(object sender, EventArgs e)

{

CurrentPage = (Convert.ToInt32(ViewState[“TotalPages”]) – 1);

this.BindMngRegistration();

}

#endregion

//total Pages

private void doPaging()

{

DataTable dt = new DataTable();

dt.Columns.Add(“PageIndex”);

dt.Columns.Add(“PageText”);

fistIndex = CurrentPage – 5;

if (CurrentPage > 5)

{

lastIndex = CurrentPage + 5;

}

else

{

lastIndex = 10;

}

if (lastIndex > Convert.ToInt32(ViewState[“TotalPages”]))

{

lastIndex = Convert.ToInt32(ViewState[“TotalPages”]);

fistIndex = lastIndex – 10;

}

if (fistIndex < 0)

{

fistIndex = 0;

}

for (int i = fistIndex; i < lastIndex; i++)

{

DataRow dr = dt.NewRow();

dr[0] = i;

dr[1] = i + 1;

dt.Rows.Add(dr);

}

this.dlPaging.DataSource = dt;

this.dlPaging.DataBind();

}

Client- Side Code

<div style=”float:right;”>

<table cellpadding=”0″ border=”0″>

<tr><td>

<asp:Label ID=”lblPageInfo” runat=”server”></asp:Label>

</td><td>&nbsp;&nbsp;</td>

<td align=”right”>

<asp:LinkButton ID=”lbtnFirst” runat=”server”

CausesValidation=”false” OnClick=”lbtnFirst_Click” CssClass=”paging”>First</asp:LinkButton>

&nbsp;</td>

<td align=”right”>

<asp:LinkButton ID=”lbtnPrevious” CssClass=”paging” runat=”server”

CausesValidation=”false” OnClick=”lbtnPrevious_Click”>Previous</asp:LinkButton>&nbsp;&nbsp;</td>

<td align=”center” valign=”middle”>

<asp:DataList ID=”dlPaging” runat=”server” RepeatDirection=”Horizontal” OnItemCommand=”dlPaging_ItemCommand”

OnItemDataBound=”dlPaging_ItemDataBound”>

<ItemTemplate>

<asp:LinkButton CssClass=”paging” ID=”lnkbtnPaging” runat=”server” CommandArgument='<%# Eval(“PageIndex”) %>’

CommandName=”Paging” Text='<%# Eval(“PageText”) %>’></asp:LinkButton>&nbsp;

</ItemTemplate>

<SeparatorTemplate>&nbsp;|&nbsp;</SeparatorTemplate>

</asp:DataList>

</td>

<td align=”left”>

&nbsp;&nbsp;<asp:LinkButton CssClass=”paging” ID=”lbtnNext” runat=”server” CausesValidation=”false”

OnClick=”lbtnNext_Click”>Next</asp:LinkButton></td>

<td align=”left”>

&nbsp;

<asp:LinkButton ID=”lbtnLast” runat=”server” CausesValidation=”false” OnClick=”lbtnLast_Click” CssClass=”paging”>Last</asp:LinkButton></td>

<td style=”padding-left:5px;”>&nbsp;</td>

</tr>

<tr>

<td colspan=”7″ align=”center” style=”display:none;” valign=”middle”>

&nbsp;</td>

</tr>

</table></div>

 
2 Comments

Posted by on June 25, 2010 in ASP Dot Net C#, Uncategorized

 

Hello world!


Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

 
Leave a comment

Posted by on June 25, 2010 in Uncategorized