Friday, 13 September 2013

SET PAGING IN DATALIST IN ASP.NET

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


<!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:DataList id="theDataList" runat="server">


<ItemTemplate>


<table border="0" cellpadding="0" cellspacing="0" width="500">


<tr>


<td width="140"><font size="-1" face="Verdana, Arial, Helvetica, sans-serif"><strong>Company Name</strong>:</font></td>


<td><font size="-1" face="Verdana, Arial, Helvetica, sans-serif"><%# DataBinder.Eval(Container.DataItem, "CompanyName") %></font></td>


</tr>


<tr>


<td width="110"><font size="-1" face="Verdana, Arial, Helvetica, sans-serif"><strong>Contact Name</strong>:</font></td>


<td><font size="-1" face="Verdana, Arial, Helvetica, sans-serif"><%# DataBinder.Eval(Container.DataItem, "ContactName") %></td>


</tr>


<tr>


<td width="110"><font size="-1" face="Verdana, Arial, Helvetica, sans-serif"><strong>Contact Title</strong>:</font></td>


<td><font size="-1" face="Verdana, Arial, Helvetica, sans-serif"><%# DataBinder.Eval(Container.DataItem, "ContactTitle") %></font></td>


</tr>


</table>


</ItemTemplate>


<separatortemplate>


<hr color="#0099FF" />


</separatortemplate>


</asp:DataList>
        <asp:LinkButton ID="btnFirst" runat="server" OnClick="btnFirst_Click">First</asp:LinkButton>
        <asp:LinkButton id="btnPrev" Text="Prev" OnClick="btnPrev_Click" runat="server" />
        <asp:Label ID="lblCurrentPage" runat="server"></asp:Label>


 



<asp:LinkButton id="btnNext" Text="Next" OnClick="btnNext_Click" runat="server" />
        <asp:LinkButton ID="btnLast" runat="server" OnClick="btnLast_Click">Last</asp:LinkButton></div>
    </form>
</body>
</html>
 and in code behind:
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;

public partial class Default3 : System.Web.UI.Page
{
    PagedDataSource pagedData = new PagedDataSource();
    int CurPage=1;

    void Page_Load(Object obj, EventArgs e)
    {

        doPaging();

    }

    public DataTable getTheData()
    {

        DataSet DS = new DataSet();
        SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);

        SqlDataAdapter objSQLAdapter = new SqlDataAdapter("SELECT CompanyName, ContactName, ContactTitle FROM Customers", myConnection); objSQLAdapter.Fill(DS, "Customers");


        return DS.Tables[0];

    }

    void doPaging()
    {

        pagedData.DataSource = getTheData().DefaultView;

        pagedData.AllowPaging = true;
        pagedData.PageSize = 4;



        try
        {
            if (Request["Page"].ToString() != null)
            {
                CurPage = Int32.Parse(Request["Page"].ToString());
            }
            else
            {
                CurPage = 1;
            }

            pagedData.CurrentPageIndex = CurPage - 1;

        }

        catch

        (Exception ex)
        {

            pagedData.CurrentPageIndex = 0;

        }

        btnPrev.Enabled = (!pagedData.IsFirstPage);
        //btnPrev.Visible = (!pagedData.IsFirstPage);

        btnFirst.Enabled = (!pagedData.IsFirstPage);
        
        btnNext.Enabled = (!pagedData.IsLastPage);
        //btnNext.Visible = (!pagedData.IsLastPage);

        btnLast.Enabled = (!pagedData.IsLastPage);

        //pagedData.CurrentPageIndex = CurPage - 1;

        lblCurrentPage.Text = "Page: " + CurPage.ToString() + " of " + pagedData.PageCount.ToString(); ;

        theDataList.DataSource = pagedData;
        theDataList.DataBind();

    }

    
    protected void btnPrev_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (CurPage - 1));
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (CurPage+ 1));
    }

    protected void btnFirst_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (1));
    }

    protected void btnLast_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (pagedData.PageCount));
    }
}

Simple ways to Auto Generate Serial Number in GridVie

Introduction

Sometimes we have a scenario to create a column that will auto generate the serial number, so in this post I will explain how to generate serial number in Grid View.

Simple ways to Auto Generate serial number in GridView

  •   You can do using Container.DataItemIndex in GridView

<asp:TemplateField HeaderText="Serial No">                   
                    <ItemTemplate>
                        <%#Container.DataItemIndex + 1 %>
                    </ItemTemplate>
</asp:TemplateField>



  • You can add following line of code to auto generate a column in GridView
  
<asp:TemplateField HeaderText="Serial No">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server"
                        Text='<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1 %>'>
                        </asp:Label>
                    </ItemTemplate>
</asp:TemplateField>

Changing the color of a row in a GridView in ASP.NET

This article describes changing the color of a GridView row depending on the value of a column and changing the value of a column depending on the value of that column.
First, let's start with binding a GridView with data from the database. Create a GridView.

<asp:GridView ID="grdDoc" runat="server" AllowPaging="True" 
        AutoGenerateColumns="False" DataKeyNames="DOCCODE" Height="40px" 
        PageSize="8" ShowFooter="True"   Visible="false" 
        onpageindexchanging="grdDoc_PageIndexChanging" 
        onselectedindexchanged="grdDoc_SelectedIndexChanged" >
    <PagerSettings Mode="NumericFirstLast" />
    <RowStyle BackColor="WhiteSmoke" BorderColor="CornflowerBlue" 
        ForeColor="Black" Height="30px" />
    <Columns>
        <asp:TemplateField HeaderText="Dose">
            <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" 
                      CommandName="select" 
                      Text='<%#Eval("DOCCODE")%>'>
                </asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="DOCNAME" HeaderText="Description" />
        <asp:BoundField DataField="DOCDEPT" HeaderText="Description" />
        <asp:BoundField DataField="DOCACTIVE" HeaderText="Description" />
    </Columns>
    <FooterStyle BackColor="Silver" Height="25px" />
    <PagerStyle BackColor="DarkGray" />
    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
</asp:GridView>
Load data from a database:
protected void Page_Load(object sender, EventArgs e)
{
    string strSQLconnection = 
      "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";
    SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
    SqlCommand sqlCommand = new SqlCommand("select DOCCODE,DOCNAME," + 
        "DOCDEPT, DOCACTIVE from DOCTORS", sqlConnection);
    sqlConnection.Open();
    SqlDataReader reader = sqlCommand.ExecuteReader();
    grdDoc.DataSource = reader;
    grdDoc.DataBind();
}
Change the color of a row depending on whether the Doctor is Active or Inactive.
protected void grdDoc _RowDataBound(object sender, GridViewRowEventArgs e)
{
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((string.IsNullOrEmpty(e.Row.Cells[3].Text) != true) || 
                       (e.Row.Cells[3].Text != "&nbsp;"))
            {
                Char result = Convert.ToInt32(e.Row.Cells[3].Text);
                if (result == ‘Y’) e.Row.BackColor = System.Drawing.Color.Aqua;
                else if (result ==’N’) e.Row.BackColor = System.Drawing.Color.Cornsilk;
            }
       }
    }
}
First, we need to check if the data in the fourth column is null or the column is empty. If the Doctor is Active, then the row color will be AQUA. Or else the Color of the row will be CORNSILK.
Change the Color of the cells depending on the Value of a column:
protected void grdDoc _RowDataBound(object sender, GridViewRowEventArgs e)
{
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((string.IsNullOrEmpty(e.Row.Cells[3].Text) != true) 
                  || (e.Row.Cells[3].Text != "&nbsp;"))
            {
                string result = Convert.ToInt32(e.Row.Cells[2].Text);
                if (result == “M.S”)
                    e.Row.Cells[3].BackColor= System.Drawing.Color. Aquamarine;
                else
                    e.Row.Cells[3].BackColor= System.Drawing.Color. BlanchedAlmond;
            }
        }
    }
}

How To Convert DateTime To Date(MM/dd/yyyy) Formate

 <ItemTemplate>
                    <asp:Label ID="Label9" runat="server" Text='<%#String.Format("{0:d}",Eval("FDate_Of_Opening"))%>'></asp:Label>
                </ItemTemplate>
               

HOW TO COLOR CONTROL AT RUN TIME IN ASP.NET

HOW TO COLOR CONTROL AT RUN TIME IN ASP.NET



 protected void Contorlcolor()
    {
        try
        {
            for (int i = 0; i < DataList2.Items.Count; i++)
            {
                LinkButton lblTypeall = (LinkButton)DataList2.Items[i].FindControl("LinkButton1");
                DataList dtl3 = (DataList)DataList2.Items[i].FindControl("DataList3");
                if (lblTypeall.Text == ViewState["dl2"].ToString())
                {
                    lblTypeall.ForeColor = System.Drawing.Color.Orange;

                    da = new SqlDataAdapter("select Stype from subtype where Ptype='" + ViewState["dl2"].ToString() + "'", con);
                    dt = new DataTable();
                    da.Fill(dt);
                    dtl3.DataSource = dt;
                    dtl3.DataBind();
                    for (int j = 0; j < dtl3.Items.Count; j++)
                    {
                        LinkButton dt33 = (LinkButton)dtl3.Items[j].FindControl("LinkButton1");
                        if (dt33.Text == ViewState["dl3"].ToString())
                        {
                            dt33.ForeColor = System.Drawing.Color.Orange;
                        }
                        else
                        {
                            dt33.ForeColor = System.Drawing.Color.Green;
                        }
                    }
                }
                else
                {
                    lblTypeall.ForeColor = System.Drawing.Color.Gray;
                    da = new SqlDataAdapter("select Stype from subtype where Ptype='zzzzzzzz'", con);
                    dt = new DataTable();
                    da.Fill(dt);
                    dtl3.DataSource = dt;
                    dtl3.DataBind();

                }

            }
        }
        catch (Exception)
        {
        }
    }

Printing Flow Document using WPF PrintDialog

Printing Flow Document using WPF PrintDialog



PrintDocument method accepts document in form of DocumentPaginator with print description. DocumentPaginator is a member of interfaceIDocumentPaginatorSource. To create document in WPF, majorly FlowDocument and FixedDocument classes are used. FlowDocument andFixedDocument both classes implements IDocumentPaginatorSource. So while passing FlowDocument to PrintDocument method of PrintDialog class we just need to pass DocumentPaginator of that document.

Let’s try to understand how to print FlowDocument using PrintDocument method of PrintDialog.

XAML
<Window x:Class="WpfApplication1.PrintDocumentDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Print Document Demo" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="0.9*" />
            <RowDefinition Height="0.2*"/>
        </Grid.RowDefinitions>
        <FlowDocumentReader Grid.Row="0">
            <FlowDocument Name="flowDocument">
                <Paragraph FontSize="20"
                           FontWeight="Bold">Printing document</Paragraph>
                <Paragraph FontSize="15">This is sample text to be printed.</Paragraph>
            </FlowDocument>
        </FlowDocumentReader>
        <Button Content="Print"
                Height="30" Width="150"
                Grid.Row="1" Click="Button_Click" />
    </Grid>
</Window>

Code
private void Button_Click(object sender, RoutedEventArgs e)
{
    PrintDialog pd = new PrintDialog();
    if (pd.ShowDialog() != true) return;

    flowDocument.PageHeight = pd.PrintableAreaHeight;
    flowDocument.PageWidth = pd.PrintableAreaWidth;

    IDocumentPaginatorSource idocument = flowDocument asIDocumentPaginatorSource;

    pd.PrintDocument(idocument.DocumentPaginator, "Printing Flow Document...");
}

Output




As demonstrated in above code, I have written XAML code to create FlowDocument under FlowDocumentReader and added few text lines as paragraph which I wanted to print in page when user clicks on Print button.

In code, I have created an instance of PrintDialog class and set FlowDocument height and width to match with printable area of PageDialog. After that I have called PrintDocument method of PrintDialog class and passed DocumentPaginator of FlowDocument with some description.