Showing posts with label GridView. Show all posts
Showing posts with label GridView. Show all posts

February 28, 2012

Nested GridView within Cell of a OuterGridView

Below sample code is to show how a nested gridview can be added in a GridView Cell.

DB Design
 Stuent Table
     Student _id int
     FirstName Varchar
     LastName varchar
     ContactID int


Contact table
       ContactID int
       Email varchar
       HomePhone varchar
       Mobile varchar

In a outer grid view all the data from table student will come and in column ContactId the data will be retrieved from the contact table and will be added in the inner Gridview .

Below is the code

NestedGridView .aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NestedGridView.aspx.cs" Inherits="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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="OuterGrid" runat="server" 
            onrowdatabound="OuterGrid_RowDataBound">
        </asp:GridView>
    </div>
    </form>
</body>
</html>


NestedGridView .aspx.cs


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Configuration;


public partial class NestedGridView : System.Web.UI.Page
{
   // private string connstring = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ConnectionString;
    private SqlConnection connObj;


    private SqlDataAdapter objAdapter;
    private DataSet ds = new DataSet();


    protected void Page_Load(object sender, EventArgs e)
    {


    
        if (!IsPostBack)
        {
            //Bind OuterGrid View Here
            BindOuterGridView();


        }
    }




    private void BindOuterGridView()
    {
        connObj = new SqlConnection();
        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
        connObj.Open();






        SqlCommand objCommand = new SqlCommand("Select Student_id, FirstName,LastName,Contactid from student ", connObj);


        objAdapter = new SqlDataAdapter(objCommand);






        objAdapter.Fill(ds);


        connObj.Close();




        OuterGrid.DataSource = ds.Tables[0];
        OuterGrid.DataBind();
        


    }
    protected void OuterGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //Create Inner GridView Here
        DataSet ds = new DataSet();
         GridView grd2 =new GridView ();


        GridViewRow ROW = e.Row;
        if (ROW.RowType != DataControlRowType.Header )
        {
         //  grd2 = new GridView();
            int contactID=0;


            if(e.Row.Cells[3].Text!="&nbsp;" )
             contactID = int.Parse(e.Row.Cells[3].Text);


            //grd2 = (GridView)e.Row.FindControl("grd2");
            if (contactID != 0)
            {
                connObj.Open();
                SqlCommand cmd = new SqlCommand("select * from Contact where Contactid=" + contactID, connObj);


                cmd.ExecuteNonQuery();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;


                da.Fill(ds);
                connObj.Close();


                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        //Bind Inner  GridView Here
                        grd2.DataSource = ds.Tables[0];
                        grd2.DataBind();
                    }


                    else
                    {
                        grd2.EmptyDataText = "No Data Found.";
                        grd2.DataBind();
                    }


                }
                //Add Inner GridView To Outer GridView's cell 
                e.Row.Cells[3].Controls.Add(grd2 );
            }
        }
    }
}



Below is the ScreenShot attached of the o/p


February 27, 2012

GridView Sorting for Dynamically created columns

Below is the code for sorting on columns in dynamically bounded gridview


ExGridViewSorting .aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExGridViewSorting.aspx.cs" Inherits="ExGridViewSorting" %>


<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:GridView ID="GridView1" runat="server" onsorting="GridView1_Sorting" AllowSorting="true">
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>



ExGridViewSorting .aspx.cs


using System;
using System.Collections.Generic;


using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class ExGridViewSorting : System.Web.UI.Page
{
    SqlConnection connObj = new SqlConnection();
    DataSet ds = new DataSet();
    SqlDataAdapter objAdapter;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {


            FillGrid();
        }
    }


    private void FillGrid()
    {
        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
        connObj.Open();


        SqlCommand objCommand = new SqlCommand("Select * from account", connObj);


        objAdapter = new SqlDataAdapter(objCommand);
        objAdapter.Fill(ds);
        connObj.Close();
        GridView1.DataSource = ds.Tables[0];
        ViewState["dtbl"] = ds.Tables[0];
        GridView1.DataBind();


    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dataTable = ViewState["dtbl"] as DataTable;
   
        if(dataTable!=null)
        {
        DataView  dvSortedView = new  DataView(dataTable);
       
            //string order=" asc";
            dvSortedView.Sort = e.SortExpression + " " + getSortDirection(e.SortDirection);
        GridView1.DataSource = dvSortedView;
        GridView1.DataBind();
        }
    }


    private string getSortDirection(SortDirection sortDirection)
    {
        string newSortDirection = String.Empty;


        switch (sortDirection)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;


            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }


        return newSortDirection;
    }


}









February 20, 2012

GridView Data Format in Indian Rs.

Below code will format the data in gridview cell in Indian Rs
for example 500 will be displayed as 500
and 4300 will be displayed as 4,300
and 123400 will be displayed as 1,23,400


 protected void gvActual_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            decimal d = decimal.Parse(e.Row.Cells[1].Text);                  
            e.Row.Cells[1].Text = String.Format("{0:N0}", d);


        }


    }


November 8, 2011

Set Auto generated columns as read only in Editable Grid View

Below code can be used to make read only columns in grid view


  protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        rowIndex = e.NewEditIndex;


        BindData();
        FillGrid();
    }



//Make 1,2,3,4,7,8,9 as readonly

  protected void GridView1_PreRender(object sender, EventArgs e)
    {
        if (rowIndex > -1)
        {
            if (GridView1.Rows.Count > rowIndex)
            {
                if (GridView1.Rows[rowIndex].Cells.Count > 1)
                {
                    if (GridView1.Rows[rowIndex].Cells[1].Controls.Count > 0)
                    {
                        for (int i = 1; i < 4; i++)
                        {
                            if (GridView1.Rows[rowIndex].Cells[i].Controls[0].GetType() == typeof(TextBox))
                            {
                                ((TextBox)GridView1.Rows[rowIndex].Cells[i].Controls[0]).Visible = false;
                                GridView1.Rows[rowIndex].Cells[i].Text
                                    = ((TextBox)GridView1.Rows[rowIndex].Cells[i].Controls[0]).Text;
                            }
                        }
                        for (int j = 7; j < 10; j++)
                        {
                            if (GridView1.Rows[rowIndex].Cells[j].Controls[0].GetType() == typeof(TextBox))
                            {
                                ((TextBox)GridView1.Rows[rowIndex].Cells[j].Controls[0]).Visible = false;
                                GridView1.Rows[rowIndex].Cells[j].Text
                                    = ((TextBox)GridView1.Rows[rowIndex].Cells[j].Controls[0]).Text;
                            }
                        }






                    }
                }
            }
        }
    }

June 25, 2011

Code to Populate Selected Row in Details View From ASP.NET Grid View


Example11 .aspx
<%@ Page Language="C#" ErrorPage ="~/Error.aspx" AutoEventWireup="true" CodeFile="Example11.aspx.cs" Inherits="Example11" %>


<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" 
              OnSelectedIndexChanging="GridView1_SelectedIndexChanging" 
            AutoGenerateSelectButton="true" 
            onselectedindexchanged="GridView1_SelectedIndexChanged">
        </asp:GridView>
        <asp:DetailsView ID="DetailsView1"  runat="server" Height="50px" Width="125px">
        </asp:DetailsView>
    </div>   
    </form>
</body>
</html>



Example11 .aspx.cs

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;
using System.Data.SqlClient;
using NLog;


public partial class Example11 : System.Web.UI.Page
{
    SqlConnection connObj = new SqlConnection();
    DataSet ds;
    SqlCommand objCommand;
    SqlDataAdapter objAdapter;


    protected void Page_Load(object sender, EventArgs e)     
    {
        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();

//Bind Data To grid View
            connObj.Open();
            ds = new DataSet();
            objCommand = new SqlCommand("Select * from student", connObj);
            objAdapter = new SqlDataAdapter(objCommand);
            objAdapter.Fill(ds);
            connObj.Close();


            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
    }

    protected void GridView1_SelectedIndexChanging(object sender, EventArgs e)
    {
     
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = GridView1.SelectedRow;
        int id =int.Parse ( row.Cells[1].Text );

//Bind selected row from  grid View to Details View                connObj.Open();
        ds = new DataSet();
        objCommand = new SqlCommand("Select * from student where Student_ID= " + id, connObj);
        objAdapter = new SqlDataAdapter(objCommand);
        objAdapter.Fill(ds);
        connObj.Close();


        DetailsView1 .DataSource = ds.Tables[0];
        DetailsView1.DataBind();


    }
}



Below is the Connection String in web.config file.


<add name="DotNetTrainingConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=DotNetTraining;Integrated Security=True" providerName="System.Data.SqlClient"/>

See the below o/p on 10 as selected row from the Grid