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

Multiple Selection in ASP.NET calendar control

Below is the sample code to choose and display multiple dates selected from the calendar

CalMulitpleSelection.aspx

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


<!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="Form2" runat="server">
        <h3>Using Calendar</h3>
        Please enter your requested vacation dates:
        <asp:Calendar id="Calendar1" runat="server"   selectionmode="DayWeekMonth" 
            onselectionchanged="Cal_SelectionChanged" 
            ondayrender="Calendar1_DayRender" />
        <asp:Button ID="Show" runat="server" Text="Button" onclick="Show_Click" />
        <br>
        <asp:label id="VacationLabel" runat="Server" />
    </form>
<body>


  


</html>

CalMulitpleSelection.aspx.cs


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


public partial class CalMulitpleSelection : System.Web.UI.Page
{
    public static List<string> list = new List<string>();
    protected void Page_Load(object sender, EventArgs e)
    {


    }
    protected void Cal_SelectionChanged(object sender, EventArgs e)
    {
        if (Session["SelectedDates"] != null)
        {
            List<string> selectedList = (List<string>)Session["SelectedDates"];
        foreach (string s in selectedList)
        {
            Calendar1.SelectedDates.Add(Convert.ToDateTime (s));
        }
        list.Clear();
    }
    }
    protected void Show_Click(object sender, EventArgs e)
    {
        if (Session["SelectedDates"] != null)
        {
            List<string> newList = (List<string>)Session["SelectedDates"];
            foreach (string s in newList)
            {
                Response.Write(s+ "<BR/>");
            }
        }
    }


    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        if (e.Day.IsSelected == true)
        {
            list.Add(e.Day.Date.ToString ("MM/dd/yyyy"));
        }
        Session["SelectedDates"] = list;
    }
}

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

Can anyone explain a perse error like this one: "Method 'get_EnableCdn' in type 'System.Web.UI.ScriptManager' from assembly 'System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation."


I got this error in a web application when I was   upgrading  from a Visual Studio 2008 project to a Visual Studio 2010 project.
The solution was to remove the following section from the web.config file:
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
            <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
            <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
        </dependentAssembly>
    </assemblyBinding>
</runtime>

String to DateTime Conversion ( in format "MM/dd/yyyy") in C#

Below sample code can be used to convert a string in to DateTime in MM/dd/yyyy format.



            DateTime dateValue;
            if (DateTime.TryParseExact(txtPassword.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
            {
                DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
                dtfi.ShortDatePattern = "MM/dd/yyyy";
                dtfi.DateSeparator = "/";


              DateTime convertedDate= Convert.ToDateTime(txtPassword.Text, dtfi);
            } 


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);


        }


    }