Pages

Wednesday, May 4, 2011

Nested gridview In Asp.net

Nested Gridview In Asp.net C# with toggle  

Introduction : This article describe you how add nested gridview in asp.net . Many times we require to add nested gridview .

Nested Gridview Code : I have written the html code and code behind code for binding the nested gridview .which is shown below .It is very easy to implement nested gridview in your application just you need to add it and change the connection string and query as per you requirement . I have added the toggle for nested gridview too.its toggle using javascript code.
Html code nested gridview :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="NestedGridview.aspx.cs" Inherits="HamidSite.NestedGridview" %>

<!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></title>
    <script type="text/javascript" language="javascript">
        function toggle(toggeldivid, toggeltext) {                    
            var divelement = document.getElementById(toggeldivid);
            var lbltext = document.getElementById(toggeltext);
            if (divelement.style.display == "block")
             {
                divelement.style.display = "none";              
                lbltext.innerHTML = "+ Show Orders";
            }
            else {
                divelement.style.display = "block";                
                lbltext.innerHTML = "- Hide Orders";
            }
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GVMain" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84"
            BorderColor="#DEBA84" BorderStyle="Double" BorderWidth="3px" CellPadding="5" 
            OnRowDataBound="GVMain_RowDataBound" CellSpacing="2">
            <RowStyle ForeColor="#8C4510" BackColor="#FFF7E7" />
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <asp:Label ID="lblID" Text='<%# Eval("CustomerID") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Customer Name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" Text='<%# Eval("CustomerName") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Orders">
                    <ItemTemplate>
                        <asp:Label ID="lbltoggel" runat="server" >+ Hide Orders</asp:Label>
                        <asp:Label ID="lblCustomerID" Visible="false" Text='<%# Eval("CustomerID") %>' runat="server"></asp:Label>
                        <asp:GridView ID="GVChild" style="display:block" runat="server" AutoGenerateColumns="False" BackColor="White"
                            BorderColor="#E7E7FF" BorderStyle="Solid" BorderWidth="1px" CellPadding="5" GridLines="Horizontal">
                            <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
                            <Columns>
                                <asp:TemplateField HeaderText="Order No">
                                    <ItemTemplate>
                                        <asp:Label ID="lblOrderID" Text='<%# Eval("Orderid") %>' runat="server"></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Description">
                                    <ItemTemplate>
                                        <asp:Label ID="lblTotal" Text='<%# Eval("description") %>' runat="server"></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
                            <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
                            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
                            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
                            <AlternatingRowStyle BackColor="#F7F7F7" />
                        </asp:GridView>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FFF1D4" />
            <SortedAscendingHeaderStyle BackColor="#B95C30" />
            <SortedDescendingCellStyle BackColor="#F1E5CE" />
            <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code Behind Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace HamidSite
{
    public partial class NestedGridview : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindGridview();
            }
        }
        private void bindGridview()
        {
            try
            {
                DataSet Ds = GetDataSet("Select * from Customers");
                GVMain.DataSource = Ds;                // Set DataSource Here
                GVMain.DataBind();
            }
            catch (Exception) { }
        }
        private void bindChildGridview(int customerId, GridView ChildGridview)
        {
            try
            {
                DataSet Ds = GetDataSet("Select * from CustomerOrder where customerid = "+customerId);
                ChildGridview.DataSource = Ds;                // Set DataSource Here
                ChildGridview.DataBind();
            }
            catch (Exception) { }
        }
        private DataSet GetDataSet(string Query)
        {
            DataSet Ds = new DataSet();
            try
            {
                string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True;";  //Conntection String
                SqlConnection Con = new SqlConnection(strCon);
                SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
                Da.Fill(Ds);
            }
            catch (Exception) { }
            return Ds;
        }
        protected void GVMain_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblCustomerID = (Label)e.Row.FindControl("lblCustomerID");
                Label lbltoggel = (Label)e.Row.FindControl("lbltoggel");
                
                GridView GvChild = (GridView)e.Row.FindControl("GVChild");
                bindChildGridview(Convert.ToInt32(lblCustomerID.Text), GvChild); //Bind the child gridvie here ..

                lbltoggel.Attributes.Add("onClick", "toggle('" + GvChild.ClientID + "' ,'"+lbltoggel.ClientID+"');");
            }
        }
    }
}
Happy Codding ...

Related Other posts

Create a DataTable Dynamically In C# .

Create a DataTable Dynamically In C# .

Introduction : In this article i will show you how to create DataTable Dynamically in c# .Many times we require to create a DataTable Dynamically in our code .It is very easy you just need to declare all the DataColumn and need to add in Datatable.

Dynamic DataTable code in c# :

//--Decalration Of Data Table ---//
DataTable Dt = new DataTable();

//--Decalration Of Data Column-----//
DataColumn DCID = new DataColumn("ID", typeof(Int32));
DataColumn DCName = new DataColumn("Name", typeof(String));
DataColumn DCCustomerID = new DataColumn("CustomerID", typeof(Int32));

//-- Add Data Column to DataTable --//
Dt.Columns.Add(DCID);
Dt.Columns.Add(DCName);
Dt.Columns.Add(DCCustomerID);


//-- Add Data Rows to DataTable --//
DataRow Dr1 = Dt.NewRow();
Dr1["ID"] = 1;
Dr1["Name"] = "Hamid Seta";
Dr1["CustomerID"] = 1;

DataRow Dr2 = Dt.NewRow();
Dr2["ID"] = 2;
Dr2["Name"] = "Ankur Shah";
Dr2["CustomerID"] = 2;

Dt.Rows.Add(Dr1);
Dt.Rows.Add(Dr2);



Related Other posts

Wednesday, August 18, 2010

Only Decimal values in javascript

Following is the code for only decimal allowed in javascript .

Javascript Code :-



function onlyDemialValues(objEvent, id) {


var iKeyCode;
if (window.event) // IE
{
iKeyCode = objEvent.keyCode;
}
else if (objEvent.which)  // Netscape/Firefox/Opera
{
iKeyCode = objEvent.which;
}
if (iKeyCode >= 48 && iKeyCode <= 57 || iKeyCode == 46 || iKeyCode == 8) {

if (iKeyCode == 46) {
if (document.getElementById(id).value.indexOf(".") != -1) return false;
}

return true;
}
return false;
}

Related Other posts

Friday, July 9, 2010

Table of Content In RDLC

Introduction :
This article show you how you can create Table Of Content In rdlc report . I have written step to fetch page no of the rdlc page .

 Step 1.Go In Report >> Report Properties >> Code >>

Step 2. Write Following code in Code .

Public Function GetValue(PageNo As String) As String
Dim path As String = "Test"
Dim Sb As New System.Text.StringBuilder()
Try
If Not String.IsNullOrEmpty(PageNo.Trim().Split("-"C)(1).ToString()) Then
Dim con As String = "Connection String"
Dim Cn As New System.Data.SqlClient.SqlConnection(con)
Cn.Open()
Dim Cmd As New System.Data.SqlClient.SqlCommand("INSERT INTO DATA(NAME) VALUES('" & PageNo & "')", Cn)
Cmd.ExecuteNonQuery()
Cn.Close()
End If
Return path
Catch Exc As System.Exception
Return Exc.Message
End Try
End Function

Step 3. then add following assembly In references :

System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 

Step 4.Then In header of the report In textbox write

=code.GetValue(Globals!PageNumber & " -  " &  ReportItems!textbox8.Value   )

Step 5. Finally In code behind add Following Code Lines.

ReportViewer1.LocalReport.ExecuteReportInCurrentAppDomain(AppDomain.CurrentDomain.Evidence);
ReportViewer1.LocalReport.ExecuteReportInCurrentAppDomain(System.Reflection.Assembly.GetExecutingAssembly().Evidence);
ReportViewer1.LocalReport.AddTrustedCodeModuleInCurrentAppDomain("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
ReportViewer1.LocalReport.Refresh();

Page no of Page where textbox8 reside will be insert in database .In these way you can generate Table of Content .Generate One Doc File and merge it with exported Doc File .
 

Related Other posts

Saturday, January 2, 2010

Get column values by comma separated in Sql Server

Get column values by comma separated in Sql Server
Introduction : In this article i will explain you how to get column's values by comma separated in sql server .
It is very easy to get all values of column in one string as separated by comma .

Query for get comma separated value of column in sql server :

Declare @Description varchar(4000)
select @Description = coalesce(@Description + ',' , '') + Name FROM UserTable
print @Description 


Output of query :
seta hamid , bhaumik vora ,vinayak , dave 


Related Other posts

Friday, January 1, 2010

All Sundays between two dates in asp.net C#

Find Sundays between two dates in asp.net C# .
Introduction : In this article i will show you how to get all Sundays between two dates in asp.net c# .
Following is function i have written for getting all Sundays between two dates in c# .It is very just you need to add code and you will able get all Sundays between two dates in c# . 

protected void Page_Load(object sender, EventArgs e)
{
    DateTime Dt1 = DateTime.Now;
    DateTime Dt2 = DateTime.Now.AddDays(30);
    GetAllSundays(Dt1, Dt2);
}
public void GetAllSundays(DateTime Date1, DateTime Date2)
{
    TimeSpan DateDiff = Date2.Subtract(Date1);
    for (int i = 0; i <= DateDiff.Days; i++)
    {
        if (Date1.Date.AddDays(i).DayOfWeek == DayOfWeek.Sunday)
        {
         Response.Write(Date1.Date.AddDays(i).ToLongDateString() + " " + Date1.Date.AddDays(i).DayOfWeek + "
"); } } }

Related Other posts


Find week number from Date in asp.ne c#

Find the week from the date in asp.net c# :

Introduction : This article describe you how to find week number from date in c# .I have created one function which return you week number from the date in c#  .

C# Code for finding the week number :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HamidSite
{
    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {            
            int WeekNo = GetWeeknumber(DateTime.Now);
        }
        public int GetWeeknumber(DateTime Date)
        {
            try
            {   int iMonth = Date.Month;
                int returnNumber = 0;
                for (int i = 1; i <= 5; i++)
                {
                    if (iMonth == Date.AddDays(-7 * i).Month)
                    { }
                    else
                    {
                        returnNumber = i; break;
                    }
                }
                return returnNumber;  
            }
            catch (Exception Exc) { throw Exc; }
        }
    }
}

Related Other posts