Vinit Patel

In The News.aspx Page

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

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”gvNews” runat=”server” AutoGenerateColumns=”false” ShowHeader=”false”>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID=”mylink” runat=”server” Text='<%# Eval(“Title”) %>’ NavigateUrl='<%# “~/NewsDetails.aspx?nid=” + DataBinder.Eval(Container, “RowIndex”) %>’></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

Codebehind in News.aspx page,

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;

public partial class News : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Gets the xml from the Url using XmlTextReader
XmlTextReader reader = new XmlTextReader(“http://www.rediff.com/rss/newsrss.xml&#8221;);
// creates a new instance of DataSet
DataSet ds = new DataSet();
// Reads the xml into the dataset
ds.ReadXml(reader);
// Assigns the data table to the datagrid
gvNews.DataSource = ds.Tables[3];
// Binds the datagrid
gvNews.DataBind();
}
}
}

In NewsDetails.aspx Page,

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

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<iframe id=”myiframe” runat=”server” width=”100%” height=”600px”></iframe>
</div>
</form>
</body>
</html>

In Codebehind of NewsDetails.aspx page,

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;

public partial class NewsDetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString[“nid”] != null)
{
// Gets the xml from the Url using XmlTextReader
XmlTextReader reader = new XmlTextReader(“http://www.rediff.com/rss/newsrss.xml&#8221;);
// creates a new instance of DataSet
DataSet ds = new DataSet();
// Reads the xml into the dataset
ds.ReadXml(reader);

Int32 index = 0;
Int32.TryParse(Request.QueryString[“nid”].ToString(), out index);
string link = ds.Tables[3].Rows[index][“link”].ToString();

myiframe.Attributes.Add(“src”, link);
}
}
}

Advertisements

Declare a public string in the partial class of the CS file. like

public string str;

now place the str in the aspx file where you need to create the multiple textboxes like this

<%=str%>

now in the button click event using stringbuilder append the code that is used to create the TextBoxes dynamically like this

StringBuilder sb=new  StringBuilder();

sb.Append(“<asp:TextBox id=”xxx” runat=”server”/>”);

like this u can bind number of TextBoxes.

now assign this “sb” to the “str”

str=sb.ToString();

your Textboxes get created in the aspx file.

I’m going to provide a simple example how to display hierarchical data

from SQL Server database in the TreeView. A requirement is that the

implementation should not be dependant on the hierarchy level in the

database. It means that the TreeView implementation should be capable

of displaying data from any level, no matter how deep.

TreeviewEx.aspx

<asp:treeview id="tvCategoryList" runat="server" imageset="BulletedList3"
width="100%"

    showexpandcollapse="True" nodewrap="True"
     ontreenodepopulate="tvCategoryList_TreeNodePopulate"

    expanddepth="2" populatenodesfromclient="False">

    <ParentNodeStyle Font-Bold="True" />

    <RootNodeStyle Font-Bold="True" 
         CssClass="Table_Title_Label_Black12" />

    <HoverNodeStyle Font-Underline="True"
             ForeColor="#5555DD" />

    <SelectedNodeStyle Font-Underline="True"
       HorizontalPadding="0px" VerticalPadding="0px"
         ForeColor="#5555DD" />

    <NodeStyle Font-Names="Verdana" Font-Size="8pt"
      ForeColor="Black" HorizontalPadding="0px" 
      NodeSpacing="0px" VerticalPadding="0px" />

</asp:treeview>

 

Treeview.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

        PopulateRootLevel();

    }

}

This happens by connecting to the database, querying the first 
set of nodes (having null as the parent id), and creating 
TreeNode objects with the PopulateNodes routine, which 
follows next.

private void PopulateRootLevel()
{

    DataTable dt = BAL_Category.GetParentCategory();
// Get Parent CategoryList From Database 
    PopulateNodes(dt, tvCategoryList.Nodes);
}

Next, we want to create the routine to populate the

child nodes of a given node. This happens with the

PopulateSubLevel method.

private void PopulateSubLevel(int parentid, TreeNode parentNode)

{

    // Get CategoryList by ParentID From Database 

    DataTable dt = BAL_Category.GetChildCategory(parentid);

    PopulateNodes(dt, parentNode.ChildNodes);

}

Here, the idea is the same as with the root level, but with

the distinction that only child nodes of the given node are

queried and populated with the PopulateNodes method

(described earlier).
The trick to triggering the populating of the child nodes

is as follows.

protected void tvCategoryList_TreeNodePopulate
        (object sender, TreeNodeEventArgs e)

{

    PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);

}

TreeNodePopulate is raised for a TreeNode which is expanded

by the user for the first time. Due to

PopulateNodesFromClient (TreeView) and PopulateOnDemand
(TreeNode) settings, this happens with the client-side callback

mechanism which is handled by the ASP.NET Page framework.

This means that populating does not
involve a postback. And, due to better cross-browser support in

ASP.NET 2.0, this also works for other browsers such as Firefox.

Note that clicking on the node does
cause a postback because I haven’t modified the select action

of the populated tree nodes from the defaults.

private void PopulateNodes(DataTable dt, 
                               TreeNodeCollection nodes)

{

    foreach (DataRow dr in dt.Rows)

    {

        TreeNode tn = new TreeNode();

        tn.Text = dr["Category"].ToString();

        tn.Value = dr["CategoryID"].ToString();

        int NoofChild = 
        Convert.ToInt32(dr["childnodecount"].ToString());

        if (NoofChild != 0 )

        {

            tn.PopulateOnDemand = true;

            tn.SelectAction = TreeNodeSelectAction.None;

        }

        else

        {

            tn.PopulateOnDemand = false;

      if (dr["TotalDoc"].ToString().Equals("0") == false)

            {

          tn.NavigateUrl = 
        "~/CategoryWiseProductList.aspx?ID=" 
            + dr["CategoryID"].ToString();

           tn.Text = tn.Text + 
            " (" + dr["TotalProduct"].ToString() + ")";

            }

            else

            {

          tn.NavigateUrl = 
 "javascript:alert('Product is not Available Under this Category.')";

            }

        }

        nodes.Add(tn);

    }

}

DataRow[] results = null;
DataTable above24 = null;
DataTable dsStates = //state information
DataTable dsCity = //city information

ddlRegion.Items.Clear();
ddlRegion.Items.Insert(0, new OptionListItem(“Select Region…”, “-1”));

int cntr = 1;

for (int i = 0; i < dsStates.Rows.Count; i++)
{

ddlRegion.Items.Insert(cntr, new OptionGroupItem(dsStates.Rows[i][“State”].ToString()));
ddlRegion.Items[cntr].Attributes.Add(“style”, “FONT-WEIGHT: bold;BACKGROUND-COLOR: #ccccff;COLOR: black;FONT-SIZE: 1.5em”);

cntr++;

results = null;

//copy the schema of source table
above24 = dsCity.Clone();

//get only the rows you want
if (dsStates != null)
{
results = dsCity.Select(“StateID=” + Convert.ToInt32(dsStates.Rows[i][“StateID”].ToString()));
}

//populate new destination table
foreach (DataRow dr in results)
above24.ImportRow(dr);

for (int j = 0; j < above24.Rows.Count; j++)
{
ddlRegion.Items.Insert(cntr, new OptionListItem(above24.Rows[j][“CityName”].ToString(), above24.Rows[j][“CityName”].ToString()));
cntr++;
}
}

It will look like that.

1

using System.Data;

using System.Data.SqlClient;

using System.Text;

using System.IO;

using iTextSharp.text;

using iTextSharp.text.pdf;

using iTextSharp.text.html;

using iTextSharp.text.html.simpleparser;

Function to get the results in datatable

private DataTable GetData(SqlCommand cmd)

{

DataTable dt = new DataTable();

String strConnString = System.Configuration.ConfigurationManager.

ConnectionStrings[“conString”].ConnectionString;

SqlConnection con = new SqlConnection(strConnString);

SqlDataAdapter sda = new SqlDataAdapter();

cmd.CommandType = CommandType.Text;

cmd.Connection = con;

try

{

con.Open();

sda.SelectCommand = cmd;

sda.Fill(dt);

return dt;

}

catch (Exception ex)

{

throw ex;

}

finally

{

con.Close();

sda.Dispose();

con.Dispose();

}

}

As you can see above I am passing the query to the GetData function and it returns the results as datatable back.

Export to Word

protected void ExportToWord(object sender, EventArgs e)

{

//Get the data from database into datatable

string strQuery = “select CustomerID, ContactName, City, PostalCode” +

” from customers”;

SqlCommand cmd = new SqlCommand(strQuery);

DataTable dt = GetData(cmd);

//Create a dummy GridView

GridView GridView1 = new GridView();

GridView1.AllowPaging = false;

GridView1.DataSource = dt;

GridView1.DataBind();

Response.Clear();

Response.Buffer = true;

Response.AddHeader(“content-disposition”,

“attachment;filename=DataTable.doc”);

Response.Charset = “”;

Response.ContentType = “application/vnd.ms-word “;

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

GridView1.RenderControl(hw);

Response.Output.Write(sw.ToString());

Response.Flush();

Response.End();

}

image

Export to Excel

Below is the code to export the datatable to Excel Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as Excel Workbook. Also you will notice I applied textmode style to all the rows so that it in rendered as text.

protected void ExportToExcel(object sender, EventArgs e)

{

//Get the data from database into datatable

string strQuery = “select CustomerID, ContactName, City, PostalCode” +

” from customers”;

SqlCommand cmd = new SqlCommand(strQuery);

DataTable dt = GetData(cmd);

//Create a dummy GridView

GridView GridView1 = new GridView();

GridView1.AllowPaging = false;

GridView1.DataSource = dt;

GridView1.DataBind();

Response.Clear();

Response.Buffer = true;

Response.AddHeader(“content-disposition”,

“attachment;filename=DataTable.xls”);

Response.Charset = “”;

Response.ContentType = “application/vnd.ms-excel”;

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

for (int i = 0; i < GridView1.Rows.Count; i++)

{

//Apply text style to each Row

GridView1.Rows[i].Attributes.Add(“class”, “textmode”);

}

GridView1.RenderControl(hw);

//style to format numbers to string

string style = @”<style> .textmode { mso-number-format:\@; } </style>”;

Response.Write(style);

Response.Output.Write(sw.ToString());

Response.Flush();

Response.End();

}

image1

Export to Portable Document Format (PDF)

Below is the code to export the datatable to PDF Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as PDF document using the iTextSharp Library which is a free open source library and can be downloaded from here.

protected void ExportToPDF(object sender, EventArgs e)

{

//Get the data from database into datatable

string strQuery = “select CustomerID, ContactName, City, PostalCode” +

” from customers”;

SqlCommand cmd = new SqlCommand(strQuery);

DataTable dt = GetData(cmd);

//Create a dummy GridView

GridView GridView1 = new GridView();

GridView1.AllowPaging = false;

GridView1.DataSource = dt;

GridView1.DataBind();

Response.ContentType = “application/pdf”;

Response.AddHeader(“content-disposition”,

“attachment;filename=DataTable.pdf”);

Response.Cache.SetCacheability(HttpCacheability.NoCache);

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

GridView1.RenderControl(hw);

StringReader sr = new StringReader(sw.ToString());

Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

pdfDoc.Open();

htmlparser.Parse(sr);

pdfDoc.Close();

Response.Write(pdfDoc);

Response.End();

}

image2

Export to Comma Separated Values (CSV)

Below is the code to export the datatable to CSV or Text Format. It first fills the datatable using the GetData function. To export dataset to CSV there is no need of dummy GridView. We just have to loop through the records and append the delimiting character comma.

protected void ExportToCSV(object sender, EventArgs e)

{

//Get the data from database into datatable

string strQuery = “select CustomerID, ContactName, City, PostalCode” +

” from customers”;

SqlCommand cmd = new SqlCommand(strQuery);

DataTable dt = GetData(cmd);

Response.Clear();

Response.Buffer = true;

Response.AddHeader(“content-disposition”,

“attachment;filename=DataTable.csv”);

Response.Charset = “”;

Response.ContentType = “application/text”;

StringBuilder sb = new StringBuilder();

for (int k = 0; k < dt.Columns.Count; k++)

{

//add separator

sb.Append(dt.Columns[k].ColumnName + ‘,’);

}

//append new line

sb.Append(“\r\n”);

for (int i = 0; i < dt.Rows.Count; i++)

{

for (int k = 0; k < dt.Columns.Count; k++)

{

//add separator

sb.Append(dt.Rows[i][k].ToString().Replace(“,”, “;”) + ‘,’);

}

//append new line

sb.Append(“\r\n”);

}

Response.Output.Write(sb.ToString());

Response.Flush();

Response.End();

}

image3

Calendar

November 2017
M T W T F S S
« Jan    
 12345
6789101112
13141516171819
20212223242526
27282930  

Stats Of Blog

  • 7,054 hits

Cluster Map