-->

Thursday, September 5, 2013

How to bind FormView control Using SqlDataSource in ASP.NET

The FormView Control

The FormView control displays a single record from the associated data source. Each row of the table displays each field of the record. For the FormView control to display content, you need to create templates for the different parts of the control. You must create a template for the mode in which the control is configured , even trough most of the templates are optional. The FormView control exists within the System.Web.UI.WebControl interface.
To display the content through the FormView control, you need to create templates for different parts of the control. the mode of the control and template should be same. For Example. a FormView control that supports editing records must have an EditItem template.

Bind is the terms for connecting front-end to back-end simply. If you bind FormView control to database you may use SqlDatasource control.
Follow some steps for connecting front-end to back-end
After connected,  you can use Edit template property using the Show Smart tag also select paging CheckBox.
 Edit template property

A new Dialog box open after selected Edit Template . In given template you can select display template.

Display Template
There are many templates in given display template such as Item Template, Footer Template, EditItem Template , InsertItem Template , Header Template , EmptyData Template and Pager Template.
In this example we are using ItemTemplate because Item Template will show on Browser when your page first time load. So we are using horizontal ruler between the field  for formating purpose.

Display Item Template
Now , complete code is
<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
        <asp:FormView ID="FormView1" runat="server" AllowPaging="True" DataKeyNames="Id" DataSourceID="SqlDataSource1" Height="138px" Width="142px">
            <EditItemTemplate>
                Id:
                <asp:Label ID="IdLabel1" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                namet:
                <asp:TextBox ID="nametTextBox" runat="server" Text='<%# Bind("namet") %>' />
                <br />
                Income:
                <asp:TextBox ID="IncomeTextBox" runat="server" Text='<%# Bind("Income") %>' />
                <br />
                <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
                &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </EditItemTemplate>
            <InsertItemTemplate>
                namet:
                <asp:TextBox ID="nametTextBox" runat="server" Text='<%# Bind("namet") %>' />
                <br />
                Income:
                <asp:TextBox ID="IncomeTextBox" runat="server" Text='<%# Bind("Income") %>' />
                <br />
                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" />
                &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </InsertItemTemplate>
            <ItemTemplate>
                Id:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                <hr />
                <br />
                namet:
                <asp:Label ID="nametLabel" runat="server" Text='<%# Bind("namet") %>' />
                <br />
                <hr />
                <br />
                Income:
                <asp:Label ID="IncomeLabel" runat="server" Text='<%# Bind("Income") %>' />
                <br />

            </ItemTemplate>
        </asp:FormView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [footerex]"></asp:SqlDataSource>
 
    </div>
    </form>
</body>
</html>



Output
How to bind FormView control Using SqlDataSource in ASP.NET


Group Items using Group Box Control: WPF

We are using individual items all the time in our programming, doesn’t matter which programming it is. But sometimes we have to use grouping of items, so that they cannot move on their position with the resizing of the container.

For an example we cannot use two individual radio button controls to show genders on the form. Actually we can, but when we resizing the container, they may move on (from their position) a little bit. That’s why we use a group box control to place them together with a header.

Group box control is used to create a container that has some child controls and a border around them. The following code snippet (in XAML) is used to create a group box having two radio button for male and female.
<GroupBox Header="Gender">
<StackPanel>
<RadioButton Content="Male"/>
<RadioButton Content="FeMale"/>
</StackPanel>
</GroupBox>

Now the question is, why we used stack panel above. The answer is, a group box can contain only one item either it is a single item like label, textbox, radio button or it can be a container like stack panel or grid view. The image shows the output for the above code snippet

Grouping of items using GroupBox control in WPF

Here I used only two items in a group box, you can use as you want through a container. The group box can also be created using code in c# language like:
GroupBox grpBox = new GroupBox();
grpBox.Header = "Gender";

StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(new RadioButton() { Content = "Male" });
stackPanel.Children.Add(new RadioButton() { Content = "FeMale" });
grpBox.Content = stackPanel;

this.Content = grpBox;

The above code will create the same group box with two radio button in it.

Split Columns using GridSplitter Control: WPF

By default the XAML code contains a grid panel, in which we have to use other controls. The grid control can be changed if we want. The columns of a grid are of fixed size, if we are in running mode. The size can be changed during the programming session by the programmer, otherwise not.

Grid splitter is a control which provides the functionality of resizing the columns in running mode, by the user itself. The following code will place a splitter in first column to be resizable:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>


<GridSplitter Grid.Column="1" ShowsPreview="True" HorizontalAlignment="Left"
 VerticalAlignment="Stretch" Background="Black" Width="2" >

</GridSplitter>
<Label Grid.Column="0" Content="Column 1"/>
<Label Grid.Column="1" Content="Column 2"/>
<Label Grid.Column="2"  Content="Column 3"/>
</Grid>

It will show a splitter between first and second column as in following image:


Here above HorizontalAlignment property decides, on which two columns you want to resize. When it is left, the splitter will be between first and second column from the left side and if it is right, splitter will be between first and first column from the right side.

If your grid has more than one row, we can set the RowSpan property to specify the no. of rows, till where we want to split the column.

ResizeBehaviour property specifies, how the columns are resizing with some in-built values i.e. CurrentAndNext, PreviousAndNext and 2 more.

ResizeDirection property is used to determine whether the rows are resizing or columns. All the common properties are also usable like height, width, margin and etc.

How to use Expander Control: WPF

Expander control is most often used to represent data in a hierarchical view, in which a parent can be expanded or collapsed. It can only be used to expand or collapse a single item whether it is textbox, label or a grid (having multiple child controls). Just drag-n-drop it from the toolbox or write <Expander/> in XAML code to add an expander.

It has a symbol (left of the control) to expand or collapse the data contained in it. As in Visual Studio the toolbox have some categories of control i.e. Common controls and all controls which can be shown using this expander control. The following code is used to show an expander with three items:
<Expander Header="Labels">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="First Label"/>
<Label Grid.Row="1" Content="Second Label"/>
<Label Grid.Row="2"  Content="Third Label"/>
</Grid>
</Expander>

It will show an expander with header Labels and it is collapsed by default:

WPF Expander control in collapsed state

To expand these labels just click on the icon on the left and this will expanded. To expand this by default you have to set IsExpanded property to true.

WPF Expander control in expanded state

In the above code, I have used a grid view as the child element of the expander, you can use as you want. In the image the labels are just below the header. We can put some space using the margin property of the controls, as in our visual studio toolbox.

Expand direction can also be changed according to the user by using ExpandDirection property. If we want some function to be execute when it is expand then we can write that in the expanded event of this control.
private void Expander_Expanded(object sender, RoutedEventArgs e)
{
MessageBox.Show("It is Expanded");
}

The above code will show a message each time when the control is expanded.

How to use DataList Control in ASP.NET

The DataList Control

The DataList control is a Data bound control that display data by using templates. These templates define controls and HTML elements that should be displayed for an item. The DataList control exists within the System.Web.UI.WebControl namespace.
Now , lets take an example.

How to bind DataList Control using the SqlDataSource

Follow some steps for binding Datalist to SqlDataSource . Steps same as Previous post. Basically SqlDataSource is used to connect front-end to  back-end using connection string . Connection string  saved in configuration file.
Now , After establishing connection you have to use property builder through ShowSmart tag.
DataList Property builder
Select Property Builder link , Now after selected a new window will open 


dataList Properties

Run You Application

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
        <asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1" Height="285px" RepeatColumns="3" RepeatDirection="Horizontal" Width="134px">
            <ItemTemplate>
                Id:
                <asp:Label ID="IdLabel" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                namet:
                <asp:Label ID="nametLabel" runat="server" Text='<%# Eval("namet") %>' />
                <br />
                Income:
                <asp:Label ID="IncomeLabel" runat="server" Text='<%# Eval("Income") %>' />
                <br />
<br />
            </ItemTemplate>
        </asp:DataList>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [footerex]"></asp:SqlDataSource>
 
    </div>
    </form>
</body>
</html>

Output
How to use DataList Control in ASP.NET

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




© Copyright 2013 Computer Programming | All Right Reserved