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

Tuesday, May 1, 2012

Bind DropDownList in Gridview


Binding values in Dropdownlist in Gridview at runtime is not a big task.We can do it using RowDatabound event.In the given example dropdownlist is being populated at the time of editing.
At first declare a dropdownlist control in EditItemTemplate.

 <asp:TemplateField HeaderText="State" SortExpression="StateName" >
 <EditItemTemplate>
      <asp:DropDownList ID="ddlStateNm" runat="server" DataTextField="StateName"    DataValueField="StateID"> </asp:DropDownList>
      <asp:Label ID="lblStateID" runat="server" Text='<%# Bind("StateID") %>' Visible="false"></asp:Label>
 </EditItemTemplate>
 <ItemTemplate>
         <asp:Label ID="lblStateName" runat="server" Text='<%# Bind("StateName") %>'></asp:Label>
 </ItemTemplate>
</asp:TemplateField>

Write a Function to bind DropDownList.
 public void BindStateddl(DropDownList ddl)
    {
        SqlDataAdapter adp = new SqlDataAdapter("SELECT [StateID],[StateName] FROM [dbo].[MST_State] order by [StateName] asc", con);
        DataSet ds = new DataSet();
        adp.Fill(ds);


        ddl.DataSource = ds;
        ddl.DataBind();
        ddl.Items.Insert(0, new ListItem("---Select---", "0"));
    }

Now the most important part the RowDataBound event. Here at first check for DataRow so that it will overlook HeaderRow and then check for EditIndex so that Databinding to DropDownList will be implemented to editble row only.

   protected void gvCourt_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
         
            if (gvCourt.EditIndex == e.Row.RowIndex) //to overlook header row
            {
                string StateId = ((Label)e.Row.FindControl("lblStateID")).Text;


                DropDownList ddlGridState = (DropDownList)e.Row.FindControl("ddlStateNm");
           
                BindStateddl(ddlGridState);


                ddlGridState.SelectedValue = StateId;
            }
        }
    }


Saturday, April 21, 2012

Left or Right alignment in Gridview Columns

When we work with Grid-view we need to make left or right or centered alignment on column values according to their Datatype.For example we have to make right aligned all money values and character values to be left aligned. To do this just embed column within table like given example -:

 <asp:TemplateField HeaderText="Debit">
          <ItemTemplate>
                    <table align="right"  ><tr><td>
                                <asp:Label ID="lblDebit" runat="server" Text='<%# Bind("Debit") %>'></asp:Label>
                    </td></tr></table>
          </ItemTemplate>
 </asp:TemplateField>

Hope you'll get it. Enjoy coding.

Monday, March 26, 2012

Show Value upto Two Decimal Places in Gridview

Show money or float values upto two decimal places using 
String.Format in Gridview.
 
<%# String.Format("{0:f2}",DataBinder.Eval(Container.DataItem,"Rate")) %>
 or
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Amt","{0:f2}")  %>'></asp:Label> 
 
Example :  
<asp:TemplateField  HeaderText="Rate">
<ItemTemplate>
   <table align="right" style="text-align: right"><tr><td align="right">
    <asp:Label ID="lblRate" runat="server" 

Text='<%# String.Format("{0:f2}",DataBinder.Eval(Container.DataItem,"Rate")) %>' ></asp:Label>
   </td></tr></table>
</ItemTemplate>
</asp:TemplateField>

Friday, December 23, 2011

Serial No in Gridview

To show serial no in GridView just embed this code within Template Field :


<asp:TemplateField>
  <ItemTemplate>
   <table class="style2">
       <tr>
      <td>
        <%#Container.DataItemIndex+1 %>
     </td>
    </tr>
   </table>
 </ItemTemplate>
</asp:TemplateField>




Thursday, December 1, 2011

Nested Grid Through ADO.NET

Today I am going to show you how to implement the nested grid through ADO.NET. We can get various example of nested grid which are implemented through linq or sqldatasource or objectdatasource.
ScreenShots of Output are given below--:



In aspx put the grid in the given way-:
        <asp:GridView ID="gvParent" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px"
            CellPadding="3" CellSpacing="1" GridLines="None"
            onrowcommand="gvParent_RowCommand">
            <Columns>
                <asp:BoundField DataField="Grp_Id" HeaderText="ID" SortExpression="Grp_Id" />
                <asp:BoundField DataField="GrpNm" HeaderText="Name" SortExpression="GrpNm" />
                <asp:TemplateField HeaderText="Group">
                    <ItemTemplate>
                        <asp:Button ID="btnShowChild" runat="server"
                            CommandArgument='<%# Bind("Grp_Id") %>' CommandName="ShowChild" Text="+" />
                             <asp:Button ID="btnHideChild" runat="server"
                            CommandArgument='<%# Bind("Grp_Id") %>' CommandName="HideChild" Text="-" Visible="false" />
                        <asp:GridView ID="gvChild" runat="server" AutoGenerateColumns="False">
                            <Columns>
                                <asp:BoundField DataField="Acct_Id" HeaderText="AcctId"
                                    SortExpression="Acct_Id" />
                                <asp:BoundField DataField="PartyNm" HeaderText="Party Name"
                                    SortExpression="PartyNm" />
                                <asp:BoundField DataField="TempAdd" HeaderText="Address"
                                    SortExpression="TempAdd" />
                            </Columns>
                        </asp:GridView>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#594B9C" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#33276A" />
        </asp:GridView>



Code Behind File will be like this--:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbMandiConnectionString"].ConnectionString);
    string query = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindParentGrid();
        }
    }
    public void BindParentGrid()
    {
        query = "SELECT [Grp_Id] ,[GrpNm]  FROM [dbo].[tbl_Group]";
        SqlDataAdapter sdap = new SqlDataAdapter(query, con);
        DataSet ds = new DataSet();
        sdap.Fill(ds);

        gvParent.DataSource = ds;
        gvParent.DataBind();
        ds.Clear();
    }
    protected void gvParent_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName== "ShowChild")
        {
            query = "SELECT *  FROM [dbo].[tbl_AccountMaster] where [Grp_Id]="+e.CommandArgument.ToString()+"";
            SqlDataAdapter sdap = new SqlDataAdapter(query, con);
            DataSet ds = new DataSet();
            sdap.Fill(ds);
            for (int i = 0; i < gvParent.Rows.Count; i++)
            {
                if (e.CommandArgument.ToString() == (gvParent.Rows[i].Cells[0].Text))
                {
                    ((GridView)gvParent.Rows[i].FindControl("gvChild")).DataSource = ds;
                    ((GridView)gvParent.Rows[i].FindControl("gvChild")).DataBind();
                    ((Button)gvParent.Rows[i].FindControl("btnShowChild")).Visible = false;
                    ((Button)gvParent.Rows[i].FindControl("btnHideChild")).Visible = true;
                }
            }
        }
        if (e.CommandName == "HideChild")
        {
          
            for (int i = 0; i < gvParent.Rows.Count; i++)
            {
                if (e.CommandArgument.ToString() == (gvParent.Rows[i].Cells[0].Text))
                {
                    ((GridView)gvParent.Rows[i].FindControl("gvChild")).DataSource = null;
                    ((GridView)gvParent.Rows[i].FindControl("gvChild")).DataBind();
                    ((Button)gvParent.Rows[i].FindControl("btnShowChild")).Visible = true;
                    ((Button)gvParent.Rows[i].FindControl("btnHideChild")).Visible = false;
                }
            }
        }
    }
}

Tuesday, November 15, 2011

Show Total in GridView Footer

 Given Example shows you how to calculate total of particular cells value and show at the footer of Gridview.
At first define footer template in template field for which you want to calculate total.


<asp:TemplateField HeaderText="Total Pcs">
 <ItemTemplate>
          <asp:Label ID="lbltotpcs" runat="server"  Text='<%# Bind("totpcs") %>'></asp:Label>
 </ItemTemplate>
 <FooterTemplate>
        Total : <asp:Label ID="lbltotqty" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
</asp:TemplateField>


Populate the RowDataBound event of Gridview where you have to do the main calculation.

int totqty=0;
protected void gvCrate_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label totpcs = (Label)e.Row.FindControl("lbltotpcs");
            totqty = totqty + (Convert.ToInt32(totpcs.Text));
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            ((Label)e.Row.FindControl("lbltotqty")).Text = totqty.ToString();
            TxtTotalpcs.Value = totqty.ToString();
        }
    }

Enable  "ShowFooter" as True in Gridview's property.