Sunday, January 31, 2010

Javascript innerText alternative for Mozilla Firefox




Please visit my new Web Site WWW.Codedisplay.com



Since you are here i assume that you have already tried to work with innerText in cross-browser like mozilla firefox but you failed because in mozilla firefox the property innertext does not work. Don't there is an alternative method i will introduce in this javascript article or javascript tutorial. Before that i want to say something regarding innerHTML. Since most of the developers will suggest you to use innerHTML instead of innerText but my thought is different because if you use innerHTML instead of innerText then you may experience rendering problem due to your CSS. So i will suggest you use textContent instead of innerText for mozilla firefox will reslove your all problem. So first detect browser by javascript and then use innerText and textContent respecively like below:






Add an aspx page to test in your project. Copy and paste the below code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="innerText_textContent.aspx.cs" Inherits="innerText_textContent" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Alternative of innerText</title>
    
    <script type="text/javascript">
    function TransferValue()
    {
        var txtInfo=document.getElementById('<%= txtInfo.ClientID %>');
        var lblInfo=document.getElementById('<%= lblInfo.ClientID %>');
        if(document.all)
        {
            
            lblInfo.innerText = txtInfo.value;
        } 
        else
        {
            lblInfo.textContent = txtInfo.value;
        }
        return false;
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:TextBox ID="txtInfo" runat="server"></asp:TextBox>
    <asp:Button ID="cmdTransfer" runat="server" OnClientClick="return TransferValue();" Text="Transfer" />
    <asp:Label ID="lblInfo" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>
Run the page and you will get below interface:
Alternative innerText in mozilla firefox

Another real life example using textContent you can read:
http://shawpnendu.blogspot.com/2010/01/check-textarea-max-length-using.html

Hope now you can use both innerText and textContent based on browser.

Check TextArea Max Length using Javascript




Please visit my new Web Site WWW.Codedisplay.com



In many forums i found that Asp.Net C# VB.Net developers ask how to check max length of textarea HTML control. Thats why i think i post this topic. This article also resolve cross browser issue as well as copy paste problem in clipboard. When i am googling i found a lot of articles on this but i didn't get a javascript function which can resolve cross-browser issue as well as copy paste problem. Hope this article will help you to restrict user within your maxlength limit.

If you are looking for setting Asp.net TextBox max length using javascript then click here.

Output like:

Check TextArea Max Length

The javascript function is given below:
<script type="text/javascript">
    function ismaxlength(objTxtCtrl,nLength)
    {
        if (objTxtCtrl.getAttribute && objTxtCtrl.value.length>nLength)
            objTxtCtrl.value=objTxtCtrl.value.substring(0,nLength)
        
        if(document.all)
            document.getElementById('lblCaption').innerText=objTxtCtrl.value.length +' Out Of '+nLength;
        else
            document.getElementById('lblCaption').textContent=objTxtCtrl.value.length +' Out Of '+nLength;
        
    }
</script>
How to use from TextArea Control:
<textarea rows="5" cols="50" onkeyup="return ismaxlength(this,125)"></textarea>
<br />
<label id='lblCaption' style="font-family:Tahoma;font-size:1em;font-weight:bold"></label>
Full HTML Markup language is given below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TextArea_Max_Length.aspx.cs" Inherits="TextArea_Max_Length" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">
    <title>How to check TextArea max length using javascript</title>
    
    <script type="text/javascript">
        function ismaxlength(objTxtCtrl,nLength)
        {
            if (objTxtCtrl.getAttribute && objTxtCtrl.value.length>nLength)
                objTxtCtrl.value=objTxtCtrl.value.substring(0,nLength)
            
            if(document.all)
                document.getElementById('lblCaption').innerText=objTxtCtrl.value.length +' Out Of '+nLength;
            else
                document.getElementById('lblCaption').textContent=objTxtCtrl.value.length +' Out Of '+nLength;
            
        }
    </script>

</head>

<body>
    <form id="form1" runat="server">
    <div>
        <textarea rows="5" cols="50" onkeyup="return ismaxlength(this,125)"></textarea>
        <br />
        <label id='lblCaption' style="font-family:Tahoma;font-size:1em;font-weight:bold"></label>
    </div>
    </form>
</body>
</html>
Hope now you can apply maxlength property in textarea control.

Script tested for:
1. Internet Explorer
2. Mozilla Firefox
3. Opera
4. Google Chrome

Thursday, January 21, 2010

Merge merging or Split spliting GridView Header Row or columns in Asp.Net 2.0 / 3.5




Please visit my new Web Site WWW.Codedisplay.com



In most of the times for reporting purpose we need to merge or merging GridView header columns or rows or to use multiple headers in Asp.Net C# Vb.Net code. In this article or Asp.Net C# tutorial i will explain how one can merge or split GridView Header rows or columns. For this example here i took product table. Where In first two columns i will show Brand Name & Category Name & by spliting i will give the name hierarchy. Then i will display product name & after that i will show quantities & split & merge into three columns. So the output look like below:


To implement the above example we need to mastering in the GridView RowCreated event like below:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridView HeaderGrid = (GridView)sender;
            GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
            TableCell Cell_Header = new TableCell();
            Cell_Header.Text = "Hierarchy";
            Cell_Header.HorizontalAlign = HorizontalAlign.Center;
            Cell_Header.ColumnSpan = 2;
            HeaderRow.Cells.Add(Cell_Header);

            Cell_Header = new TableCell();
            Cell_Header.Text = "Product Name";
            Cell_Header.HorizontalAlign = HorizontalAlign.Center;
            Cell_Header.ColumnSpan = 1;
            Cell_Header.RowSpan = 2;
            HeaderRow.Cells.Add(Cell_Header);

            Cell_Header = new TableCell();
            Cell_Header.Text = "Quantity";
            Cell_Header.HorizontalAlign = HorizontalAlign.Center;
            Cell_Header.ColumnSpan = 3;
            HeaderRow.Cells.Add(Cell_Header);

            GridView1.Controls[0].Controls.AddAt(0, HeaderRow);

        }
    }
Add the GridView in your page like below:
<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" OnRowCreated="GridView1_RowCreated" OnRowDataBound="GridView1_RowDataBound" >
            <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
            <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
            <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
            <asp:BoundField DataField="Product Name" HeaderText="Product Name" />
            <asp:BoundField DataField="Logical" HeaderText="Logical" />
            <asp:BoundField DataField="Physical" HeaderText="Physical" />
            <asp:BoundField DataField="Quarentine" HeaderText="Quarentine" />
        </Columns>
        </asp:GridView>
One another tricks is to merge middle row for product name. Here i have merged the row cells within RowCreated event. The problem is we need to set visible false for bind column 'product name' in GridView HTML. To do that here i choose the GridView RowDataBound event. So that you can do what you require in runtime. Look how we can control to merging row cells:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.Cells[2].Visible = false;
    }
The complete HTML MARKUP code is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Header_Row_Split_Merge.aspx.cs" Inherits="GridView_Header_Row_Split_Merge" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>How to merge or split gridView header row</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" OnRowCreated="GridView1_RowCreated" OnRowDataBound="GridView1_RowDataBound" >
            <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
            <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
            <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
            <asp:BoundField DataField="Product Name" HeaderText="Product Name" />
            <asp:BoundField DataField="Logical" HeaderText="Logical" />
            <asp:BoundField DataField="Physical" HeaderText="Physical" />
            <asp:BoundField DataField="Quarentine" HeaderText="Quarentine" />
        </Columns>
        </asp:GridView>    
    
    </div>
    </form>
</body>
</html>
The complete Server side code is:
using System;
using System.Web.UI.WebControls;

public partial class GridView_Header_Row_Split_Merge : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = clsDBUtility.GetDataTable("SELECT B.Name [Brand Name],C.Name [Category Name], " +
            "P.Name [Product Name],P.Logical,P.Physical,P.Quarentine FROM " +
            "Brand B, Category C, Product P " +
            "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
            GridView1.DataBind();
        }
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridView HeaderGrid = (GridView)sender;
            GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
            TableCell Cell_Header = new TableCell();
            Cell_Header.Text = "Hierarchy";
            Cell_Header.HorizontalAlign = HorizontalAlign.Center;
            Cell_Header.ColumnSpan = 2;
            HeaderRow.Cells.Add(Cell_Header);

            Cell_Header = new TableCell();
            Cell_Header.Text = "Product Name";
            Cell_Header.HorizontalAlign = HorizontalAlign.Center;
            Cell_Header.ColumnSpan = 1;
            Cell_Header.RowSpan = 2;
            HeaderRow.Cells.Add(Cell_Header);

            Cell_Header = new TableCell();
            Cell_Header.Text = "Quantity";
            Cell_Header.HorizontalAlign = HorizontalAlign.Center;
            Cell_Header.ColumnSpan = 3;
            HeaderRow.Cells.Add(Cell_Header);

            GridView1.Controls[0].Controls.AddAt(0, HeaderRow);

        }
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.Cells[2].Visible = false;
    }
}
Hope now you can merge or split gridview header based on client requirements. Happy programming.

Wednesday, January 20, 2010

Download free E-commerce website templates




Please visit my new Web Site WWW.Codedisplay.com



For you means who does not designed their online Ecommerce website yet the free e-commerce website templates can provide you a pre designed solution for creating an online E-Commerce website quickly. Which will reduce your development time as well as quicker to start your business soon. Just download one of my favourite e-commerce website templates & start online business now. No need to give in website design but kepp your valuable time for SEO purpose. So that you can start your online business & earn money quickly. Lets start:

Free E-Commerce Website Template #1:

Preview & Download




Free E-Commerce Website Template #2:


Preview & Download




Free E-Commerce Website Template #3:

Preview & Download




Free E-Commerce Website Template #4:

Preview & Download




Free E-Commerce Website Template #5:

Preview & Download




Free E-Commerce Website Template #6:

Preview & Download



Hope now you can develop Ecommerce website quickly.

Searching in the GridView control with paging enabled using Asp.Net C# 2.0 / 3.5




Please visit my new Web Site WWW.Codedisplay.com



In many forums Asp.net C# Vb.Net developers ask a common question How one can search in a GridView and highlight GridView rows or record data. The answer is yes we found a lot of example on this issue and here in this example i am going to explain how you can highlight gridview rows data based on search result. As we know that GridView control is a very nice and helpful control but still can't provide us such facility to search within gridview and highlight data. To do that first add a page in your project then add a textbox and a commandbutton to search within the gridview. After that add a GridView control & bind with data. In this example i will skip how to bind data in GridvIew since its out of scope of this article. Here in this example i will show only how one can search within the GridView control easily. Also i would like to show you how you can search within gridview even the GridView has paging functionality. I would also like to show you how you can search within all Gridview rows & all columns.






Now under code file write the below two methods:
protected string HighlightText(string searchWord, string inputText)
    {
        // Replace spaces by | for Regular Expressions
        Regex expression = new Regex(search_Word.Replace(" ", "|"), RegexOptions.IgnoreCase);
        return expression.Replace(inputText, new MatchEvaluator(ReplaceKeywords));
    }

    public string ReplaceKeywords(Match m)
    {
        return "<span class='highlight'>" + m.Value + "</span>";
    }
Now under search button write the below code:
protected void cmdSearch_Click(object sender, EventArgs e)
    {
        // Assign search_Word
        search_Word = txtSearch.Text;
        RefreshData();
    }
Ohh one anotherthing is i will explain also how you can highlight gridview data based on search result even the GridView has paging functionality. To do that write the below code under PageIndexChanging event:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        search_Word = txtSearch.Text;
        RefreshData();
    }
Now look at the below GridView HTML Markup:
<asp:GridView ID="GridView1" runat="server" Width="400px" AutoGenerateColumns="False" 
        AllowPaging="true" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging">
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
            <asp:TemplateField HeaderText="Brand Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Brand Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
            <asp:TemplateField HeaderText="Category Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Category Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
            <asp:TemplateField HeaderText="Product Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Product Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
        </Columns>
        </asp:GridView>
If you have more column just apply the above technique for each column to search.

Now add the below CSS in your page:
<style type="text/css">
    .highlight
    {
        background-Color:Yellow;
    }
    </style>
The output will be:

The complete HTML markup code is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Search.aspx.cs" Inherits="GridView_Search" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>How to search within GridView</title>
    <style type="text/css">
    .highlight
    {
        background-Color:Yellow;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <asp:Button ID="cmdSearch" runat="server" Text="Search" OnClick="cmdSearch_Click" />
    <br />
        <asp:GridView ID="GridView1" runat="server" Width="400px" AutoGenerateColumns="False" 
        AllowPaging="true" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging">
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
            <asp:TemplateField HeaderText="Brand Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Brand Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
            <asp:TemplateField HeaderText="Category Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Category Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
            <asp:TemplateField HeaderText="Product Name">
            <ItemTemplate>
            <%# HighlightText(search_Word, (string)Eval("Product Name"))%>
            </ItemTemplate>
            </asp:TemplateField>         
        </Columns>
        </asp:GridView>    
    
    </div>
    </form>
</body>
</html>
The complete server side code is:
using System;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

public partial class GridView_Search : System.Web.UI.Page
{
    protected string search_Word = String.Empty;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            RefreshData();
    }

    protected string HighlightText(string searchWord, string inputText)
    {
        // Replace spaces by | for Regular Expressions
        Regex expression = new Regex(search_Word.Replace(" ", "|"), RegexOptions.IgnoreCase);
        return expression.Replace(inputText, new MatchEvaluator(ReplaceKeywords));
    }

    public string ReplaceKeywords(Match m)
    {
        return "" + m.Value + "";
    }
    
    protected void cmdSearch_Click(object sender, EventArgs e)
    {
        // Assign search_Word
        search_Word = txtSearch.Text;
        RefreshData();
    }
    
    protected void RefreshData()
    {
        // Here bind the gridview
        GridView1.DataSource = clsDBUtility.GetDataTable("SELECT B.Name [Brand Name],C.Name [Category Name], " +
        "P.Name [Product Name] FROM " +
        "Brand B, Category C, Product P " +
        "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
        GridView1.DataBind();
    }
    
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        search_Word = txtSearch.Text;
        RefreshData();
    }
}
Hope now you can search within GridView control as well as can highlight search word based on search result.

Ref: http://aspnet.4guysfromrolla.com/articles/072402-1.aspx

Sunday, January 17, 2010

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




Please visit my new Web Site WWW.Codedisplay.com



In most of the cases specially for reporting purpose we need to merge GridView cells or columns for client preferred output. In this example i will show you how one can merge GridView cells or columns in asp.net C#. My special focus is on to merge cells when both contains same or equal data. So that the GridView looks like a traditional report. For merging GridView cells here i want to show you a generic way so that you can use only one common method for all GridViews in your project where applicable. Let i have 3 tables named Brand,Category and product. I want to merge all brand & category if consecutive rows contains same data. Look at my below sample data:


If i directly bind the above data then professionally it won't acceptable to client. Look at the difference what we want to generate:


To produce aforementioned output add a class in your project and named it clsUIUtility. Then copy and paste the below code:
using System;
using System.Web.UI.WebControls;

public class clsUIUtility
{
 public clsUIUtility()
 {
 }

    public static void GridView_Row_Merger(GridView gridView)
    {
        for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
        {
            GridViewRow currentRow = gridView.Rows[rowIndex];
            GridViewRow previousRow = gridView.Rows[rowIndex + 1];

            for (int i = 0; i < currentRow.Cells.Count; i++)
            {
                if (currentRow.Cells[i].Text == previousRow.Cells[i].Text)
                {
                    if (previousRow.Cells[i].RowSpan < 2)
                        currentRow.Cells[i].RowSpan = 2;
                    else
                        currentRow.Cells[i].RowSpan = previousRow.Cells[i].RowSpan + 1;
                    previousRow.Cells[i].Visible = false;
                }
            }
        }
    }
}
Now add a page in your project. The HTML Markup code will look like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Merge.aspx.cs" Inherits="GridView_Merger" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>How to merge GridView cell or Column</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="False">
        <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
        <RowStyle BackColor="LightGray" />
        <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
             <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
             <asp:BoundField DataField="Product Name" HeaderText="Product Name" />
        </Columns>
        </asp:GridView>    
    </div>
    </form>
</body>
</html>
In serverside write the below code:
using System;

public partial class GridView_Merger : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Here i have used my own db utility class
            // Bind data in your own way..its out of scope of this article
            GridView1.DataSource = clsDBUtility.GetDataTable("SELECT B.Name [Brand Name],C.Name [Category Name], "+
            "P.Name [Product Name] FROM "+
            "Brand B, Category C, Product P "+
            "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
            GridView1.DataBind();
            clsUIUtility.GridView_Row_Merger(GridView1);
        }
    }
}
Hope now you can merge all of your GridView Cells Or Columns in Row using ASP.NET C# within your project by writing a single line. Just call the clsUIUtility.GridView_Row_Merger method and send the GridView that you want to merge for all applicable Gridviews in your project.

There is a lot of scope to modify the generic method if GridView rows contain controls like DropDwonList, CheckBoxList, RadioButtonList etc. in a template column.

Be smart & happy programming.

DropDownList RadioButtonList CheckBox CheckBoxList in GridView Edit Mode in Asp.Net




Please visit my new Web Site WWW.Codedisplay.com



Most of the Asp.net (C# or VB.Net) developers faced a problem when they want to implement edit functionality within a GridView. The problem was developers can not understand how to populate DropDownList RadioButtonList CheckBox CheckBoxList in GridView Edit Mode. The another problem is after populating how to display or show current database value by default in DropDownList RadioButtonList CheckBox CheckBoxList controls in edit mode. In this example i will give you the below solutions:

1. How to populate DropDownList while loading gridview.
2. How to set current database value as primarily selected value in DropDownList.
3. How to populate RadioButtonList while loading gridview.
4. How to set current database value as primarily selected value in RadioButtonList.
5. How to populate CheckBox while loading gridview.
6. How to set current database value as primarily selected value in CheckBox.
7. How to populate CheckBoxList while loading gridview.
8. How to set current database value as primarily selected value in CheckBoxList.

SO lets go to describe how to implement DropDownList RadioButtonList CheckBox CheckBoxList in Edit mode of GridVIew using EditItemTemaplate in ASP.NET C#. DropDownList RadioButtonList CheckBox CheckBoxList were selected in edit mode based on value saved in your SQL Server DataBase.

The output will be like this:


To do that i have followed the below table structure:


Now add a page in your project & copy the below HTML Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Edit.aspx.cs" Inherits="GridView_Edit" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Radobutton Dropdownlist in GridView Edit Mode</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" DataKeyNames="ID"  Width="100%"
            AutoGenerateColumns="False" DataSourceID="SqlDataSource1" 
            onrowdatabound="GridView1_RowDataBound" onrowupdating="GridView1_RowUpdating">
        <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
        <RowStyle BackColor="Gray" />
        <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
             <asp:BoundField DataField="Description" HeaderText="Description" />
             <asp:BoundField DataField="Color" HeaderText="Color" />
             
             <asp:TemplateField HeaderText="Size">
             <ItemTemplate>
             <asp:Label ID="lblSize" runat="server" Text='<%#Eval("Size") %>'>
             </asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:DropDownList ID="cboSize" runat="server">
             <asp:ListItem>Family</asp:ListItem>
             <asp:ListItem>Regular</asp:ListItem>
             <asp:ListItem>Standard</asp:ListItem>
             </asp:DropDownList>
             </EditItemTemplate>
             </asp:TemplateField>
             
             <asp:TemplateField HeaderText="Is Kit?">
             <ItemTemplate>
             <asp:Label ID="lblIsKit" runat="server" Text='<%#Eval("IsKit") %>'></asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:RadioButtonList ID="rdoIsKit" runat="server">
             <asp:ListItem>Product</asp:ListItem>
             <asp:ListItem>Kit</asp:ListItem>
             </asp:RadioButtonList>
             </EditItemTemplate>
             </asp:TemplateField>
             
             <asp:TemplateField HeaderText="Active?">
             <ItemTemplate>
             <asp:Label ID="lblActive" runat="server" Text='<%#Eval("Active") %>'></asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:CheckBox ID="chkActive" runat="server" Text="Active" />
             </EditItemTemplate>
             </asp:TemplateField>

             <asp:TemplateField HeaderText="Vendor Name">
             <ItemTemplate>
             <asp:Label ID="lblVendor" runat="server" Text='<%#Eval("Vendor_Name") %>'></asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:CheckBoxList ID="chkVendors" runat="server">
             <asp:ListItem>Sonali Traders</asp:ListItem>
             <asp:ListItem>Linkers</asp:ListItem>
             <asp:ListItem>Asma Associates</asp:ListItem>
             <asp:ListItem>Chameli Traders</asp:ListItem>
             </asp:CheckBoxList>
             </EditItemTemplate>
             </asp:TemplateField>

             <asp:CommandField ShowEditButton="True" />            
        </Columns>
        </asp:GridView>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:LocalConnection %>"
        
            SelectCommand="SELECT [ID], [Name], [Color], [Description], [Size], [IsKit],[Vendor_Name],[Active] FROM [Product]"
            UpdateCommand="Update Product Set [Name]=@Name,[Description]=@Description,[Color]=@Color,[Size]=@Size, [IsKit]=@IsKit,Vendor_Name=@Vendor_Name,[Active]=@Active Where [ID]=@ID">
           <UpdateParameters>
               <asp:Parameter Name="ID" />
               <asp:Parameter Name="Name" />
               <asp:Parameter Name="Description" />
               <asp:Parameter Name="Color" />
               <asp:Parameter Name="Size" />
               <asp:Parameter Name="IsKit" />
               <asp:Parameter Name="Vendor_Name" />
               <asp:Parameter Name="Active" />
           </UpdateParameters>
        </asp:SqlDataSource>    
    </div>
    </form>
</body>
</html>
Now we need to populate the controls under RowDataBound event of GridView plus need to supply update parameter while user updating the GridView. The complete server side code is given below:
using System;
using System.Data;
using System.Web.UI.WebControls;

public partial class GridView_Edit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                DropDownList cboSize = (DropDownList)e.Row.FindControl("cboSize");
                RadioButtonList rdoIsKit = (RadioButtonList)e.Row.FindControl("rdoIsKit");
                CheckBox chkActive = (CheckBox)e.Row.FindControl("chkActive");
                CheckBoxList chkVendors = (CheckBoxList)e.Row.FindControl("chkVendors");
                cboSize.SelectedValue = ((DataRowView)e.Row.DataItem)["Size"].ToString();
                if (!Convert.ToBoolean(((DataRowView)e.Row.DataItem)["IsKit"]))
                    rdoIsKit.SelectedValue = "Product";
                else
                    rdoIsKit.SelectedValue = "Kit";
                chkActive.Checked =Convert.ToBoolean(((DataRowView)e.Row.DataItem)["Active"]);
                string[] strSplitArr = ((DataRowView)e.Row.DataItem)["Vendor_Name"].ToString().Split(',');
                // Loop through all checkboxlist items
                // If matched with database table value then checked
                foreach (ListItem oItem in chkVendors.Items)
                {
                    for (int i = 0; i < strSplitArr.Length; i++)
                    {
                        if (oItem.Value == strSplitArr[i].Trim())
                        {
                            oItem.Selected = true;
                            break;
                        }
                    }
                }
            }
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        DropDownList cboSize = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cboSize");
        RadioButtonList rdoIsKit = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("rdoIsKit");
        CheckBox chkActive = (CheckBox)GridView1.Rows[e.RowIndex].FindControl("chkActive");
        CheckBoxList chkVendors = (CheckBoxList)GridView1.Rows[e.RowIndex].FindControl("chkVendors");
        SqlDataSource1.UpdateParameters["Size"].DefaultValue = cboSize.SelectedValue;
        if(rdoIsKit.SelectedValue=="Product")
            SqlDataSource1.UpdateParameters["IsKit"].DefaultValue = "0";
        else
            SqlDataSource1.UpdateParameters["IsKit"].DefaultValue = "1";
        SqlDataSource1.UpdateParameters["Active"].DefaultValue = chkActive.Checked.ToString();
        string sVendors = "";
        foreach (ListItem oItem in chkVendors.Items)
        {
            if (oItem.Selected)
            {
                if (sVendors.Length == 0)
                    sVendors = oItem.Value;
                else
                    sVendors = sVendors + "," + oItem.Value;
            }
        }
        // Here i just show you an example
        // Its not applicable in real life
        // You need to insert multiple vendor into another details table
        // Hope now you can do
        SqlDataSource1.UpdateParameters["Vendor_Name"].DefaultValue = sVendors;
    }
}
Hope now you can control DropDownList RadioButtonList CheckBox CheckBoxList within GridView in Edit Mode.

Thursday, January 14, 2010

Highlight GridView Row On MouseOver Using Javascript in Asp.net




Please visit my new Web Site WWW.Codedisplay.com



Asp.net GridView gives us huge facility that we can't imagine few years ago. But still we have a lot of chance to improve look & feel as well as GridView functionality. Here in this article i will describe how you can highlight a gridview row when move the mouse over the row and also how to retain the original background color when user leaves the mouse from a row or in mouseout event. After googling i found a lot of series on Gridview row highlighting issues but unfortunately most of them uses style sheet to change GridView row colour. But my observation is if you strict on using CSS to highlight GridView row then you will face difficulties when your Grid contains different background color for rowstyle and alternative rowstyle. I hope you will not face this problem if you use my technique. In a small quote i can say that how i can do this. First when user moves mouse pointer over the row then at first i copied the rows original color & then change the color to highlight the rows using javascript. And when user leaves the row or mouseout then i assign the previously copied color as row backgroud using javascript. So if your gridview contains different color for different row style highlight will works nicely.

As you knew that Gridview won't gives us the highlighting facility by default but we can achieve highlighting functionality by using simple javascript. To do that we need to use two javascript event. The one is onmouseover event which is also termed as Mouse Hover effect. The another one is onmouseout event. By using this two strong javascript events we will highlight our GridView rows. Ok now we know which javascript event we will use but how we can add these two javascript event handler with our GridView rows? The answer is simple. GridView gives us an event named RowCreated which we can use to bind
javascript event with our GridView rows. Let’s look how we can do this.

To do that first add a page in your project and give the name GridView_Row_Highlight.aspx. Now copy the following HTML markup code into the page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Row_Highlight.aspx.cs" Inherits="GridView_Row_Highlight" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to highlight Gridview row using javascript</title>
</head>

<body>
    <form id="form1" runat="server">
     <div>
        
 <asp:GridView ID="GridView_Products" runat="server" AutoGenerateColumns="False" 
            Width="100%" Font-Names="tahoma" onrowcreated="GridView_Products_RowCreated">
        <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
        <RowStyle BackColor="Gray" />
        <AlternatingRowStyle BackColor="LightGray" />
        <SelectedRowStyle BackColor="Pink" ForeColor="White" Font-Bold="true" />
        <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        <asp:BoundField DataField="Color" HeaderText="Color" />
        <asp:BoundField DataField="Size" HeaderText="Size" />
        <asp:CommandField ShowSelectButton="True" />
        </Columns>
        </asp:GridView>    
    
 </div>
    </form>
</body>
</html>
Now go to the code behind and write following code:
using System;
using System.Web.UI.WebControls;

public partial class GridView_Row_Highlight : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Bind your data in your own way
            GridView_Products.DataSource = clsDbUtility.ExecuteQuery("Select * FROM Product");
            GridView_Products.DataBind();
        }
    }
    protected void GridView_Products_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // When user moves mouse over the GridView row,First save original or previous color to new attribute,
            // and then change it by magenta color to highlight the gridview row.
            e.Row.Attributes.Add("onmouseover","this.previous_color=this.style.backgroundColor;this.style.backgroundColor='Magenta'");
            
            // When user leaves the mouse from the row,change the bg color 
            // or backgroud color to its previous or original value  
            e.Row.Attributes.Add("onmouseout","this.style.backgroundColor=this.previous_color;");
        }
    }
}

Now run the project & hope you will get output like below:


OK now you can highlight gridview row using javascript even your GridView row has different color for different conditions. Happy programming.

Tuesday, January 12, 2010

Read or consume RSS Feed in Asp.net 2.0/3.5




Please visit my new Web Site WWW.Codedisplay.com



In my first article i have explained "How you can create RSS feed using Asp.net". Here in this article i will explain how one can read or consume RSS Feed from Asp.net website. If you look at google reader then you will get a basic idea how one can Reading or Consuming RSS Feed from a RSS Feed link. I don't want to teach you the necessity of reading RSS in this article. So i want to start straight forward. Since in my first article i have created a RSS Feed so that open this project again and add another page and rename it to RSSFeedReader.aspx. In my local PC the RSS Feed link is: "http://localhost:50537/StudyProject/CreateRSS.aspx". Change it by copying the URL for CreateRSS.aspx page. Ok now everything is prepared to read or consume an RSS Feed from Asp.Net web application.






First add a server side table control in your RSSFeedReader.aspx page. So the complete HTML markup will be now:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RSSFeedReader.aspx.cs" Inherits="RSSFeedReader" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>RSS Feed Reader</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
 <table cellpadding="0" cellspacing="0">
        <tr>
        <td>
    
 <table class="NormalText" runat="server" id="tbl_Feed_Reader" cellpadding="0" cellspacing="0">
        </table>
        
 </td>
        </tr>
        </table>    

    </div>
    </form>
</body>
</html>
The complete server side code is given below for Reading & Consuming RSS feed is like below:
using System;
using System.Data;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Xml;
using System.IO;


public partial class RSSFeedReader : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebRequest MyRssRequest = WebRequest.Create("http://localhost:50537/StudyProject/CreateRSS.aspx");
        WebResponse MyRssResponse = MyRssRequest.GetResponse();

        Stream MyRssStream = MyRssResponse.GetResponseStream();

        // Load previously created XML Document
        XmlDocument MyRssDocument = new XmlDocument();
        MyRssDocument.Load(MyRssStream);

        XmlNodeList MyRssList = MyRssDocument.SelectNodes("rss/channel/item");

        string sTitle = "";
        string sLink = "";
        string sDescription = "";

        // Iterate/Loop through RSS Feed items
        for (int i = 0; i < MyRssList.Count; i++)
        {
            XmlNode MyRssDetail;

            MyRssDetail = MyRssList.Item(i).SelectSingleNode("title");
            if (MyRssDetail != null)
                sTitle = MyRssDetail.InnerText;
            else
                sTitle = "";

            MyRssDetail = MyRssList.Item(i).SelectSingleNode("link");
            if (MyRssDetail != null)
                sLink = MyRssDetail.InnerText;
            else
                sLink = "";

            MyRssDetail = MyRssList.Item(i).SelectSingleNode("description");
            if (MyRssDetail != null)
                sDescription = MyRssDetail.InnerText;
            else
            {
                sDescription = "";
            }

            // Now generating HTML table rows and cells based on Title,Link & Description
            HtmlTableCell block = new HtmlTableCell();
            block.InnerHtml = "<span style='font-weight:bold'><a href='" + sLink + "' target='new'>"+ sTitle + "</a></span>";
            HtmlTableRow row = new HtmlTableRow();
            row.Cells.Add(block);
            tbl_Feed_Reader.Rows.Add(row);
            HtmlTableCell block_description = new HtmlTableCell();
            block_description.InnerHtml = "<p align='justify'>" + sDescription + "</p>";
            HtmlTableRow row2 = new HtmlTableRow();
            row2.Cells.Add(block_description);
            tbl_Feed_Reader.Rows.Add(row2);
        }
    }
}

And the Output will be look like this:


So, I hope now you can Make or Create an RSS Feed as well as can read or consume RSS feed using Asp.net. Happy programming.

Tuesday, January 5, 2010

Creating RSS feed using Asp.Net 2.0 / 3.5




Please visit my new Web Site WWW.Codedisplay.com



RSS means Really Simple Syndication which is a Web content syndication format.

If you are looking for "Read/Consume RSS feed" article then click here.

Now let’s try to find out what RSS is about. Basically the website owner should return a RSS feed - and that's simply an XML document following a certain standard, describing new or latest articles on your site. When one copy your feeds & read it by a reader like goggle reader then reader get an overview of your latest articles. If reader wants to read details lets "How to make or create RSS Feed using Asp.net" then the reader will click on your Creating RSS Feed link which will redirect the user to your site.

So i hope now you can understand why Creating RSS feed is necessary for website or blog owner. In blog we will get RSS feed by default but for website you must need to create or make RSS feed for your regular readers so that all times they won’t visit your website to read your latest articles.

In most cases developers Create RSS feed from database. That’s why I will show you the way how we can achieve it. Since you are making or creating RSS feed from database so that you can Dynamically or Runtime create RSS feed from your aspx page. To do that first create the below table:


Fig: Table Structure

Enter some data like:


Fig: Sample data

Now create a new web site. Rename the default.aspx page to CreateRSS.aspx. Now open the CreateRSS.aspx page and add the below line just after the first line of the page:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="CreateRSS.aspx.cs" Inherits="_Default" %>
<%@ OutputCache Duration="120" VaryByParam="*" %>
Now go to code behind & write the code under page load event to dynamically create RSS feed using Asp.Net:
using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Text;
using System.Xml;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
        DataTable dt = new DataTable();
        SqlConnection conn = new SqlConnection(connectionString);
        using (conn)
        {
            SqlDataAdapter ad = new SqlDataAdapter("SELECT * from tblRSS", conn);
            ad.Fill(dt);
        }

        Response.Clear();
        Response.ContentType = "text/xml";
        XmlTextWriter TextWriter = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        TextWriter.WriteStartDocument();
        
        //Below tags are mandatory rss tag
        TextWriter.WriteStartElement("rss");
        TextWriter.WriteAttributeString("version", "2.0");

        // Channel tag will contain RSS feed details
        TextWriter.WriteStartElement("channel");
        TextWriter.WriteElementString("title", ".Net Mixer Free Articles");
        TextWriter.WriteElementString("link", "http://shawpnendu.blogspot.com");
        TextWriter.WriteElementString("description", "Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,XML,GridView Articles and code examples -- by Shawpnendu Bikash");
        TextWriter.WriteElementString("copyright", "Copyright 2009 - 2010 shawpnendu.blogspot.com. All rights reserved.");

        foreach (DataRow oFeedItem in dt.Rows)
        {
            TextWriter.WriteStartElement("item");
            TextWriter.WriteElementString("title", oFeedItem["Title"].ToString());
            TextWriter.WriteElementString("description", oFeedItem["Description"].ToString());
            TextWriter.WriteElementString("link", oFeedItem["URL"].ToString());
            TextWriter.WriteEndElement();
        }
        TextWriter.WriteEndElement();
        TextWriter.WriteEndElement();
        TextWriter.WriteEndDocument();
        TextWriter.Flush();
        TextWriter.Close();
        Response.End();
    }
}
Now build the project & run it hope you will get an output like below:
Create_RSS_output
So now i hope that you can runtime create RSS feed in asp.net application without help of others. In my next article i will show you how you can Read/Consume RSS feed in your asp.net aspx page.

There are more useful tags which you can use to create the RSS feed, such as the author, category or an unique ID. You found more information on Creating RSS Feed in the RSS 2.0 specification page.
Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash