Tuesday, August 27, 2013

Custom paging in Repeater control in asp.net

Repeater Paging
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Repater2.aspx.cs" Inherits="DUMMY_Repater2" %>
<!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:Repeater ID="rptBooks" runat="server">
     <HeaderTemplate>  
        <table style=" border:1px solid #c1650f; width:300px" cellpadding="0">
<tr style="background-color:#ffa100; color:White">
<td colspan="2">
<b><center>Book Details</center></b>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="background-color:#ffa100">
<td>
<table style="background-color:#f7f7f7;border-top:1px dotted #c1650f; width:300px" >
<tr>
<td>
<b>Book Name:</b>
<asp:Label ID="lblBookName" runat="server" Text='<%#Eval("Title") %>'/>
</td>
</tr>
</table>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
    </asp:Repeater>
     <div style="overflow: hidden;">
        <asp:Repeater ID="rptPaging" runat="server" onitemcommand="rptPaging_ItemCommand">
            <ItemTemplate>
                                <asp:LinkButton ID="btnPage"
                 style="padding:8px; margin:2px; background:#ffa100; border:solid 1px #666; font:8pt tahoma;"
                CommandName="Page" CommandArgument="<%# Container.DataItem %>"
                 runat="server" ForeColor="White" Font-Bold="True"><%# Container.DataItem %>
                                </asp:LinkButton>
           </ItemTemplate>
        </asp:Repeater>
        </div>
    </div>
    </form>
</body>
</html>


 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class DUMMY_Repater2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindRepeater();
        }
    }
    protected void BindRepeater()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString.ToString());
        SqlCommand cmd = new SqlCommand("Select * from Announcement", con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(dt);
        PagedDataSource pgitems = new PagedDataSource();
        DataView dv = new DataView(dt);
        pgitems.DataSource = dv;
        pgitems.AllowPaging = true;
        pgitems.PageSize = 5;//2;
        pgitems.CurrentPageIndex = PageNumber;
        if (pgitems.PageCount > 1)
        {
            rptPaging.Visible = true;
            ArrayList pages = new ArrayList();
            for (int i = 0; i < pgitems.PageCount; i++)
                pages.Add((i + 1).ToString());
            rptPaging.DataSource = pages;
            rptPaging.DataBind();
        }
        else
        {
            rptPaging.Visible = false;
        }
        rptBooks.DataSource = pgitems;
        rptBooks.DataBind();
    }
    public int PageNumber
    {
        get
        {
            if (ViewState["PageNumber"] != null)
                return Convert.ToInt32(ViewState["PageNumber"]);
            else
                return 0;
        }
        set
        {
            ViewState["PageNumber"] = value;
        }
    }
    protected void rptPaging_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
        BindRepeater();
    }
}

GridView OnCommad Event and Javascript window

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Gv3.aspx.cs" Inherits="DUMMY_Gv3" %>
<%--<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>--%>
<!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>
    <script type="text/javascript">
        //        function ShowEditForms(id, rowIndex) {
        //            window.radopen("EditUserDetail.aspx?UserID=" + id, "UserListDialog");
        //            return false;
        //        }
        function popupwindow(url, title, w, h) {
            var left = (screen.width / 2) - (w / 2);
            var top = (screen.height / 2) - (h / 2);
            return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
        } 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="Sc1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:GridView ID="GridView1" runat="server" DataKeyNames="AnnouncementID" AutoGenerateColumns="false"
            OnRowDataBound="GridView1_OnRowDataBound" OnRowCommand="GridView1_OnRowCommand"
            OnPageIndexChanging="OnPaging" AllowPaging="true" PageSize="10">
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <EditRowStyle BackColor="#2ff1BF" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="lblItemIndex" runat="server" Text='<%#Container.DataItemIndex + 1 %>'>
                        </asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <asp:Label ID="lblAnnouncementID" runat="server" Text='<%#Eval("AnnouncementID") %>'
                            Visible="false"></asp:Label>
                        <asp:LinkButton ID="lnkAnnouncementID" runat="server" Text="Edit" CommandName="Editing"
                            CommandArgument='<%#Eval("AnnouncementID") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Type">
                    <ItemTemplate>
                        <asp:Label ID="lblAnnouncementType" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Title">
                    <ItemTemplate>
                        <asp:Label ID="lblTitle" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Message">
                    <ItemTemplate>
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HyperLink ID="EditLinks" runat="server" Text="Edit"></asp:HyperLink>
                        <asp:LinkButton ID="LinkButton1" runat="server" Text="Edits"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EmptyDataTemplate>
                There are no Datas Available...
            </EmptyDataTemplate>
        </asp:GridView>
        
    </div>
    </form>
</body>
</html>


 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class DUMMY_Gv3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    private void BindGrid()
    {
        List<Announcement> objAnnouncement = AnnouncementProvider.GetAll();
        GridView1.DataSource = objAnnouncement;
        GridView1.DataBind();
    }
    protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Announcement rowData = (Announcement)e.Row.DataItem;
            LinkButton lnkAnnouncementID = (LinkButton)e.Row.FindControl("lnkAnnouncementID");
            Label lblAnnouncementType = (Label)e.Row.FindControl("lblAnnouncementType");
            Label lblTitle = (Label)e.Row.FindControl("lblTitle");
            Label lblMessage = (Label)e.Row.FindControl("lblMessage");
            lnkAnnouncementID.Text = Convert.ToString(rowData.AnnouncementId);
            lblAnnouncementType.Text = Convert.ToString(rowData.AnnouncementType);
            lblTitle.Text = Convert.ToString(rowData.Title);
            lblMessage.Text = Convert.ToString(rowData.Message);
            //HyperLink editLinks = (HyperLink)e.Row.FindControl("EditLinks");
            //editLinks.Attributes["href"] = "javascript:void(0);";
            //editLinks.Attributes.Add("onclick", String.Format("return ShowEditForms('{0}','{1}');", rowData.AnnouncementId, e.Row.RowIndex));
            //LinkButton LinkButton1 = (LinkButton)e.Row.FindControl("LinkButton1");
            //LinkButton1.Attributes.Add("onclick", String.Format("return ShowEditForms('{0}','{1}');", rowData.AnnouncementId, e.Row.RowIndex));
            HyperLink editLinks = (HyperLink)e.Row.FindControl("EditLinks");
            editLinks.Attributes["href"] = "javascript:void(0);";
            editLinks.Attributes.Add("onclick", String.Format("return popupwindow('{0}','{1}','{2}','{3}');", "EditUserDetail.aspx", "Edit", "500", "500"));
            LinkButton LinkButton1 = (LinkButton)e.Row.FindControl("LinkButton1");
            LinkButton1.Attributes.Add("onclick", String.Format("return popupwindow('{0}','{1}','{2}','{3}');", "EditUserDetail.aspx", "Edit", "500", "500"));
        }
    }
    protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
    {
        string CommandName = e.CommandName;
        if (CommandName != "Page") //because for page page index will handle it. 
        {
            Guid ID = new Guid(Convert.ToString(e.CommandArgument));
            switch (CommandName)
            {
                case "Editing":
                     // do stuff here... (window open,page redirection,or editing)
                    break;
            }
        }
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    protected void OnPaging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        //GridView1.DataBind();
        BindGrid();
    }
}

Saturday, July 13, 2013

Reading Selected Elements from XML

place.xml
-----------
<?xml version="1.0" encoding="utf-8" ?>
<Places>
  <Place>
    <Id> 1 </Id>
    <City>Chennai</City>
    <Country>INDIA </Country>
  </Place>
  <Place>
    <Id> 2 </Id>
    <City> Atlanta </City>
    <Country>USA </Country>
  </Place>
</Places>
Default.aspx
----------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default8.aspx.cs" Inherits="XML_Default8" %>
<!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 id="Head1" runat="server">
   <title>Reading XML</title>
   </head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="ddl" runat="server"></asp:DropDownList>&nbsp;<br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
    <asp:GridView ID="grxml" runat="server">
    </asp:GridView>  
    </form>
</body>
</html>
Default.aspx.cs
----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System;
using System.Data;
using System.Xml;
using System.Text;
public partial class XML_Default8 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("~/place.xml"));
            XmlNodeList bookList = doc.GetElementsByTagName("Place");
            foreach (XmlNode node in bookList)
            {
                XmlElement bookElement = (XmlElement)node;
                string ctry = bookElement.GetElementsByTagName("Country")[0].InnerText;
                ddl.Items.Add(ctry);
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("Id");
        DataColumn dc1 = new DataColumn("City");
        dt.Columns.Add(dc);
        dt.Columns.Add(dc1);
        string ct = ddl.SelectedItem.ToString();
        string dataPath = Server.MapPath("~/place.xml");
        DataSet dSet = new DataSet();
        dSet.ReadXml(dataPath);
        DataRow[] rows = dSet.Tables[0].Select(" Country = '" + ct + "'");
        foreach (DataRow dr in rows)
        {
            DataRow myRow = dt.NewRow();
            myRow["Id"] = dr["Id"];
            myRow["City"] = dr["City"];
            dt.Rows.Add(myRow);
        }
        grxml.DataSource = dt;
        grxml.DataBind();
    }
}

Read XML Data Into DataSet In Asp.Net C# VB.NET

using System.Data;
using System.IO;
protected void btnReadXmlFile_Click(object sender, EventArgs e)
    {
        string filePath = Server.MapPath("~/Employees.xml");
        DataSet dsData = new DataSet();
        //If you don't want to read through FileStream then comment below line
        FileStream fsReadSchema = new FileStream(filePath, FileMode.Open);
        dsData.ReadXml(fsReadSchema);
        fsReadSchema.Close();
        GridView1.DataSource = dsData;
        GridView1.DataBind();
    }

HOW TO: Read an XML file in ASP.NET/C#

 
XML is used almost everywhere these days to facilitate sharing data between applications, between application layers or simply as data storage. This post shows you a basic method of reading an XML file in ASP.NET and display the output on an .aspx page. We will take the following xml as an example that has information about book such as title, ISBN, and author.


<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book>
    <Title>Programming Microsoft ASP.NET 4</Title>
    <ISBN>9780735643383</ISBN>
    <Author>Dino Esposito</Author>
  </Book>
  <Book>
    <Title>Microsoft Visual C# 2010 Step by Step</Title>
    <ISBN>0735626707</ISBN>
    <Author>John Sharp</Author>
  </Book>
  <Book>
    <Title>Programming Microsoft ADO.NET Core Reference</Title>
    <ISBN>073562206X</ISBN>
    <Author>David Sceppa</Author>
  </Book>
</Books>


Here is the C# code to read the above XML file which is stored in the root application folder in the attached example and display the data on the asp.net page.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System;
using System.Data;
using System.Xml;
using System.Text;
public partial class Default8 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Bind Data to Gridview
            readXML();
        }
    }
    // This method is used to get xml node values and bind to gridview
    private void readXML()
    {
        XmlDocument doc = new XmlDocument();
        //Load XML from the file into XmlDocument object
        doc.Load(Server.MapPath("~/SampleXML.xml"));
        XmlNode root = doc.DocumentElement;
        StringBuilder sb = new StringBuilder();
	//Select all nodes with the tag Book
        XmlNodeList nodeList = root.SelectNodes("Book");
	//Loop through each node under the node “Book”
        foreach (XmlNode node in nodeList)
        {
            sb.Append("Title: ");
	    //Select the text from a single node, “Title” in this case
            sb.Append(node.SelectSingleNode("Title").InnerText);
            sb.Append("ISBN: ");
            sb.Append(node.SelectSingleNode("ISBN").InnerText);
            sb.Append("Author: ");
            sb.Append(node.SelectSingleNode("Author").InnerText);
            sb.Append("");
        }
        Response.Write(sb.ToString());
    }
}