Showing posts with label Gridview. Show all posts
Showing posts with label Gridview. Show all posts

Thursday, March 1, 2012

Master page Group Radio Button problem Vertically in Gridview Control using Javascript in ASP.net C#




Please visit my new Web Site https://coderstechzone.com



In those cases where you need to choose or select one value from a list of values then grouping radio button is required. But unfortunately in ASP.Net there is no easiest built in way to group radio button vertically. But some times to meet client requirement we need to do group Radio Button vertically. It’s a grouping problem which most of the developer experience at least once in his student life or development life. Here i will try to write a javascript function to resolve Radio Button grouping problem within Gridview rows. It will also work in master page as well as in non master page. If you need to grouping Horizontally then read my THIS POST.

Output:
Problem in Grouping Radio Button

To do that we need to write a Javascript which will ensure single selection from a set of Radio Buttons in the following way:
1. First we need to know which Radio Button is clicked
2. Pass the selected Radio Button reference to the Javascript Function
3. Loop through Radio Button Array and set checked=false for others
4. Now you will get only one selected Radio Button at a time in your whole Gridview control

The complete HTML Markup is:
<script type="text/javascript">
        function GridSelection(objType)
        {
            var oItem = objType.children;
            var SelectedCtrl=(objType.type=="radio")?objType:objType.children.item[0];
            bChecked=SelectedCtrl.checked;
            arrRButtons=SelectedCtrl.form.elements;
            for(i=0;i<arrRButtons.length;i++)
            if(arrRButtons[i].type=="radio" && arrRButtons[i].id!=SelectedCtrl.id)
                arrRButtons[i].checked=!bChecked;
        }
    </script>

    <b>Who is your favourite player:</b><br />
    <asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" HorizontalAlign="Left">
        <Columns>
        <asp:boundfield datafield="Name" headertext="Super Player" />
        <asp:templatefield headertext="Choose">
            <ItemTemplate>
                <asp:radiobutton runat="server" id="chkChoose" onclick="javascript:GridSelection(this);"/>
            </ItemTemplate>
        </asp:templatefield>
        </Columns>
    </asp:GridView>
    <asp:Button runat="server" ID="cmdGet" Text="Get Selected Value" OnClick="cmdGet_Click" /><br />
    <asp:Literal runat="server" ID="ltrl"></asp:Literal>

The complete Codebehind Code is:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dtPlayers = new DataTable("Super_Player");
            dtPlayers.Columns.Add(new DataColumn("ID", System.Type.GetType("System.UInt64")));
            dtPlayers.Columns.Add(new DataColumn("Name"));
            dtPlayers.Rows.Add(1, "Leonel Messi");
            dtPlayers.Rows.Add(2, "Christiano Ronaldo");
            dtPlayers.Rows.Add(3, "Carlos Tevez");
            dtPlayers.Rows.Add(4, "Xavi");
            dtPlayers.Rows.Add(5, "Iniesta");
            GridView1.DataSource = dtPlayers;
            GridView1.DataBind();
        }
    }

    protected void cmdGet_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow oRow in GridView1.Rows)
        {
            if (((RadioButton)oRow.FindControl("chkChoose")).Checked)
                ltrl.Text = "Selected ID = " + GridView1.DataKeys[oRow.RowIndex].Value + "
 Selected Name = " + oRow.Cells[0].Text;
            // Now You can do update or delete or anything.................. Based on selection
        }
    }

Hope now you can apply single selection or group Radio Button in your Master Pages as well as normal pages. The javascirpt code is tested for Internet Explorer, Mozila Firefox, Opera, Google Chrome etc.

Leave your comment if can not implement.

Happy coding.

Read DataKeyNames value of Gridview row using Asp.net C#




Please visit my new Web Site https://coderstechzone.com



When we need to bind data in a Gridview column then we need to add an unique reference number which will help to identify a specific object or a datarow. Some developers use hidden field to store the ID column of a table on which he can INSERT UPDATE or DELETE based on hidden ID column. But this is not a good practice. Because Gridview control gives us a property named DataKeyNames on which we can assign our unique ID or code column value to distinguish invidual row. Here in this example i will show how one can read DataKeyNames value from code behind. Asp.net Gridview control also provides us a facility to assign more ID or Code type column in a single Gridview for each DataRow item specialy for composite keys of a table to bind. I have already discuss "How to use more DataKeynames in a Gridview". Also i have discuss on "Jquery to read DatakeyNames value of Selected Rows of GridView".

Sample Output:
Read Datakeynames of a Gridview row

HTML Markup Code:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" HorizontalAlign="Left">
        <Columns>
            <asp:boundfield datafield="Name" headertext="Super Player" />
        </Columns>
    </asp:GridView>

Codebehind Code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dtPlayers = new DataTable("Super_Player");
            dtPlayers.Columns.Add(new DataColumn("ID", System.Type.GetType("System.UInt64")));
            dtPlayers.Columns.Add(new DataColumn("Name"));
            dtPlayers.Rows.Add(1, "Leonel Messi");
            dtPlayers.Rows.Add(2, "Christiano Ronaldo");
            dtPlayers.Rows.Add(3, "Carlos Tevez");
            dtPlayers.Rows.Add(4, "Xavi");
            dtPlayers.Rows.Add(5, "Iniesta");
            GridView1.DataSource = dtPlayers;
            GridView1.DataBind();

            foreach (GridViewRow oRow in GridView1.Rows)
                Response.Write("DataKeyNames="+GridView1.DataKeys[oRow.RowIndex].Value + "
");
        }
    }
Hope now you can use DataKeyNames property of a Gridview control efficiently when required.

Sunday, October 10, 2010

Jquery to read DatakeyNames value of Selected Rows of GridView in Asp.Net




Please visit my new Web Site https://coderstechzone.com



As we know GridView is a very popular control. We always experiment to enhance the GridView control to provide better experience to user. Since javascript is also a popular clientside language, most of the times we use this in client side operations like validation, Row coloring, cell coloring etc. Now a days Jquery is more popular so that in this article i will explain how you can capture the selected rows of a GridView control and also read the datakeyname values using JQuery. So at first i will tell you how we capture selected rows of a GridView. In this example i don't consider the built in Select command. Instead of select command here i use checkbox to select rows by user. The another important tip is we cannot directly access DataKeyNames values of a GridView. To get the value, here I will use a template column to store the same DataKeyValue in a hiddenfield. After that through iteration by Jquery I will read the hiddenfield values which looks alike datakeynames values.

For selecting/deselecting all checkboxes of a GridView using Javascript click here.


My example output look like below:
GridView_Datakeynames_jQuery

The GridView Control HTML will be:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID">   
            <Columns>   
                <asp:TemplateField>   
                    <ItemTemplate>   
                        <asp:CheckBox ID="chkSelect" runat="server" />   
                        <asp:HiddenField ID="IDVal" runat="server" Value='<%# Eval("ID") %>' />   
                    </ItemTemplate>   
                </asp:TemplateField>   
                <asp:TemplateField>   
                    <HeaderTemplate>   
                        Name   
                    </HeaderTemplate>   
                    <ItemTemplate>   
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>   
                    </ItemTemplate>   
                </asp:TemplateField>   
            </Columns>   
        </asp:GridView>

The Jquery Script also given below:
<script type="text/javascript">   
    $(document).ready(function() {  
    var gridView1Control = document.getElementById('<%= GridView1.ClientID %>');   
    $('#<%= cmdGetData.ClientID %>').click(function (e) {
        var DataKeyName="";  
        $('input:checkbox[id$=chkSelect]:checked', gridView1Control).each(function (item, index) {   
            if(DataKeyName.length==0)
            {
                DataKeyName = $(this).next('input:hidden[id$=IDVal]').val();
            }
            else
            {
                DataKeyName += "," + $(this).next('input:hidden[id$=IDVal]').val();
            }
        });   
        alert(DataKeyName);
        return false;   
    });   
   });   
</script>

Now Bind the GridView data within Page_Load Event:
protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add("ID");
        dt.Columns.Add("Name");

        DataRow oItem = dt.NewRow();
        oItem[0] = "1";
        oItem[1] = "Shawpnendu Bikash Maloroy";
        dt.Rows.Add(oItem);

        oItem = dt.NewRow();
        oItem[0] = "2";
        oItem[1] = "Bimalendu Bikash Maloroy";
        dt.Rows.Add(oItem);

        oItem = dt.NewRow();
        oItem[0] = "3";
        oItem[1] = "Purnendu Bikash Maloroy";
        dt.Rows.Add(oItem);

        GridView1.DataSource = dt;
        GridView1.DataBind();

    }

The complete markup language of this example is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_DataKeyNames_Jquery.aspx.cs" Inherits="GridView_DataKeyNames_Jquery" %>

<!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>Get Selected rows of a GridView using Jquery</title>
<script src="Script/jquery.js" type="text/javascript"></script>

<script type="text/javascript">   
    $(document).ready(function() {  
    var gridView1Control = document.getElementById('<%= GridView1.ClientID %>');   
    $('#<%= cmdGetData.ClientID %>').click(function (e) {
        var DataKeyName="";  
        $('input:checkbox[id$=chkSelect]:checked', gridView1Control).each(function (item, index) {   
            if(DataKeyName.length==0)
            {
                DataKeyName = $(this).next('input:hidden[id$=IDVal]').val();
            }
            else
            {
                DataKeyName += "," + $(this).next('input:hidden[id$=IDVal]').val();
            }
        });   
        alert(DataKeyName);
        return false;   
    });   
   });   
</script>   
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID">   
            <Columns>   
                <asp:TemplateField>   
                    <ItemTemplate>   
                        <asp:CheckBox ID="chkSelect" runat="server" />   
                        <asp:HiddenField ID="IDVal" runat="server" Value='<%# Eval("ID") %>' />   
                    </ItemTemplate>   
                </asp:TemplateField>   
                <asp:TemplateField>   
                    <HeaderTemplate>   
                        Name   
                    </HeaderTemplate>   
                    <ItemTemplate>   
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>   
                    </ItemTemplate>   
                </asp:TemplateField>   
            </Columns>   
        </asp:GridView>   
  
        <br />   
        <asp:Button ID="cmdGetData" runat="server" Text="Get Data" />    
    </div>
    </form>
</body>
</html>

Hope you got my trick & now you can read get selected rows of a GrodView control using jQuery.

Sunday, May 16, 2010

How to read hidden field data in GridView Asp.net C#




Please visit my new Web Site https://coderstechzone.com



In some cases developers need to collect more data instead of datakeynames. In that cases developers use hidden field to retain those important data. Here in this article i wil show how one can use hidden field to store some important data & how can read those. For simplicity here i use a product table & use ID in a hidden field to read them from server side SelectedIndexChanged event. The product table looks like below:

Product

Now add a page in your project & also add a GridView like below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Hidden.aspx.cs" Inherits="GridView_Hidden" %>

<!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 read GridView Hiden Field Data</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
         <HeaderStyle BackColor="Red" Font-Bold="True" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />

         <Columns>
             <asp:CommandField ShowSelectButton="True" />

             <asp:TemplateField HeaderText="Product Name">
             <ItemTemplate>
             <asp:HiddenField runat="server" ID="HiddenField1" Value='<%#Eval("ID")%>'></asp:HiddenField>
             <asp:Label runat="server" ID="Label2" Text ='<%#Eval("Name")%>'></asp:Label>
             </ItemTemplate>
             </asp:TemplateField>

             <asp:BoundField DataField="Description" HeaderText="Description" />
             <asp:BoundField DataField="Color" HeaderText="Color" />
             <asp:BoundField DataField="Size" HeaderText="Size" />


         </Columns>
            <SelectedRowStyle BackColor="Blue" ForeColor="White" />
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>
Now under SelectedIndexChanged event write the below code to read hidden field value within gridview template column:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt = clsDBUtility.GetDataTable("SELECT * FROM PRODUCT");
            GridView1.DataSource = dt;
            GridView1.DataBind();
            Cache["Data"] = dt;
        }

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sValue = ((HiddenField)GridView1.SelectedRow.Cells[1].FindControl("HiddenField1")).Value;
        Response.Write("Product Id=" + sValue);
    }
Now run the project & will get below like output:

Output

Hope now you can read & use the hidden field vlaue from within a GridView.

Tuesday, April 20, 2010

Runtime Dynamically Creating Bound and Template Columns in GridView using Asp.net C#




Please visit my new Web Site https://coderstechzone.com



In some complex scenarios developers need to create runtime GridView dynamically. So obviously developers need to create dynamic columns for dynamic gridviews. Here in this article I will explain how one can develop or implement runtime dynamically create bound column as well as template column of a GridView control and also how to bind data into the dynamically created GridView. For simplicity here i use a datatable but you can bind data from database as well. Here I also showed how developers can write dynamic event handler for dynamically created button within the template column. The output will be:
Dynamic GridView

Creating bound column is easier than template column because if you want to add dynamic template column in your GridView then you must implement ITemplate interface. When you instantiate the implemented object then it will automatically call the "InstantiateIn" method. To implement my example first add a class in your project and named it "TemplateHandler". Then copy the code sample:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

public class TemplateHandler : ITemplate
{
    void ITemplate.InstantiateIn(Control container)
    {
        Button  cmd= new Button();
        cmd.ID = "cmd";
        cmd.Text = "HI";
        cmd.Click += new EventHandler(Dynamic_Method);
        container.Controls.Add(cmd);
    }

    protected void Dynamic_Method(object sender, EventArgs e)
    {
        ((Button)sender).Text = "Hellooooo";
    }
}

Now add a page in your project & copy the below codes under page_load event:
protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add("FirstName");
        dt.Columns.Add("LastName");
        dt.Columns.Add("Age", typeof(System.Int32));

        DataRow oItem = dt.NewRow();
        oItem[0] = "Shawpnendu";
        oItem[1] = "Bikash";
        oItem[2] = 32;
        dt.Rows.Add(oItem);

        oItem = dt.NewRow();
        oItem[0] = "Bimalendu";
        oItem[1] = "Bikash";
        oItem[2] = 27;
        dt.Rows.Add(oItem);


        GridView gv = new GridView();
        gv.AutoGenerateColumns = false;

        BoundField nameColumn = new BoundField();
        nameColumn.DataField = "FirstName";
        nameColumn.HeaderText = "First Name";
        gv.Columns.Add(nameColumn);

        nameColumn = new BoundField();
        nameColumn.DataField = "LastName";
        nameColumn.HeaderText = "Last Name";
        gv.Columns.Add(nameColumn);

        nameColumn = new BoundField();
        nameColumn.DataField = "Age";
        nameColumn.HeaderText = "Age";
        gv.Columns.Add(nameColumn);

        // Here is template column portion
        TemplateField TmpCol = new TemplateField();
        TmpCol.HeaderText = "Click Me";
        gv.Columns.Add(TmpCol);
        TmpCol.ItemTemplate = new TemplateHandler();        

        gv.DataSource = dt;
        gv.DataBind();

        Form.Controls.Add(gv);
    }

Now run the page & click on the button that i have added in a template column will say you "Helloooo".

Here i showed an example how one can create runtime gridview with bound & template column. Experiment it & hope you will achieve your client target.

Sort Sorting GridView control Manually in Asp.net C#




Please visit my new Web Site https://coderstechzone.com



Asp.net SqlDataSource control ease our lives because if you are using SqlDataSource control to bind a GridView control then no need to sorting gridview or paging gridview control since you will achieve it automatically. But if you are using different datasource like Datatable, DataSet then you need to GridView sorting manually. Here in this article I will show you how you can develop GridView Sorting easily. One thing keep in mind that When you need to sort a GridView then each time you have to bind the GridView with data.

So you have two way to hold data:
1. You can read data from database each time
2. You can store data within viewstate or cache

Here I am using asp.net cache since you knew that viewstate will increase the page response time. Ok lets start. Add a page in your project then add a GridView on it. Now from GridView properties set the AllowSorting=true. Now in your each bind column set the sortexpression like below:
<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" AllowSorting="true" OnSorting="GridView1_Sorting" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand" HeaderText="Brand Name" SortExpression="Brand"/>
             <asp:BoundField DataField="Category" HeaderText="Category Name" SortExpression="Category" />
             <asp:BoundField DataField="Product" HeaderText="Product Name" SortExpression="Product"/>
         </Columns>
        </asp:GridView>
* SortExpression must be same as DataField property.


Now in page_load method follow my below sample code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt;
            String SQL = "SELECT B.Name Brand,C.Name Category, " +
                    "P.Name Product FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3";


            string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sConstr))
            {
                using (SqlCommand comm = new SqlCommand(SQL, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
                    {
                        dt = new DataTable("tbl");
                        da.Fill(dt);
                    }
                }
            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
            Cache["dt"] = dt;
            ViewState["Column_Name"] = "Brand";
            ViewState["Sort_Order"] = "ASC";
        }
    }

From here you can change your query according to your base table. Now add the Sorting event of your gridview and write the below code:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression == ViewState["Column_Name"].ToString())
        {
            if (ViewState["Sort_Order"].ToString() == "ASC")
                RebindData(e.SortExpression, "DESC");
            else
                RebindData(e.SortExpression, "ASC");
        }
        else
            RebindData(e.SortExpression, "ASC");
    }
If you look at the code you found that here I am using a method named RebindData. The code for this method is given below:
private void RebindData(string sColimnName,string sSortOrder)
    {
        DataTable dt=(DataTable)Cache["dt"];
        dt.DefaultView.Sort = sColimnName + " " + sSortOrder;
        GridView1.DataSource = dt;
        GridView1.DataBind();
        ViewState["Column_Name"] = sColimnName;
        ViewState["Sort_Order"] = sSortOrder;
    }

Code Explanation:
Here if you look at my bind query in page_load event then you found that Brand column already sorted in ascending order thats why I have stored the Brand column name & sortorder, so that if user click again on Brand column then i need to sort the column in descending order but if user click on other column then i need to sort that column in ascending order. Hope now you can understand the logic why I use two viewstate variables ViewState["Column_Name"] and ViewState["Sort_Order"]. Basically those two variables is used to remeber user last action.

Now its your turn to make a generic sorting class for your project.

Sunday, April 18, 2010

GridView paging manually in Asp.net C#




Please visit my new Web Site https://coderstechzone.com



GridView paging will be required when data volume is higher. If you are using SqlDataSource control to bind a gridview control then no need to paging gridview because you will achieve it automatically. But if you use different datasource then you need to do mannual paging. To enable paging in gridview control at first set the AllowPaging="true" and also define the page size by PageSize="3". In asp.net paging is too much easy. You just need to set the NewPageIndex on the PageIndexChanging event. The ultimate output of my below example looks like:
GridView Paging 1

To do the paging just add a page in your project then add a gridview control on it like below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging" >
         <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>
Now under page load event first bind the data with the gridview and then cache the datasource which we will use to rebind when page index change. Sample code is given below:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt=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.DataSource = dt;
            GridView1.DataBind();
            Cache["Data"] = dt;
        }
    }
Now under gridview PageIndexChanging event write the below code:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = (DataTable)Cache["Data"];
        GridView1.DataBind();
    }
Now run the project, hope you will get paging enabled gridview.

Note: Gridview control gives us PagerSettings tag to enrich look & feel for paging navigation. By using this PagerSettings tag you can navigate from one page to another by image or text instead of default number. To use images as your navigation just use FirstPageImageUrl, LastPageImageUrl, NextPageImageUrl, PreviousPageImageUrl properties.

Now modify your gridview control like below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging" >
         <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>

         <PagerSettings 
            Position="Bottom" 
            Mode="NextPreviousFirstLast" 
            FirstPageText="First" 
            LastPageText="Last" 
            NextPageText="Next" 
            PreviousPageText="Prev"
             />
       
        </asp:GridView>
Now you will get below output:
GridView paging 2

Keep experimenting on PagerSettings tag to give the user different look and feel. Later i will discuss on efficient paging. Until then TC.

Thursday, February 25, 2010

Efficient best Syntax to Open a SqlConnection in Asp.Net 2.0 3.5




Please visit my new Web Site https://coderstechzone.com



To describe the best way to open sql server connection in asp.net here i am choosing to bind the gridview because in most of the cases the major task is to bind GridView data. You can make more generous method to collect sql server data but here my intension is to show you how you can open sql server connection efficiently.













Please have a look at the code sample:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt;
            String SQL= "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";
            

            string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sConstr))
            {
                using (SqlCommand comm = new SqlCommand(SQL, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
                    {
                        dt = new DataTable("tbl");
                        da.Fill(dt);
                    }
                }
            }
            
            GridView1.DataSource = dt;
            GridView1.DataBind();

        }

The best practice is to wrap up all code under using statement. If you look at the code you will find that i have wrapped up all code under connection object as well as sql command. Keep in mind that when corresponding "using" statement reached at the end then asp.net automatically clear all variables immediately within the scope. You do not need to dispose those manually. Such as here i don't close the connection, sqlcommand. For ease understanding here i am using datatable. You can use any ado.net component whichever you like. But keep in mind to wrap up the connection object within "Using" statement.
This is my message to you.

Wednesday, February 24, 2010

How To get RowIndex of Asp.Net GridView in the RowCommand Event




Please visit my new Web Site https://coderstechzone.com



As we know that if we add any button control or image button control or link button within the GridView and click to generate postback event then GridView RowCommand Event will fire. But the problem is from this RowCommand method we did not easily get the cliclked or selected GridView row index number. To get the RowIndex of Asp.Net GridView in the RowCommand Event we have two options.

1. Using CommandSource object
2. Using CommandArgument property

Ok our target is to add an action button within GridView rows & get the RowIndex number from RowCommand Method like below:
GridView RowCommand to get RowIndex

Using CommandSource object:
To do that first add a GridView with a LinkButton in a template field like below:
<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" >
         <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:TemplateField HeaderText="Submit" ItemStyle-HorizontalAlign="Center"> 
                <ItemTemplate> 
                <asp:LinkButton ID="lnkSubmit" runat="server" CommandName="Submit" Text="Action" ></asp:LinkButton> 
                </ItemTemplate> 
                <EditItemTemplate> 
                </EditItemTemplate> 
                </asp:TemplateField>             

         </Columns>
        </asp:GridView>
        <br />
        <hr />

        <asp:Label runat="server" ID="lblRowIndex" Font-Bold="True" Font-Size="Larger"></asp:Label>

Now go to the design mode. Right click on GridView to get property window. From event list select RowCommand event. Double click to write the method code like below:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Submit"))
        {
            GridViewRow oItem = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
            int RowIndex = oItem.RowIndex;
            lblRowIndex.Text = "Row Index = "+RowIndex.ToString();
        }
    }

Now run the page & click on any one of the Action linkbutton. The label shows the RowIndex number of your clicked Action button.


Using CommandArgument property:
To do that first add a GridView with a LinkButton in a template field like below:
<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" >
         <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:TemplateField HeaderText="Submit" ItemStyle-HorizontalAlign="Center"> 
                <ItemTemplate> 
                <asp:LinkButton ID="lnkSubmit" runat="server" CommandName="Submit" Text="Action" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' ></asp:LinkButton> 
                </ItemTemplate> 
                <EditItemTemplate> 
                </EditItemTemplate> 
                </asp:TemplateField>             

         </Columns>
        </asp:GridView>
        <br />
        <hr />

        <asp:Label runat="server" ID="lblRowIndex" Font-Bold="True" Font-Size="Larger"></asp:Label>
Now go to the design mode. Right click on GridView to get property window. From event list select RowCommand event. Double click to write the method code like below:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Submit"))
        {
            int RowIndex = Convert.ToInt32((e.CommandArgument).ToString());
            lblRowIndex.Text = "Row Index = "+RowIndex.ToString();
        }
    }

Hope now you can findout the RowIndex number of any row of the GridView whatever the control is.
Happy coding !!

Monday, February 22, 2010

How to read GridView row column data using javascript




Please visit my new Web Site https://coderstechzone.com



In some cases we need to read GridView row column data using javascript specially for search purpose. Also there were lots of reason to read GridView data using javascript. If you can read gridview data from a javascript function then you can implement lot of eye catching interface for your client.

The below javascript function wiil read gridview contents or loop through gridview rows:









function Read_Data ()
    {
        var str='';
        var Grid_Table = document.getElementById('<%= GridView1.ClientID %>');
        for(var row=1; row<Grid_Table.rows.length; row++)
        {
            for(var col=0; col<Grid_Table.rows[row].cells.length; col++)
            {
                if(col==0)
                    if(document.all)
                        str=str+Grid_Table.rows[row].cells[col].innerText;
                    else
                        str=str+Grid_Table.rows[row].cells[col].textContent;
                else
                    if(document.all)
                        str=str+'--'+Grid_Table.rows[row].cells[col].innerText;
                    else
                        str=str+'--'+Grid_Table.rows[row].cells[col].textContent;
            }
            str=str+'\n';   
        }
        alert(str);
        return false;
    }    
If you need to know the gridview row header name then start first loop from 0.

For a complete example you can add an aspx page & copy the below html markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="javascript_GridView_Read.aspx.cs" Inherits="javascript_GridView_Read" %>

<!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>Read GridView Contents using javascript</title>
<script type="text/javascript">
    function Read_Data ()
    {
        var str='';
        var Grid_Table = document.getElementById('<%= GridView1.ClientID %>');
        for(var row=1; row<Grid_Table.rows.length; row++)
        {
            for(var col=0; col<Grid_Table.rows[row].cells.length; col++)
            {
                if(col==0)
                    if(document.all)
                        str=str+Grid_Table.rows[row].cells[col].innerText;
                    else
                        str=str+Grid_Table.rows[row].cells[col].textContent;
                else
                    if(document.all)
                        str=str+'--'+Grid_Table.rows[row].cells[col].innerText;
                    else
                        str=str+'--'+Grid_Table.rows[row].cells[col].textContent;
            }
            str=str+'\n';   
        }
        alert(str);
        return false;
    }    
</script>
</head>

<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" Width="800px" 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>
        <br />
        <hr />
        <br />
        <asp:Button runat="server" ID="cmdRead" Text="Javascript to read gridview data" OnClientClick=" return Read_Data();" />
    </div>
    </form>
</body>
</html>
The serverside code is given below:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class javascript_GridView_Read : 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] FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
            GridView1.DataBind();
        }
    }
}
The output looks like:
javascript to read gridview

Hope now you can read gridview content using javascript. Happy programming.

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

Tuesday, February 16, 2010

How to Loop through GridView Rows Asp.net C#




Please visit my new Web Site https://coderstechzone.com



This is a small tips for asp.net C# vb.net novice developers. We can loop through GridView rows using two ways:

1. Use GridViewRow class to loop through or navigate the GridView rows from outsite the GridView control's event.

2. Use general for loop based on GridView Rowcount method.

In this article i will generate the following interface:
Loop gridview rows

Loop through GridView rows using GridViewRow class:
protected void cmdGridViewRow_Click(object sender, EventArgs e)
    {
        string str = "";
        foreach (GridViewRow oItem in GridView1.Rows)
            str = str + oItem.Cells[0].Text + " -- " + oItem.Cells[1].Text + " -- " + oItem.Cells[2].Text + "
";
        ltrlText.Text = str;
    }
Loop through GridView rows using simple For loop:
protected void cmdRowCount_Click(object sender, EventArgs e)
    {
        string str = "";
        for (int i = 0; i < GridView1.Rows.Count; i++)
            str = str + GridView1.Rows[i].Cells[0].Text + " -- " + GridView1.Rows[i].Cells[1].Text + " -- " + GridView1.Rows[i].Cells[2].Text + "
";
            ltrlText.Text = str;
    }
To generate the example the complete HTML markup code is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="gridview_loop.aspx.cs" Inherits="gridview_loop" %>

<!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 loop through gridview rows</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" Width="800px" 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>
        <br />
        <hr />
        <asp:Button runat="server" ID="cmdGridViewRow" Text="Loop GridViewRow" OnClick="cmdGridViewRow_Click" />
        <asp:Button runat="server" ID="cmdRowCount" Text="Loop Row Count" OnClick="cmdRowCount_Click" />
        <br />
        <hr />
        <br />
        <asp:Literal runat="server" ID="ltrlText"></asp:Literal>
    </div>
    </form>
</body>
</html>
The complete server side code is:
using System;
using System.Web.UI.WebControls;

public partial class gridview_loop : 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] 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 cmdGridViewRow_Click(object sender, EventArgs e)
    {
        string str = "";
        foreach (GridViewRow oItem in GridView1.Rows)
            str = str + oItem.Cells[0].Text + " -- " + oItem.Cells[1].Text + " -- " + oItem.Cells[2].Text + "
";
        ltrlText.Text = str;
    }
    protected void cmdRowCount_Click(object sender, EventArgs e)
    {
        string str = "";
        for (int i = 0; i < GridView1.Rows.Count; i++)
            str = str + GridView1.Rows[i].Cells[0].Text + " -- " + GridView1.Rows[i].Cells[1].Text + " -- " + GridView1.Rows[i].Cells[2].Text + "<br />";
            ltrlText.Text = str;
    }
}
Hope now you can loop through all the rows within a gridview.

Thursday, February 4, 2010

How to use more than one DataKeyNames of a GridView in asp.net 2.0 / 3.5




Please visit my new Web Site https://coderstechzone.com



In my previous article i have described "how we can remove multiple GridView rows like gmail deletion at a time". This article is the continution article. In this article i will modify the base article class file to show you how one can use more than one datakeynames in a gridview as well as in editing time or in GridView manipulation time how one can read more than one datakeynames that you have assigned in design time or in runtime. The real example is let you have a product table. Which contains productid,brandid,category id as well. Also a product may have a different category. So when you show a list of products then you have to pick a product with productid, CategoryID for deletion or modification. Here i will describe how.

DataKeyNames is the property to define Read-only primary key or composite primary key like fields in a GridView control. We can also add some more fields to this property separated by commas.

At first have a look at the below example how to assign more than one or multiple datakeynames in a gridview:
<asp:GridView runat="server" ID="GridView1" DataKeyNames="ID,BrandID,CategoryID" AutoGenerateColumns="false">
<HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="Gray" />
<AlternatingRowStyle BackColor="LightGray" />
<Columns>
    <asp:TemplateField HeaderText="Select">
    <ItemTemplate>
    <asp:CheckBox runat="server" ID="chk"/>
    </ItemTemplate>
    <HeaderTemplate>
    <input id="chkAll" onclick="javascript:GridSelectAllColumn(this, 'chk');" runat="server" type="checkbox" value="" />
    </HeaderTemplate>
    </asp:TemplateField>

     <asp:BoundField DataField="Name" HeaderText="Name"/>
     <asp:BoundField DataField="Description" HeaderText="Description" />
     <asp:BoundField DataField="Color" HeaderText="Color" />
</Columns>
</asp:GridView>
Secondly read the below codes how you can read more than one or multiple datakeynames in manipulation time:
public bool PerformDelete(GridView GV, string sTableName)
    {
        bool bSaved = false;
        string sClause = "";
        string sSQL = "";
        string sConstr = "";
        SqlConnection Conn;
        SqlCommand comm;

        sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
        foreach (GridViewRow oItem in GV.Rows)
        {
            if (((CheckBox)oItem.FindControl("chk")).Checked)
            {
                for (int i = 0; i < GV.DataKeyNames.Length; i++)
                    sClause =sClause+" AND "+ GV.DataKeyNames.GetValue(i) + "=" + GV.DataKeys[oItem.DataItemIndex][i].ToString();

                sSQL = "DELETE FROM " + sTableName + " WHERE 1=1"+sClause;
                // The above sql will generate like the below query
                // DELETE FROM product WHERE 1=1 AND ID=4 AND BrandID=2 AND CategoryID=4
                Conn = new SqlConnection(sConstr);
                using (Conn)
                {
                    try
                    {
                        Conn.Open();
                        comm = new SqlCommand(sSQL, Conn);
                        using (comm)
                        {
                            comm.CommandTimeout = 0;
                            comm.ExecuteNonQuery();
                            bSaved = true;
                        }
                    }
                    catch (Exception Ex)
                    {
                        bSaved = false;
                        // You can through error from here.
                    }
                }
            }
        }
        return bSaved;
    }
Since this article is a continution of previous one so for better understanding you can read the base article first & then read this article. But if you need only know the use of multiple datakeynames then hope my above example code segments is enough for you.

Wednesday, February 3, 2010

Enable disable show hide controls in grdview edit mode RowEditing or PreRender method




Please visit my new Web Site https://coderstechzone.com



In many asp.net (C# VB.Net) forum i found that developers ask how to enable or disable or show or hide asp.net server side controls like textbox,label,checkbox,checkboxlist,radiobutton,radiobuttonlist & dropdownlist or combo box in gridview edit mode. Everyone tries to find those controls within RowEditing event handler but they didn't get the control by using findcontrol method and editindex number. The findcontrol method will return null since in RowEditing eventhandler we didn't reference the controls in runtime data editing mode. But there is an alternative so that we can reference the above controls within gridview edit mode is PreRender method. In PreRender method we can access each edit template controls so that we can easily hide or show or enable or disable those controls.

If you want to read "DropDownList RadioButtonList CheckBox CheckBoxList in GridView Edit Mode in Asp.Net" then click here.

I have added a method named GridView1_PreRender which is a sequence of above article. So you can read first the above article & then continue with this one.

My sugession is in RowEditing method you didn't get control reference use prerender method in the following way:
protected void GridView1_PreRender(object sender, EventArgs e)
    {
        if (this.GridView1.EditIndex != -1)
        {
            DropDownList cboSize =(DropDownList)GridView1.Rows[GridView1.EditIndex].FindControl("cboSize");
            if (cboSize != null)
            {
                // You can apply condition here
                cboSize.Enabled = false;
            }

        }
    }
The output:
Show hide enable disable controls in gridview edit mode

Hope now you can get gridview row index in edit mode to enable or disable or soh or hide controls conditionaly.

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 https://coderstechzone.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

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




Please visit my new Web Site https://coderstechzone.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 https://coderstechzone.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 https://coderstechzone.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 https://coderstechzone.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.

Thursday, December 31, 2009

Display Images in GridView from Sql Server Database Table Using Asp.net C#




Please visit my new Web Site https://coderstechzone.com



In my previous post i showed you "How one can upload images into Sql Server using Asp.net C# FileUpload control". In this post i will show you how one can display images into a GridView from Sql Server table. As you know in most of the web applications requires to handle different type of images like large,thumbnail etc. If those web applications are e-commerce site then you must be carefull when handling images. In previous post i showed how you can store images & in this post i will show you how one can display images from Sql server table. The table structure is given below:




















Fig: Table structure

Displaying picture or image in a GridView is a different way then just using a image tag. In ASP.NET we can define a Handler to access the image from data base. So now we need to create a Handler to read binary data from database. To do that Right click on solution explorer and Add new item, click on Generic Handler and name it ImageHandler.ashx. Write this code in ProcessRequest method:
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public class ImageHandler : IHttpHandler 
{
    
    public void ProcessRequest (HttpContext context) 
    {
        string connectionString = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
        SqlConnection conn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Select [Content] from Images where ID =@ID";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = conn;

        SqlParameter ImageID = new SqlParameter("@ID", SqlDbType.BigInt);
        ImageID.Value = context.Request.QueryString["ID"];
        cmd.Parameters.Add(ImageID);
        conn.Open();
        SqlDataReader dReader = cmd.ExecuteReader();
        dReader.Read();
        context.Response.BinaryWrite((byte[])dReader["Content"]);
        dReader.Close();
        conn.Close();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}
Ok now add an aspx page in your project. Add a GridView control with a template field. Within the template field define image URL like below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Display_images.aspx.cs" Inherits="Display_images" %>

<!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>Display Images in GridView from SQL Server</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:GridView ID="GVImages" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="red" HeaderStyle-ForeColor="white">
        <Columns>
    
        <asp:BoundField DataField="ID" HeaderText="ID" />
        <asp:BoundField DataField="Name" HeaderText="Description" />
        <asp:BoundField DataField="Type" HeaderText="Type" />
    
        <asp:TemplateField HeaderText="Image">
        <ItemTemplate>
        <asp:Image ID="Image1" runat="server" 
                   ImageUrl='<%# "ImageHandler.ashx?ID=" + Eval("ID")%>'/>
        </ItemTemplate>
        </asp:TemplateField>
    
        </Columns>        
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>
Now everything is set except binding sql server data into the GridView. To do that write the below code in Page_Load event:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;

public partial class Display_images : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(connectionString);
            using (conn)
            {
                SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Images", conn);
                ad.Fill(dt);
            }
            GVImages.DataSource = dt;
            GVImages.DataBind();
        }
    }
}
Now run the project & hope you wil get a webpage like below:















Fig: Sample Output

So i think now you can display images from sql server table into a GridView. Happy programming.
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