-->

Wednesday, September 4, 2013

How to display total in GridView Footer in ASP.NET

Introduction
In this article i will show you how to show total of all rows of gridview column. I will give you an example of this problem.Suppose you have a one numeric type columnn in your data table and you want to add all column values.Also display sum of column in footerRow of the GridView. If we think about algorithm for this type of problem. Algorithm say that first we take a Gridview with Two template  field , One template field have one item template and one footer template such as


  <asp:TemplateField HeaderText ="Name">
                <ItemTemplate >

                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("namet") %>'>

                    </asp:Label>
               


                </ItemTemplate>
                <FooterTemplate >
                    Total:
                 
                </FooterTemplate>
            </asp:TemplateField>

Another template field have same field which is take above such as

<asp:TemplateField HeaderText ="Income">
                <ItemTemplate>
               <asp:Label ID="incomelbl" runat="server" Text='<%# Eval("Income") %>' />

                </ItemTemplate>
                <FooterTemplate >
                   <asp:Label ID="footerlbl" runat="server" Text="" />
                 
                </FooterTemplate>


            </asp:TemplateField>


This whole part cover designing


In codebehind model first we would bind GridView on page Load method. After that handle RowDataBound event . In RowDataBound event  first check Row type is DataRow.

After that find income label in Gridview using findcontrol method.

 if (e.Row.RowType ==DataControlRowType .DataRow)
        {
            var incomsal = e.Row.FindControl("incomelbl") as Label;
            if (incomsal != null)
            {
                total += int.Parse(incomsal.Text);
            }
       
        }

Here Total is a integer variable.
Now Show Total income to footer label then you must find control from the footer row on Page_Load method

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page .IsPostBack)
        {
           binddata();
           var footlbl = GridView1.FooterRow.FindControl("footerlbl") as Label;
           if (footlbl != null)
           {
               footlbl.Text  = total.ToString();
           }
        }
   
    }

    After founded , Total value assign to footer label
    Run you program.

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

<!DOCTYPE html>

<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" ShowFooter ="true" AutoGenerateColumns ="false" OnRowDataBound="GridView1_RowDataBound">
        <Columns >

            <asp:TemplateField HeaderText ="Name">
                <ItemTemplate >

                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("namet") %>'>

                    </asp:Label>
               


                </ItemTemplate>
                <FooterTemplate >
                    Total:
                 
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText ="Income">
                <ItemTemplate>
               <asp:Label ID="incomelbl" runat="server" Text='<%# Eval("Income") %>' />

                </ItemTemplate>
                <FooterTemplate >
                   <asp:Label ID="footerlbl" runat="server" Text="" />
                 
                </FooterTemplate>


            </asp:TemplateField>


        </Columns>   



    </asp:GridView>
        <asp:Label ID="result" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

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

public partial class additem : System.Web.UI.Page
{
    int total = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page .IsPostBack)
        {
           binddata();
           var footlbl = GridView1.FooterRow.FindControl("footerlbl") as Label;
           if (footlbl != null)
           {
               footlbl.Text  = total.ToString();
           }
        }
     
    }
    public void binddata()
    {
        System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
        cmd.CommandText = "Select * from [footerex]";
        cmd.Connection = con;
        System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd);
        System.Data.DataSet ds = new System.Data.DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }

 

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType ==DataControlRowType .DataRow)
        {
            var incomsal = e.Row.FindControl("incomelbl") as Label;
            if (incomsal != null)
            {
                total += int.Parse(incomsal.Text);
            }
         
        }

    }
}

Output
How to display total in GridView Footer in ASP.NET

How to find control from footer row of the GridView in ASP.NET

If you want to add Control to the footer Row in GridView, you must use footer template in GridView also set ShowFooter property is true. Also if you find control in code you can use FindControl menthod . Use single line for accessing control in code
lets take an example
Suppose your footer row take one TextBox control with id property (id="nametxt")

<FooterTemplate>
   <asp:TextBox ID="" runat="server"></asp:TextBox>

                    </FooterTemplate>

Now find TextBox control in code with simple example 

var nametextbox =GridView1.FooterRow.FindControl("nametxt")as TextBox; 


Now again your footer row take one Label control with label ID property (ID="namelbl")

<FooterTemplate>
    <asp:Label ID="namelbl" runat="server" Text="Label"></asp:Label>

                    </FooterTemplate>

Now find Label control in code with simple example

 var lbl =GridView1.FooterRow.FindControl("namelbl")as Label;

Example of How to insert item from GridView footer Row
Table Structure
How to find control from footer row of the GridView in ASP.NET


Database table
How to find control from footer row of the GridView in ASP.NET





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

<!DOCTYPE html>

<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" ShowFooter ="true" AutoGenerateColumns ="false" OnRowCommand="GridView1_RowCommand">
        <Columns >

            <asp:TemplateField HeaderText ="Press button">
                <ItemTemplate >

                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("namet") %>'></asp:Label>


                </ItemTemplate>
                <FooterTemplate >
                    <asp:Button ID="bt" runat ="server" Text ="Insert item" CommandName ="InsertRecord"/>
                 
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText ="Insert value">
                <FooterTemplate >
                    <asp:TextBox ID="txtCustomerID" runat="server" Text="" />
                 
                </FooterTemplate>


            </asp:TemplateField>


        </Columns>



     



    </asp:GridView>
        <asp:Label ID="result" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

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

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

        if (!Page .IsPostBack)
        {
           binddata();
        }
    }
    public void binddata()
    {
        System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
        cmd.CommandText = "Select * from [footerex]";
        cmd.Connection = con;
        System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd);
        System.Data.DataSet ds = new System.Data.DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }

 
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
 if (e.CommandName=="InsertRecord")
{
        var nametx = GridView1.FooterRow.FindControl("namebox") as TextBox;
        System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True");
        con.Open();
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
        cmd.Parameters.AddWithValue("@name", nametx .Text);
        cmd.CommandText = "insert into [footerex](namet)values(@name)";
        cmd.Connection = con;
        int a = cmd.ExecuteNonQuery();
        if (a > 0)
        {
            result.Text = "Row Updated";
  con.Close();
            binddata();
         

        }
        else
        {
            result.Text = "failed";
        }
}

    }
}
Output
Before insertion
How to find control from footer row of the GridView in ASP.NET
After Insertion
How to find control from footer row of the GridView in ASP.NET




Tuesday, September 3, 2013

Bind ComboBox Control With Grid Resource: WPF

In my previous post, I have wrote about the combo box control and add some string items. In this article I will add a grid source and then bind that source to combo box control with some easy steps.

By default a grid is placed in the XAML code file of a window. Just add the below code in the grid snippet:
<Grid.Resources>          
<x:ArrayExtension Type="{ x:Type sys:String}" x:Key="cmbPlacesSource">
<sys:String>London</sys:String>
<sys:String>Italy</sys:String>
<sys:String>California</sys:String>
<sys:String>France</sys:String>
</x:ArrayExtension>
</Grid.Resources>

The above code is defining an array extension which will be used as a source of the combo box. Now add a combo box and it should be look like the following code:
<ComboBox Name="cmbPlaces" Height="30" Width="100"
 Text="Select Places-"
 IsEditable="True"
 ItemsSource="{StaticResource cmbPlacesSource}">
</ComboBox>
Here in the above code, it doesn’t matter of height and width, you can provide these as you want. The must thing is ItemsSource of the combobox. As you are looking the code it is the same name of the above array extension. It will show all the data defined in the above source i.e. as in following image:

ComboBox binding with Grid Resource in WPF

In above image by default "Select Places-" is shown, which can be set by the text property with IsEditable property to true. In the selection changed event of combo box, we can get the selected value by using the following code:
private void cmbBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedValue = cmbPlaces.Text;
MessageBox.Show(selectedValue);
}

Each time when the selection index will change, it will show a message box with the selected text. So we can easily get the selected text of the combo box.

DatePicker Control in WPF

In my previous post, we have learnt about calendar control which is used to select a date through a mouse click. The DatePicker control allows the user to either typing the date or selecting it through a mouse movement. By default it shows a textbox written "Select a date" into it, and we will expand a calendar control by clicking on the right side of the control.

By using a single line i.e. <DatePicker /> a date picker control is added to the WPF window as shown in following image:


DatePicker Control in WPF

All the common properties are customizable by the programmer. Some mostly usable properties are:

  • DisplayDate: used to get or set the display date. By default it is today.
  • IsDropDownOpen: used to enable or disable the calendar control to be expand.
  • DisplayDateStart: set the first date from the control will show the dates.
  • DisplayDateEnd: set the last date till the control will show the dates.
  • FirstDayOfWeek: By default it is “Monday” and can be changed by this property.
  • SelectedDate: used to get of set the selected date. By default it is today. If it is not today then we can set it using <DatePicker SelectedDate="{x:Static sys:DateTime.Now}"/>.
  • Blackout Dates: the same procedure can be used as in calendar control.

All these properties are used in the same way in calendar control. If one want to add a DatePicker dynamically then use the following code:
DatePicker datePicker = new DatePicker();
datePicker.Name = "datePicker";
datePicker.Width = 200;
datePicker.DisplayDateStart = new DateTime(2013, 9, 1);
datePicker.DisplayDateEnd = new DateTime(2013, 9, 30);
datePicker.FirstDayOfWeek = DayOfWeek.Sunday;
datePicker.IsTodayHighlighted = true;

Now at the last add this datePicker to the desired container where you want to place.

How to Create WebPartManager Control in code

The WebPartManager Control

The WebPartManager control acts like a centralized hub that manages all the other Web Parts controls on a Web page. This control coordinates the interaction between Web Parts and Web Parts zone. The WebPartManager control manages the personalization states of Web Parts controls on a Web page. Personalization allows storing of User information and all the runtime customization (defined by the user) in a persistent storage (typically SQLServer database). These customizations are loaded when the user visits the website the next time. If you create a Web page that uses Web Parts controls, ensure that the page contains a WebPartManager control . There must be only one intance of the WebPartManager control on each Web page that uses the control, and it must be placed before other Web Parts Zone controls are placed on the Web page. The WebPartManager control is an object of the WebPartManager class.

The WebPartManager control performs the following tasks to control the functionality of a Web page.


  • Keeping track of different controls on a Web page.
  • Inserting and removing controls on a Web page 
  • Establishing , monitoring and managing connections between various Web Parts controls.
  • Enabling you to customize the appearance of a Web page by dragging various controls to different locations on the page.
  • Providing various views , Which you can use to change and personalize the properties and behavior of controls.
  • Enabling you to toggle between different views of a Web Page , Thereby simplifying certain tasks, such as modifying layout and editing controls.

Using the WebPartManager Class

The WebPartManager class allows users to toggle between various display modes . These display modes help the user to perform different actions on the Web page, such as changing the layout of a Web page or editing controls, and the rest. The WebPartManager class has the following five display modes:
BrowseDisplayMode- Specifies the default display mode for pages that contain Web Parts controls.
CatalogDisplayMode-Specifies the display mode in which a catalog of controls is visible . A user can add controls to a Web page from the catalog.
ConnectDisplayMode- Represents the display mode in which the connection UI is visible and where users can manage the connections between the controls of Web page.
DesignDisplayMode- Represents the display mode in which the user can modify the layout of a Web page.
EditDisplayMode- Specifies the display mode in which the user can change the appearance , properties and behavior of server controls.


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Create web part" OnClick="Button1_Click" />

        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>

    </div>
    </form>
</body>
</html>

Output
How to Create WebPartManager Control in code

How to Add Columns in DataGrid Control: WPF

Datagrid is used to represent a tabular view of data in programming. It have multiple template designs to be customizable by the programmer as per the requirements. It supports some other features like sorting the data, dragging columns and sometimes editing when user needs to do.


To add a DataGrid, just drag-n-drop it from the toolbox. Now it is known as a tabular representation, write following code to add some columns (3 here):
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Header="First Column"/>
<DataGridTextColumn Header="Second Column"/>
<DataGridTextColumn Header="Third Column"/>
</DataGrid.Columns>
</DataGrid>

When we run this window then a Datagrid is shown with three columns like in below image:

How to add columns in DataGrid control in WPF

DataGrid provides columns sorting, reordering and sizing with some properties like CanUserReorderColumns, CanUserResizeColumns, CanUserSortColumns and etc. We can even perform grouping of data by adding a group description for the list to be bind.

To add a datagrid using code behind:
DataGrid dataGrid = new DataGrid();

DataGridTextColumn textColumn1 = new DataGridTextColumn();
textColumn1.Header = "First Column";
DataGridTextColumn textColumn2 = new DataGridTextColumn();
textColumn2.Header = "Second Column";
DataGridTextColumn textColumn3 = new DataGridTextColumn();
textColumn3.Header = "Third Column";

dataGrid.Columns.Add(textColumn1);
dataGrid.Columns.Add(textColumn2);
dataGrid.Columns.Add(textColumn3);

The above code snippet add a same datagrid with three columns as in above image. We will learn binding of datagrid in later articles.

How to bind Chart Control in ASP.NET

A graph or chart diagram represents your set of data.If you want to show your company report then you must use chart control. There are different types of chart show different types of data such as



How to bind Chart Control in ASP.NET
Pie Chart
Using the pie-chart you can classify your data in graphical format. According to above diagram your movie are divided in different sections such as Action take 18% of whole movie as well as 11% take Horror.

Example of How to bind Chart Control using SqlDataSource
Step-1: Create Database Table in visual studio.

Chart Database table

.
Step-2: Bind connection with Database using SqlDataSource
<%@ Register assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="System.Web.UI.DataVisualization.Charting" tagprefix="asp" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Chart ID="Chart1" runat="server" DataSourceID="SqlDataSource1" OnLoad="Chart1_Load">
            <series>
                <asp:Series ChartType="Pie" Name="Series1" XValueMember="movie_type" YValueMembers="percentage">
                </asp:Series>
            </series>
            <chartareas>
                <asp:ChartArea Name="ChartArea1">
                    <Area3DStyle Enable3D="True" />
                </asp:ChartArea>
            </chartareas>
        </asp:Chart>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [movie]"></asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Output
How to bind Chart Control in ASP.NET

© Copyright 2013 Computer Programming | All Right Reserved