Monday, May 20, 2013

Repeater Control example in asp.net

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Repeator Control Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Enter Name: </td>
<td><asp:TextBox ID="txtName" runat="server"/></td>
</tr>
<tr>
<td>Enter Subject: </td>
<td><asp:TextBox ID="txtSubject" runat="server"/></td>
</tr>
<tr>
<td valign="top">Enter Comments:</td>
<td><asp:TextBox ID="txtComment" runat="server" Rows="5" Columns="20" TextMode="MultiLine"/></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
<div>
<asp:Repeater ID="RepDetails" runat="server">
<HeaderTemplate>
<table style=" border:1px solid #df5015; width:500px" cellpadding="0">
<tr style="background-color:#df5015; color:White">
<td colspan="2">
<b>Comments</b>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="background-color:#EBEFF0">
<td>
<table style="background-color:#EBEFF0;border-top:1px dotted #df5015; width:500px" >
<tr>
<td>
Subject:
<asp:Label ID="lblSubject" runat="server" Text='<%#Eval("Subject") %>' Font-Bold="true"/>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblComment" runat="server" Text='<%#Eval("Comment") %>'/>
</td>
</tr>
<tr>
<td>
<table style="background-color:#EBEFF0;border-top:1px dotted #df5015;border-bottom:1px solid #df5015; width:500px" >
<tr>
<td>Post By: <asp:Label ID="lblUser" runat="server" Font-Bold="true" Text='<%#Eval("UserName") %>'/></td>
<td>Created Date:<asp:Label ID="lblDate" runat="server" Font-Bold="true" Text='<%#Eval("PostedDate") %>'/></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2">&nbsp;</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
After completion of aspx page design add following namespaces in code behind

C# Code

using System;
using System.Data;
using System.Data.SqlClient;
After add namespace write the following code


private SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true");
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindRepeaterData();
}
}
// This button click event is used to insert comment details and bind data to repeater control
protected void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into Repeater_Table (UserName,Subject,Comment,PostedDate) values(@userName,@subject,@comment,@postedDate)", con);
cmd.Parameters.AddWithValue("@userName", txtName.Text);
cmd.Parameters.AddWithValue("@subject", txtSubject.Text);
cmd.Parameters.AddWithValue("@comment", txtComment.Text);
cmd.Parameters.AddWithValue("@postedDate", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
txtName.Text = string.Empty;
txtSubject.Text = string.Empty;
txtComment.Text = string.Empty;
BindRepeaterData();
}
//Bind Data to Repeater Control
protected void BindRepeaterData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Repeater_Table Order By PostedDate desc", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
RepDetails.DataSource = ds;
RepDetails.DataBind();
con.Close();
}
VB.NET Code

Imports System.Data
Imports System.Data.SqlClient

Partial Public Class Default2
Inherits System.Web.UI.Page
Private con As New SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindRepeaterData()
End If
End Sub
' This button click event is used to insert comment details and bind data to repeater control
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
con.Open()
Dim cmd As New SqlCommand("insert into Repeater_Table (UserName,Subject,Comment,PostedDate) values(@userName,@subject,@comment,@postedDate)", con)
cmd.Parameters.AddWithValue("@userName", txtName.Text)
cmd.Parameters.AddWithValue("@subject", txtSubject.Text)
cmd.Parameters.AddWithValue("@comment", txtComment.Text)
cmd.Parameters.AddWithValue("@postedDate", DateTime.Now)
cmd.ExecuteNonQuery()
con.Close()
txtName.Text = String.Empty
txtSubject.Text = String.Empty
txtComment.Text = String.Empty
BindRepeaterData()
End Sub
'Bind Data to Repeater Control
Protected Sub BindRepeaterData()
con.Open()
Dim cmd As New SqlCommand("select * from Repeater_Table Order By PostedDate desc", con)
Dim ds As New DataSet()
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
RepDetails.Visible = True
RepDetails.DataSource = ds
RepDetails.DataBind()
Else
RepDetails.Visible = False
End If
con.Close()
End Sub
End Class

Wednesday, May 8, 2013

HTML Frames EXAMPLES :



Different framesets.

top
bottom


<frameset rows="16%,84%">
<frame src="top.htm" name="top">
<frame src="bottom.htm" name="bottom">
</frameset>






tl
tr
 
bottom


<frameset rows="16%,84%">
<frameset cols="50%,50%">
<frame src="tl.htm" name="tl">
<frame src="tr.htm" name="tr">
</frameset>
<frame src="bottom.htm" name="bottom">
</frameset>






top

left

right


<frameset rows="16%,84%">
<frame src="top.htm" name="top">
<frameset cols="50%,50%">
<frame src="left.htm" name="left">
<frame src="right.htm" name="right">
</frameset>
</frameset>






toplefttopright

botleft

botright



<frameset rows="50%,50%" cols="50%,50%">
<frame src="topleft.htm" name="topleft">
<frame src="topright.htm" name="topright">
<frame src="botleft.htm" name="botleft">
<frame src="botright.htm" name="botright">
</frameset>






toplefttopright

botleft
brtlbrtr
botrbot


<frameset rows="50%,50%" cols="50%,50%">
<frame src="topleft.htm" name="topleft">
<frame src="topright.htm" name="topright">
<frame src="botleft.htm" name="botleft">
<frameset rows="50%,50%">
<frameset cols="50%,50%">
<frame src="brtl.htm" name="brtl">
<frame src="brtr.htm" name="brtr">
</frameset>
<frame src="botrbot.htm" name="botrbot">
</frameset>
</frameset>






toplefttopright

botleft

botright


<frameset rows="240,240" cols="320,320">
<frame src="topleft.htm" name="topleft">
<frame src="topright.htm" name="topright">
<frame src="botleft.htm" name="botleft">
<frame src="botright.htm" name="botright">
</frameset>






toplefttopright

botleft

botright


<frameset rows="50%,*" cols="320,*">
<frame src="topleft.htm" name="topleft">
<frame src="topright.htm" name="topright">
<frame src="botleft.htm" name="botleft">
<frame src="botright.htm" name="botright">
</frameset>

Wednesday, May 1, 2013

How the Grid View data can be converted to HTML Table.

Introduction


In this article we are going to see how to convert the grid view data to HTML table. In many web applications the users may tend to an requirement of changing the grid view data to html table.

Objective


Grid View Control is commonly used in most of the web applications in order to perform many operations like edit,view,update etc. The users may come in some requirement to change the content of a grid view data into HTML table.


Using the code


Two tables tbl_PersonalDetails and tbl_ContactDetails are used in this article for displaying the content on grid view based on users selection.

Screen 1



Screen 2



The below code is an page design which consists of Check box list controls with Personal Details and Contact Details as an users option
.aspx Page Design

<table align="center">
    <tr>
    <td align="center"><b>
    Grid View to Html Conversion
    </b></td>
    </tr>
    <tr>
    <td>
    <asp:CheckBoxList ID="chkContactDetails" runat="server" 
        RepeatDirection="Horizontal" AutoPostBack="True" 
        onselectedindexchanged="chkContactDetails_SelectedIndexChanged">
    <asp:ListItem>Contact Details</asp:ListItem>
    <asp:ListItem>Personal Details</asp:ListItem>
    </asp:CheckBoxList>
    </td>
    </tr>
    </table>
The below code is an page design which consists of two grid view controls which will display the  Personal Details and Contact Details as an users according to users selection.
.aspx Page Design

<table align="center">
<tr>
<td>
<asp:GridView ID="grdCntDetails" runat="server" AutoGenerateColumns="False" 
        Width="400px" BackColor="#FFAA2B">
<Columns>
<asp:BoundField HeaderStyle-HorizontalAlign="Left" HeaderText="Name" 
        DataField="Name" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
    </asp:BoundField>
<asp:BoundField HeaderStyle-HorizontalAlign="Left" HeaderText="Mobile" 
        DataField="Mobile" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
    </asp:BoundField>
</Columns>
    <EditRowStyle BackColor="#FFE8C4" />
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grdPersDetails" runat="server" AutoGenerateColumns="False" 
        Width="400px" BackColor="#FFAA2B">
<Columns>
<asp:BoundField HeaderStyle-HorizontalAlign="Left" HeaderText="Name" 
        DataField="Name" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
    </asp:BoundField>
<asp:BoundField HeaderStyle-HorizontalAlign="Left" HeaderText="Email" 
        DataField="Email" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
    </asp:BoundField>
</Columns>
    <EditRowStyle BackColor="#FFE8C4" />
</asp:GridView>
</td>
</tr>
<tr>
<td align="center">
<asp:Button ID="btnConvert" runat="server" Text="Grid to Html" 
        onclick="btnConvert_Click" />
</td>
</tr>
</table>
The designing of the page is done here the rest of the code will consist of .cs files as an users option
Code Behind .cs

Below are the list of namespaces required to generate Grid view content to an HTML

using System;
using System.Collections;
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;
using System.Text;
using System.IO;
Db Connection-Connection string

The below line determines the connection string to database using MS-SQL Server 2005
 string Conn = ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
Global Variables

Some global variables are declared to maintain the data under those variables globally
 DataSet ds = new DataSet();
 string Body;
Check Box List Selected Changed Event

The below event is looping through the n number of items and and displaying the specific details of the users according to calling it's associated function. In the example 2 items (Contact Details,Personal Details) are used.
 protected void chkContactDetails_SelectedIndexChanged(object sender, EventArgs e)
    {
        for (int i = 0; i < chkContactDetails.Items.Count; i++)
        {
            if (chkContactDetails.Items[i].Selected == true)
            {
                if (chkContactDetails.Items[i].Text == "Contact Details")
                {
                    CntDetailsToHtml();
                }
                else if (chkContactDetails.Items[i].Text == "Personal Details")
                {
                    PersDetailsToHtml();
                }
            }
            else if (chkContactDetails.Items[i].Selected == false)
            {
                if (chkContactDetails.Items[i].Text == "Contact Details")
                {
                    grdCntDetails.Visible = false;
                }
                else if (chkContactDetails.Items[i].Text == "Personal Details")
                {
                    grdPersDetails.Visible = false;
                }
            }
        }
    }
User Defined Methods

Method explained below binds the contact details of the user to contact grid view and for personal details.
 protected DataSet CntDetailsToHtml()
    {
        try
        {
            SqlConnection cnn = new SqlConnection(Conn);
            SqlCommand cmd = new SqlCommand("select * from tbl_ConactDetails", cnn);
            SqlDataAdapter ada = new SqlDataAdapter(cmd);
            ada.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                grdCntDetails.Visible = true;
                grdCntDetails.DataSource = ds;
                grdCntDetails.DataBind();
            }
            else
            {
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        return ds;
    }


 protected DataSet PersDetailsToHtml()
    {
        try
        {
            SqlConnection cnn = new SqlConnection(Conn);
            SqlCommand cmd = new SqlCommand("select * from tbl_PersonalDetails", cnn);
            SqlDataAdapter ada = new SqlDataAdapter(cmd);
            if (ds != null)
            {
                ds = new DataSet();
            }
            ada.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                grdPersDetails.Visible = true;
                grdPersDetails.DataSource = ds;
                grdPersDetails.DataBind();
            }
            else
            {
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        return ds;
    }
On Button Click Event

The button click event will just convert the content Grid View data in to an HTML table by calling it's associated method to convert in to HTML table


  protected void btnConvert_Click(object sender, EventArgs e)
    {
        if (chkContactDetails.SelectedIndex <= -1)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Please select any of the contact details');", true);
        }
        else
        {
            string B = fn_AttachGridView();
            Response.Write(B.ToString());
        }

    }
On Button Click Event

The button click event will just convert the content Grid View data in to an HTML table by calling it's associated method to convert in to HTML table. It first checks for any of the contact Details has been selected to convert.


  protected void btnConvert_Click(object sender, EventArgs e)
    {
        if (chkContactDetails.SelectedIndex <= -1)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Please select any of the contact details');", true);
        }
        else
        {
            string B = fn_AttachGridView();
            Response.Write(B.ToString());
        }

    }
User Defined Method

The button click event uses an fn_AttachGridView() an user defined function which in then calls the other function (ContatDtlsToHtml , PersonalDtlsToHtml)to convert it to HTML table.


  protected string ContatDtlsToHtml(GridView grdC)
    {
        ds = CntDetailsToHtml();
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        if (ds.Tables[0].Rows.Count > 0)
        {
            sb.AppendLine("<html><body><center><table width='50%' cellspacing='0' border='1'");
            sb.AppendLine("<tr>");
            sb.AppendLine("<td colspan='4' width='50%' align='center' style='background-color: #FFAA2B;'>");
            sb.AppendLine("<b>");
            sb.AppendLine("Contact Details");
            sb.AppendLine("</b>");
            sb.AppendLine("</td>");
            sb.AppendLine("</tr>");
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                sb.AppendLine("<tr style='background-color: #FFE8C4'>");
                sb.AppendLine("<td>");
                sb.AppendLine("<b>");
                sb.AppendLine("Name");
                sb.AppendLine("</b>");
                sb.AppendLine("</td>");
                sb.AppendLine("<td>");
                sb.AppendLine(ds.Tables[0].Rows[i]["Name"].ToString().ToUpper());
                sb.AppendLine("</td>");
                sb.AppendLine("<td>");
                sb.AppendLine("<b>");
                sb.AppendLine("Mobile");
                sb.AppendLine("</b>");
                sb.AppendLine("</td>");
                sb.AppendLine("<td>");
                sb.AppendLine(ds.Tables[0].Rows[i]["Mobile"].ToString().ToUpper());
                sb.AppendLine("</td>");
                sb.AppendLine("</tr>");
            }
            sb.AppendLine("</table></center></body></html>");
        }
        return sb.ToString();
    }
protected string PersonalDtlsToHtml(GridView grdP)
    {
        ds = null;
        ds = new DataSet();
        ds = PersDetailsToHtml();
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        if (ds.Tables[0].Rows.Count > 0)
        {
            sb.AppendLine("<html><body><center><table width='50%' cellspacing='0' border='1'");
            sb.AppendLine("<tr>");
            sb.AppendLine("<td colspan='4' width='50%' align='center' style='background-color: #FFAA2B;'>");
            sb.AppendLine("<b>");
            sb.AppendLine("Personal Details");
            sb.AppendLine("</b>");
            sb.AppendLine("</td>");
            sb.AppendLine("</tr>");
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                sb.AppendLine("<tr style='background-color: #FFE8C4'>");
                sb.AppendLine("<td>");
                sb.AppendLine("<b>");
                sb.AppendLine("Name");
                sb.AppendLine("</b>");
                sb.AppendLine("</td> ");
                sb.AppendLine("<td>");
                sb.AppendLine(ds.Tables[0].Rows[i]["Name"].ToString().ToUpper());
                sb.AppendLine("</td>");
                sb.AppendLine("<td>");
                sb.AppendLine("<b>");
                sb.AppendLine("Email");
                sb.AppendLine("</b>");
                sb.AppendLine("</td> ");
                sb.AppendLine("<td>");
                sb.AppendLine(ds.Tables[0].Rows[i]["Email"].ToString());
                sb.AppendLine("</td>");
                sb.AppendLine("</tr>");
            }
            sb.AppendLine("</table></center></body></html>");
        }
        return sb.ToString();
    }
Screen 1

Screen 2


Conclusion

The above article can be used in any of the web application where there is a need for converting grid view to HTML table.