Wednesday, December 24, 2008

TextBox with numeric input only : textbox, only, numeric, input

function ISonlynumber(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<asp:TextBox ID="txtmobileNO" Runat="server" Width="150" MaxLength="64" onkeypress="javascript:return ISonlynumber(event);"></asp:TextBox>

Friday, December 19, 2008

change theme of page dynamically

protected void Page_Load(object sender, EventArgs e)
{    Page.Header.Controls.Add( gettheme());

}

protected HtmlLink gettheme()
{
HtmlLink lk = new HtmlLink();
// <link type="text/css" href=StyleSheet.css rel=Stylesheet />
lk.Attributes.Add("type", "text/css");
lk.Attributes.Add("href", "StyleSheet1.css");
lk.Attributes.Add("rel", "Stylesheet");
return lk;
}

Encription of user sensitive data

using System;
using System.Collections.Generic;
using System.Text;

/// <summary>
/// Summary description for Base64
/// </summary>
public sealed class Base64
{

public static string Encode(string data)
{
try
{
byte[] encData_byte = new byte[data.Length];
encData_byte = Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch(Exception e)
{
throw new Exception("Error in base64Encode " + e.Message);
}
}

public static string Decode(string data)
{
try
{
UTF8Encoding encoder = new UTF8Encoding();
Decoder utf8Decode = encoder.GetDecoder();

byte[] todecode_byte = Convert.FromBase64String(data);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
catch(Exception e)
{
throw new Exception("Error in base64Decode " + e.Message);
}
}
}

Write Meta tag in aspx page dynamically

HtmlMeta mt = new HtmlMeta();
mt.Attributes.Add("keyword", "hello is world");
Page.Header.Controls.Add(mt);
HtmlMeta mt1 = new HtmlMeta();
mt1.Attributes.Add("name", "suresh");
mt1.Attributes.Add("keyowrd", "hello rupak how r u");
mt1.Attributes.Add("discription", "yellowpages india,web hosting");
Page.Header.Controls.Add(mt1);

Thursday, November 20, 2008

Get User Control Value inside .ASPX page

<%@ Control Language="C#" AutoEventWireup="true"

CodeFile="header.ascx.cs" Inherits="UserControl_header" %>




on aspx pages-----------------

incode berhind pages-----------
protected void Page_Load(object sender, EventArgs e)
{
UserControl huser = header1 as UserControl;

searchlog(ref huser, "text for search");
}

void searchlog(ref UserControl hd, string text)
{
Label lb = (Label)hd.FindControl("lbltext");
TextBox txtbox = (TextBox)hd.FindControl("searchtext");
//here i assign text to usercontrol label
lb.Text = text;

//here i write user control text box value on page
Response.Write("User Control Textbox value::" +

txtbox.Text);

}

search record from table at given date

you pass date as varchar type and mm/dd/yyyy format

select * from emp where (createddate>'11/15/2008' and

createddate<DATEADD(day,1, '11/15/2008'))

remove any new line charactor from value of column

update emp set name=replace(name,char(10),'') where

charindex(char(10),name)>0

remove any space from any value of column

update emp set name=replace(name,' ','') where charindex('

',name)>0

checking space or any charactor in value in any column

select name from emp where charindex(' ',name)>0

Friday, July 11, 2008

Create Dinamic Image for Security signup

<%@ WebHandler Language="C#" Class="Image" %>

using System;

using System.Web;

using System.Drawing;

using System.Drawing.Imaging;


using System.Text;

using System.Web.SessionState;

class Image : IHttpHandler, IRequiresSessionState
{public void ProcessRequest(HttpContext context)

{context.Response.ContentType = "image/gif";

Bitmap b = new Bitmap(200, 60);

Graphics g = Graphics.FromImage(b);

g.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);

Font font = new Font(FontFamily.GenericSansSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);

Random r = new Random();

string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";

string letter;

StringBuilder Lt = new StringBuilder();

for (int x = 0; x < 5; x++)

{letter = letters.Substring(r.Next(0, letters.Length - 1), 1);

Lt.Append(letter);

g.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));

}

Pen linepen = new Pen(new SolidBrush(Color.Black), 2);

for (int x = 0; x < 6; x++)

g.DrawLine(linepen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));

b.Save(context.Response.OutputStream, ImageFormat.Gif);

context.Session["image"] =Lt;

context.Response.End();

}

public bool IsReusable

{get{return true;}

}

}

Recursively find control from previous page

hi

i study more time asp.net starter kit and i found best code for finding previous page server control.

But from prevoius page you must use postbackurl on button or use server.transfer("go.aspx");

The code is follow........

public sealed class Util{

private Util(){}

public static Control FindControlRecursively(string controlID, ControlCollection controls){

if (controlID == null || controls == null)

return null;

foreach (Control c in controls){
if (c.ID == controlID)
return c;
if (c.HasControls()){
Control inner = FindControlRecursively(controlID, c.Controls);
if (inner != null)
return inner;}
}

return null;
}

Tuesday, July 8, 2008

Insert, Update, delete, paging in formview


        
        

ID:
Name:
City:
-

Name:
City:
-

Sample Database
ID:
Name:
City:
- -
Page :<%=fv.PageIndex+1%> « Prev Next »
public partial class formvieweditupdate : System.Web.UI.Page
{
SqlConnection dbConn = null;
SqlDataAdapter da = null;
DataTable dTable = null;
String strConnection = null;
String strSQL = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bindData();
}
}
private void bindData()
{
try
{
strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
dbConn = new SqlConnection(strConnection);
dbConn.Open();
strSQL = "SELECT companyid, companyname,companycity  from companydetail order by companyname";
da = new SqlDataAdapter(strSQL, dbConn);
dTable = new DataTable();
da.Fill(dTable);
fv.DataSource = dTable;
fv.DataBind();
}
finally
{
if (dbConn != null)
{
dbConn.Close();
}
}
}

protected void Update(object sender, FormViewUpdateEventArgs e)
{
try
{
int cid = Convert.ToInt32((fv.Row.FindControl("theIDLabel1") as Label).Text);
string cname = (fv.Row.FindControl("theNameTextBox") as TextBox).Text;
string ccity = (fv.Row.FindControl("theCityTextBox") as TextBox).Text;
strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
dbConn = new SqlConnection(strConnection);
dbConn.Open();
SqlCommand   da = new SqlCommand( "Update companydetail set companyname=@comp,companycity=@comcity where companyid=@cid", dbConn);
da.Parameters.Add("@cid", SqlDbType.Int).Value = cid;
da.Parameters.Add("@comp", SqlDbType.VarChar).Value = cname;
da.Parameters.Add("@comcity", SqlDbType.VarChar).Value = ccity;
da.ExecuteNonQuery();
fv.ChangeMode(FormViewMode.ReadOnly);
}

finally
{
if (dbConn != null)
{
dbConn.Close();
bindData();
}
}

}
protected void Insert(object sender, FormViewInsertEventArgs e)
{
try
{

string cname = (fv.Row.FindControl("theNameTextBox") as TextBox).Text;
string ccity = (fv.Row.FindControl("theCityTextBox") as TextBox).Text;
strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
dbConn = new SqlConnection(strConnection);
dbConn.Open();
SqlCommand da = new SqlCommand("insert into companydetail values(@comp,@add,@comcity)", dbConn);
da.Parameters.Add("@add", SqlDbType.VarChar).Value ="";
da.Parameters.Add("@comp", SqlDbType.VarChar).Value = cname;
da.Parameters.Add("@comcity", SqlDbType.VarChar).Value = ccity;
da.ExecuteNonQuery();
fv.ChangeMode(FormViewMode.ReadOnly);
}

finally
{

if (dbConn != null)
{
dbConn.Close();
bindData();
}
}

}
protected void Delete(object sender, FormViewDeleteEventArgs e)
{
try
{
int cid = Convert.ToInt32((fv.Row.FindControl("theIDLabel") as Label).Text);
strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
dbConn = new SqlConnection(strConnection);
dbConn.Open();
SqlCommand da = new SqlCommand("delete from companydetail where companyid=@cid", dbConn);
da.Parameters.Add("@cid", SqlDbType.Int).Value = cid;
da.ExecuteNonQuery();
fv.ChangeMode(FormViewMode.ReadOnly);
}

finally
{

if (dbConn != null)
{
dbConn.Close();
bindData();
}
}

}
protected void ChangMode(object sender, FormViewModeEventArgs e)
{
fv.ChangeMode(e.NewMode);
if (e.NewMode.ToString() != "Edit" && e.NewMode.ToString()!="Insert")
{
bindData();
}

}

protected void pagechanged(object sender, FormViewPageEventArgs e)
{
fv.PageIndex = e.NewPageIndex;
bindData();
}
}

Monday, July 7, 2008

Paging in Gridview using PagerTemplate










« First

< Prev
[Records <%= gv.PageIndex * gv.PageSize%>-<%= gv.PageIndex * gv.PageSize + gv.PageSize - 1%>]

Next >

Last »


fix header in repeater and datalist


LocalityidLocalityname
<%#Eval("localityid") %><%#Eval("localityname") %>
code behind code
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataAdapter cmd = new SqlDataAdapter("select top 100 * from locality", con);
cmd.SelectCommand.CommandType = CommandType.Text;
DataSet ds = new DataSet();
cmd.Fill(ds);
dl.DataSource = ds;
dl.DataBind();

}

Friday, July 4, 2008

register hidden field and its value in code file

ClientScript.RegisterHiddenField(

"hd",pageState.ToString());

where hd is hidden field name and pagestate in numeric variable which contian value

Edit,Update,delete in gridview using Xml file





TemplateField HeaderText="empId" >




TextBox ID="txtid" runat =server Text='<%#Eval("empid") %>'>
EditItemTemplate>
TemplateField>
TemplateField HeaderText="empname" >




TextBox ID="txtname" runat =server Text='<%#Eval("empname") %>'>
EditItemTemplate>
TemplateField>
empcity" >




TextBox ID="txtcity" runat =server Text='<%#Eval("empcity") %>'>


empsalary" >




TextBox ID="txtsalary" runat =server Text='<%#Eval("empsalary") %>'>


CommandField ShowEditButton="True" />
CommandField ShowDeleteButton="True" />















codefile

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
void binddata()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("empdata.xml"));
if (ds != null && ds.HasChanges())
{
gv.DataSource = ds;
gv.DataBind();
}
else
{
gv.DataBind();
}
}
protected void Editdata(object s, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex;
binddata();
}
protected void Deletedata(object s, GridViewDeleteEventArgs e)
{
binddata();
DataSet ds= gv.DataSource as DataSet;
ds.Tables[0].Rows[gv.Rows[e.RowIndex].DataItemIndex].Delete();
ds.WriteXml(Server.MapPath("empdata.xml"));
binddata ();
}
protected void Canceldata(object s, GridViewCancelEditEventArgs e)
{
gv.EditIndex = -1;
binddata();
}
protected void Updatedata(object s, GridViewUpdateEventArgs e)
{

int i =gv.Rows[e.RowIndex].DataItemIndex;
string id=(gv.Rows[e.RowIndex].FindControl("txtid") as TextBox).Text;
string name=(gv.Rows[e.RowIndex].FindControl("txtname") as TextBox).Text;
string city=(gv.Rows[e.RowIndex].FindControl("txtcity") as TextBox).Text;
string salary=(gv.Rows[e.RowIndex].FindControl("txtsalary") as TextBox).Text;
gv.EditIndex = -1;
binddata();
DataSet ds =(DataSet) gv.DataSource;
ds.Tables[0].Rows[i]["empid"] = id;
ds.Tables[0].Rows[i]["empname"] = name;
ds.Tables[0].Rows[i]["empcity"] = city;
ds.Tables[0].Rows[i]["empsalary"] = salary;
ds.WriteXml(Server.MapPath("empdata.xml"));
binddata();
}
protected void pageddata(object s, GridViewPageEventArgs e)
{
gv.PageIndex = e.NewPageIndex;
binddata();
}

protected void insert(object sender, EventArgs e)
{
binddata();
DataSet ds = gv.DataSource as DataSet;
DataRow dr = ds.Tables[0].NewRow();
dr[0] = empId.Text;
dr[1] = empName.Text;
dr[2] = empcity.Text;
dr[3] = empsalary.Text;
ds.Tables[0].Rows.Add(dr);
ds.AcceptChanges();
ds.WriteXml(Server.MapPath("empdata.xml"));
binddata();
empId.Text = string.Empty;
empcity.Text = string.Empty;
empName.Text = string.Empty;
empsalary.Text = string.Empty;
}
xml file









Thursday, July 3, 2008

Set dropdownlist value from querystring in javascript



    
delhi mumbai channai kolkota

Tuesday, July 1, 2008

Display Rss data througth Javascript

try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}function displayRSS(url)
{xmlhttp=GetXmlHttpObject();
if(xmlHttp==null)
{return;}
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange=getRssFormat;
xmlHttp.send(null);
}
function getRssFormat()

{if(xmlHttp.readyState==4)
{if(xmlHttp.status != 200)
{
document.getElementById("rss").innerHTML= "Sorry....The Server did not return any results (Result code: 200). Please try again Sorry for the Inconvenience";
}
else{
var items_count=3;
link=new Array(), title=new  Array(), pubDate=new Array()
for(var  i=0; i0)?title[i].firstChild.nodeValue:"Untitled";
link_w=(link.length>0)?link[i].firstChild.nodeValue:"";
pubDate_w=pubDate[i];
litag = document.createElement("li");
linktag =document.createElement("a");
linktag.setAttribute("href",link_w);
linktag.appendChild(document.createTextNode(title_w + " (" + pubDate_w + ")"));
litag.appendChild(linktag);
ul.appendChild(litag);
}}}
if(xmlHttp.readyState==1 || xmlHttp.readyState==2 || xmlHttp.readyState==3)
{document.getElementById("rss").innerHTML='Please Wait....';
}}

Saturday, June 28, 2008

creating Xml data in asp.net

protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/Xml"; 
        int vid = Convert.ToInt32(Request.QueryString["vid"]);
        SqlConnection con = new SqlConnection( ConfigurationManager.
        ConnectionStrings["connect"].ConnectionString);
        SqlDataAdapter cmd = new SqlDataAdapter("select vedioname,vediourl,vediodesc from vedio  where vedioid=@vid", con);
        cmd.SelectCommand.Parameters.Add("@vid", SqlDbType.Int).Value =vid;
        cmd.SelectCommand.CommandType = CommandType.Text;
        DataSet ds = new DataSet();
        cmd.Fill(ds, "root");
        String s = ds.GetXml();
       
        Response.Write(s);
        Response.End();

    }

Get web control value through javascript

<asp:TextBox id="txtname" runat=server ></asp:TextBox>
<script>

function getvalue()
{
  var val=document.getElementById('<%=txtname.ClientID%>').value;
  alert(val);
}

gridview with SqlDatasource

<asp:GridView ID="gv" Runat="Server"
AutoGenerateColumns="true"
BorderColor="#000080"
BorderWidth="2px"
HorizontalAlign="Center"
Width="90%" >
</asp:GridView>

codebehind file/////////
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlDataSource Source= new SqlDataSource();
Source.ConnectionString = ConfigurationManager.
ConnectionStrings["ConnectionString"].ConnectionString;
Source.DataSourceMode = SqlDataSourceMode.DataReader;
Source.ProviderName = "System.Data.SqlClient";
Source.SelectCommand = "SELECT companyname, companyaddress, companycity FROM companydetail ORDER BY companyname";
gv.DataSource = Source;
gv.DataBind();
}
}

Friday, June 27, 2008

using gridview calculate total in footer template

[sourcecode langauge="html"]

<asp:GridView ID="gv" Runat="Server"
AllowPaging="false"
AllowSorting="false"
AutoGenerateColumns="false"
BorderColor="#000080"
BorderStyle="Solid"
BorderWidth="2px"
Caption=""
HorizontalAlign="Center"
ShowFooter="true"
Width="90%"
OnRowDataBound="gv_RowDataBound" >
<HeaderStyle HorizontalAlign="Center" />
<RowStyle  />
<AlternatingRowStyle  />
<FooterStyle  HorizontalAlign="Right"/>
<Columns>
<asp:TemplateField HeaderText="Name" FooterText="Total:">
<ItemTemplate>
<%# Eval("name") %>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Salary"
ItemStyle-HorizontalAlign="Right">
<ItemTemplate>
<asp:Literal id="lblsalary" runat="server"
text='<%# Eval("Salry") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Literal id="lbltotSalary" runat="server" />
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Tax"
ItemStyle-HorizontalAlign="Right">
<ItemTemplate>
<asp:Literal id="lblTax" runat="server"
text='<%# Eval("Tax") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Literal id="lblTotTax"
runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

[/sourcecode]

codebehind pages

[sourcecode langauge="csharp"]

private Decimal msalaryTotal;
private Decimal mTaxTotal;
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource dSource = null;

if (!Page.IsPostBack)
{
dSource = new SqlDataSource();
dSource.ConnectionString = ConfigurationManager.
ConnectionStrings["dbConnectionString"].ConnectionString;
dSource.DataSourceMode = SqlDataSourceMode.DataReader;
dSource.ProviderName = "System.Data.SqlDb";
dSource.SelectCommand = "SELECT Name,Salary,Tax" +
"FROM emp " +"ORDER BY name";
msalaryTotal = 0;
mTaxTotal = 0;
gv.DataSource=dSource;
gv.DataBind();
}
}
protected void gv_RowDataBound(Object sender,GridViewRowEventArgs e)
{
DbDataRecord rowData;
Decimal amt;
Literal salaryLabel;
Literal TaxLabel;
Literal totalLabel;
switch (e.Row.RowType)
{
case DataControlRowType.DataRow:
rowData = (DbDataRecord)(e.Row.DataItem);
amt = (Decimal)(rowData["Salry"]);
msalaryTotal += amt;
salaryLabel = (Literal)(e.Row.FindControl("lblSalary"));
salaryLabel.Text = amt.ToString("C2");
amt = (Decimal)(rowData["Tax"]);
mTaxTotal += amt;
TaxLabel = (Literal)(e.Row.FindControl("lblTax"));
TaxLabel.Text = amt.ToString("C2");
break;
case DataControlRowType.Footer:
totalLabel = (Literal)(e.Row.FindControl("lbltotsalary"));
totalLabel.Text =msalaryTotal.ToString("C2");
totalLabel = (Literal)(e.Row.FindControl("lblTotTax"));
totalLabel.Text = mTaxTotal.ToString("C2");
break;
default:
break;
}
}

[/sourcecode]

Inserting in Gridview

<asp:GridView ID="gv" runat="server"
AutoGenerateColumns="False"
HorizontalAlign="Center"
Width="90%"
ShowFooter="True"
OnRowCommand="gv_RowCommand" CellPadding="4" ForeColor="#333333"
GridLines="None">
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle HorizontalAlign="Center"  />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle  />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"  />
<Columns>
<asp:TemplateField HeaderText="companyname"
ItemStyle-HorizontalAlign="Center"
FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<%#Eval("companyname")%>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox id="txtcompanyname" runat="server"
Columns="3" />
</FooterTemplate>

<FooterStyle HorizontalAlign="Center"></FooterStyle>

<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>

<asp:TemplateField HeaderText="Address"
ItemStyle-HorizontalAlign="Left"
FooterStyle-HorizontalAlign="Left">
<ItemTemplate>
<%#Eval("Companyaddress")%>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox id="txtCompanyaddress" runat="server"
Columns="40" />
</FooterTemplate>

<FooterStyle HorizontalAlign="Left"></FooterStyle>

<ItemStyle HorizontalAlign="Left"></ItemStyle>
</asp:TemplateField>

<asp:TemplateField HeaderText="CompanyCity"
ItemStyle-HorizontalAlign="Center"
FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<%#Eval("CompanyCity")%>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox id="txtCompanyCity" runat="server"
Columns="40" />
</FooterTemplate>

<FooterStyle HorizontalAlign="Center"></FooterStyle>

<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>

<asp:TemplateField FooterStyle-HorizontalAlign="Center">
<FooterTemplate>
<asp:Button ID="btnInsert" runat="server"
Text="Insert"
CommandName="Insert" />
</FooterTemplate>

<FooterStyle HorizontalAlign="Center"></FooterStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>

coding pages

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bindData();
}

}

protected void gv_RowCommand(Object sender,GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{

String   comp = ((TextBox)(gv.FooterRow.FindControl("txtCompanyName"))).Text;
String  address = ((TextBox)(gv.FooterRow.FindControl("txtCompanyAddress"))).Text;
String city = ((TextBox)(gv.FooterRow.FindControl("txtCompanycity"))).Text;
SqlConnection dbConn =new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand dCmd = new SqlCommand("insert into companydetail(companyname,companyaddress,companycity)values(@comp,@address,@city)", dbConn);
dCmd.Connection.Open();
dCmd.Parameters.Add("@comp", SqlDbType.NVarChar).Value = comp;
dCmd.Parameters.Add("@address", SqlDbType.NVarChar).Value = address;
dCmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = city;
dCmd.ExecuteNonQuery();
bindData();
dbConn.Close();
}

 

}
private void bindData()
{
SqlConnection dbConn =new SqlConnection( ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT companyname,companyaddress,companycity  from companydetail order by companyname", dbConn);
DataTable dTable= new DataTable();
da.Fill(dTable);
gv.DataSource = dTable;
gv.DataBind();
dbConn.Close();

}

datagrid first prev next last paging

<asp:DataGrid ID="dg" Runat="server" BorderColor="#CC9966" BorderWidth="1px" AutoGenerateColumns="False"
Width="90%"
HorizontalAlign="Center"
AllowPaging="True"
PageSize="5"
PagerStyle-Visible="False" BackColor="White" BorderStyle="None"
CellPadding="4">
<HeaderStyle HorizontalAlign="Center" BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC"
/>
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<PagerStyle Visible="False" BackColor="#FFFFCC" ForeColor="#330099"
HorizontalAlign="Center"></PagerStyle>
<ItemStyle  />
<AlternatingItemStyle/>
<Columns>
<asp:BoundColumn HeaderText="regid"
DataField="regid" />
<asp:BoundColumn HeaderText="companyname"
DataField="companyname"
ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn HeaderText="address"
DataField="address"
ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
<br />
<table width="20%" border="0" align="center">
<tr>
<td align="center">
<input id="btnFirst" runat="server" type="button"
value="First"
onserverclick="btnFirst_ServerClick">
</td>
<td align="center">
<input id="btnPrev" runat="server" type="button"
value="Prev"
onserverclick="btnPrev_ServerClick">
</td>
<td align="center">
<input id="btnNext" runat="server" type="button"
value="Next"
onserverclick="btnNext_ServerClick">
</td>
<td align="center">
<input id="Last" runat="server" type="button"
value="Last"
onserverclick="btnLast_ServerClick">
</td>
</tr>
</table>

codebehind pages

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindData();
        }
    } 

    protected void btnFirst_ServerClick(Object sender,EventArgs e)
    { 
        if (dg.CurrentPageIndex > 0)
        {   dg.CurrentPageIndex = 0;
            bindData();
        }
    } 

    protected void btnPrev_ServerClick(Object sender,EventArgs e)
    {
        if (dg.CurrentPageIndex > 0)
        {   dg.CurrentPageIndex -= 1;
            bindData();
        }
    } 
     
    protected void btnNext_ServerClick(Object sender,EventArgs e)
    {if (dg.CurrentPageIndex < dg.PageCount - 1)
        {   dg.CurrentPageIndex += 1;
            bindData();
        }
    } 

    protected void btnLast_ServerClick(Object sender,EventArgs e)
    {
        if (dg.CurrentPageIndex < dg.PageCount - 1)
        {  dg.CurrentPageIndex = dg.PageCount - 1;
            bindData();
        }
    }
    private void bindData()
    {           
            SqlConnection dbConn  = new SqlConnection( ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            SqlDataAdapter da = new SqlDataAdapter("SELECT top 50 regid, companyname, address FROM registration ORDER BY companyname", dbConn);
            DataSet dSet = new DataSet();
             da.Fill(dSet);
             dg.DataSource = dSet;
             dg.DataBind();
    
    }

Edit,Update in datagrid

<div>
     <asp:DataGrid id="dg" runat="server" BorderColor="#3366CC" BorderWidth="1px"
AutoGenerateColumns="False" HorizontalAlign="Center" dth="63%"
 OnCancelCommand="dg_CancelCommand" OnEditCommand="dg_EditCommand"
 OnUpdateCommand="dg_UpdateCommand" DataKeyField="companyid"
 BackColor="White" BorderStyle="None" CellPadding="4" Height="170px">
 <HeaderStyle HorizontalAlign="Center" BackColor="#003399" Font-Bold="True"
 ForeColor="#CCCCFF"  /> <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
 <SelectedItemStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
         <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left"
 Mode="NumericPages" /><ItemStyle BackColor="White" ForeColor="#003399"  />
 <AlternatingItemStyle  /><Columns><asp:BoundColumn DataField="companyid"
 ItemStyle-HorizontalAlign="Center" HeaderText="Company Id" ReadOnly="True" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn><asp:TemplateColumn HeaderText="ComapnyName">
<ItemTemplate><%#Eval("CompanyName")%></ItemTemplate><EditItemTemplate>
<asp:TextBox id="txtcompanyname" runat="server" Columns="55"
 text='<%# Eval("CompanyName") %>' /></EditItemTemplate>
</asp:TemplateColumn>    
 <asp:templatecolumn headertext="Company Address"
 itemstyle-horizontalalign="Center"><itemtemplate>
  <%# Eval("companyAddress") %></itemtemplate>
<edititemtemplate>
<asp:TextBox id="txtcompanyAddress" runat="server" Columns="55"
text='<%# Eval("companyAddress") %>' />
</edititemtemplate><ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:templatecolumn>
<asp:EditCommandColumn ButtonType="LinkButton" EditText="Edit"
 CancelText="Cancel" UpdateText="Update" /></Columns></asp:DataGrid>

code behind file is that

protected void Page_Load(object sender, EventArgs e)
    {if (!Page.IsPostBack)
        {
            bindData();
        }
    }
  
    protected void dg_CancelCommand(Object source,DataGridCommandEventArgs e)
    {
        dg.EditItemIndex = -1;
        bindData();
    }
    protected void dg_EditCommand(Object source,DataGridCommandEventArgs e)
    {
        dg.EditItemIndex = e.Item.ItemIndex;
        bindData();
    } 
  
    protected void dg_UpdateCommand(Object source,DataGridCommandEventArgs e)
    {
        SqlConnection dbConn = null;
        SqlCommand dCmd = null;
        String comp = null;
         String strConnection = null;
        String strSQL = null;
        int rowsAffected;
        String address = null;

        try
        {   comp = ((TextBox)(e.Item.FindControl("txtComapnyName"))).Text;
            address = ((TextBox)(e.Item.FindControl("txtComapnyAddress"))).Text;
            strConnection = ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
            dbConn = new SqlConnection(strConnection);
            dbConn.Open();
            strSQL = "UPDATE companydetail SET companyname='" + comp + "'" +",companyaddress=" + address +
                     " WHERE companyID=" +dg.DataKeys[e.Item.ItemIndex].ToString();
            dCmd = new SqlCommand(strSQL, dbConn);
            rowsAffected = dCmd.ExecuteNonQuery();
            dg.EditItemIndex = -1;
            bindData();
        }

        finally
        {
            if (dbConn != null)
            {
                dbConn.Close();
            }
        }
    }

    private void bindData()
    {
        SqlConnection dbConn = null;
        SqlDataAdapter da = null;
        DataTable dTable = null;
        String strConnection = null;
        String strSQL = null;

        try
        { strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            dbConn = new SqlConnection(strConnection);
            dbConn.Open();
            strSQL = "SELECT companyid, companyname,companyaddress  from companydetail order by companyname";

            da = new SqlDataAdapter(strSQL, dbConn);
            dTable = new DataTable();
            da.Fill(dTable);
             dg.DataSource = dTable;
            dg.DataKeyField = "companyid";
            dg.DataBind();
        }

        finally
        {

            if (dbConn != null)
            {
                dbConn.Close();
            }
        }
    }

Thursday, June 26, 2008

paging and sorting in Datagrid

     

 


div><asp:DataGrid id="dg" runat="server" AutoGenerateColumns="False" width="90%"

 HorizontalAlign="Center" AllowSorting="True"AllowPaging="True"PageSize="5"

     

 


PagerStyle-Mode="NumericPages" PagerStyle-PageButtonCount="5"

     

 


PagerStyle-Position="Bottom" pagerStyle-HorizontalAlign="Center"

     

 


PagerStyle-NextPageText="Next" PagerStyle-PrevPageText="Prev"

     

 


PagerStyle-CssClass="pagerText" OnPageIndexChanged="data_PageIndexChanged"

OnSortCommand="data_SortCommand" CellPadding="4" ForeColor="#333333"

 GridLines="None" >

<HeaderStyle HorizontalAlign="Center" BackColor="#507CD1"

     

 


Font-Bold="True" ForeColor="White" />

     

 


<ItemStyle BackColor="#EFF3FB" />

<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<EditItemStyle BackColor="#2461BF" />

<SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

     

 


<PagerStyle NextPageText="Next" PageButtonCount="5" PrevPageText="Prev"

     

 


HorizontalAlign="Center" BackColor="#2461BF" ForeColor="White"></PagerStyle>

<AlternatingItemStyle /><Columns>

<asp:BoundColumn DataField="companyname" HeaderText="companyname"

     

 


SortExpression="companyname" />

     

 


<asp:BoundColumn DataField="companyaddress"

     

 


ItemStyle-HorizontalAlign="center" SortExpression="companyaddress">

     

 


<ItemStyle HorizontalAlign="Center"></ItemStyle></asp:BoundColumn>

<asp:BoundColumn DataField="companycity"ItemStyle-HorizontalAlign="Center"

     

 


SortExpression="companycity" >

     

 


<ItemStyle HorizontalAlign="Center"></ItemStyle></asp:BoundColumn>

     

 


</Columns></asp:DataGrid></div>

codebehind pages

 
private enum SortOrder


{soAscending = 0,


soDescending = 1

}




static readonly String SORTEXPRESSION = "SortExpression";



 
  

 


static readonly String SORTORDER = "SortOrder" 

 

 

private void Page_Load(object sender, System.EventArgs e)

{String  defaultSortExpression;

SortOrder defaultSortOrder; 

 

 

if (!Page.IsPostBack){
  

 






defaultSortExpression =



 
"companyname";  

 



SortOrder.soAscending;    

 


this.ViewState.Add(SORTEXPRESSION, defaultSortExpression);

this.ViewState.Add(SORTORDER, defaultSortOrder);bindData(defaultSortExpression,defaultSortOrder);

 
}}   
protected void data_SortCommand(Object source, DataGridSortCommandEventArgs e){

 

 


 String newSortExpression = null;

 

String currentSortExpression = null;SortOrder currentSortOrder;

currentSortExpression =(String)(this.ViewState[SORTEXPRESSION]);currentSortOrder =(  

 
SortOrder)(this.ViewState[SORTORDER]); 

newSortExpression = e.SortExpression; 

if (newSortExpression == currentSortExpression){

if (currentSortOrder == SortOrder.soAscending){

currentSortOrder =SortOrder.soDescending;}

else{currentSortOrder =SortOrder.soAscending;}

} else{currentSortExpression =newSortExpression;

currentSortOrder =SortOrder.soAscending;}

this.ViewState.Add(SORTEXPRESSION, currentSortExpression);

ViewState.Add(SORTORDER, currentSortOrder); 

bindData(currentSortExpression,currentSortOrder);}

protected void data_PageIndexChanged(Object source, DataGridPageChangedEventArgs

e){String currentSortExpression;

SortOrder currentSortOrder; dg.CurrentPageIndex = e.NewPageIndex;

currentSortExpression =( String)(this.ViewState[SORTEXPRESSION]);

currentSortOrder =(SortOrder)(this.ViewState[SORTORDER]);

bindData(currentSortExpression,currentSortOrder);

 
} 

 
private void bindData(String sortExpression, SortOrder sortOrder){


DataTable dTable = null; 

int index = 0;DataGridColumn col = null;

String colImage = null;

String strSortOrder = null;


SqlConnection dbConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);dbConn.Open(); 

if (sortOrder == SortOrder.soAscending){strSortOrder =" ASC";}

strSortOrder =" DESC";}

SqlDataAdapter da = new SqlDataAdapter("SELECT companyname,companyaddress,companycity FROM companydetail ORDER BY "

+ sortExpression + strSortOrder, dbConn);

new DataTable();da.Fill(dTable);

for (index = 0; index < dg.Columns.Count; index++)

{col = dg.Columns[index]; 

if (col.SortExpression == sortExpression){

if (sortOrder == SortOrder

.soAscending){colImage ="<img src='images/sort_ascending.gif' border='0'>";} else{colImage =" <img src='images/sort_descending.gif' border='0'>";} 
}


else{colImage ="";}

col.HeaderText = col.SortExpression + colImage;}

dg.DataSource = dTable;dg.DataBind();} 



Tuesday, June 24, 2008

page bookmark in javascript

var urlAddress =window.location.href;
 var pageName = document.title;
  function addToFavorites()
  {
  if (window.external)
  {
  window.external.AddFavorite(urlAddress,pageName)
  }
  else
  {
  alert("Sorry! Your browser doesn't support this function.");
  }
}

show hide layer on tab clicking

function showDiv(dvnm)
{
 document.getElementById(dvnm).style.display = 'block';
 document.getElementById(dvnm).style.visibility = 'visible';
}

function hideDiv(dvnm)
{
 document.getElementById(dvnm).style.display = 'none';
 document.getElementById(dvnm).style.visibility = 'hidden';
}
function showlayer(n)
{
 for(i=1;i<=2;i++)//number of layer u want to show
 {
  if(i==n)
  {
   showDiv('div'+ i);//dynamically call div id
   document.getElementById('tab'+i).style.backgroundColor="#666666";//dynamically show contant id
  }
  else
  {
   hideDiv('div'+ i); 
      document.getElementById('tab'+i).style.backgroundColor="gray";
  }
 }
}

show and hide content on next prev button

<table width="99%" cellpadding="3" cellspacing="1" bgcolor="#000000">
                  <tr>
                    <td height="20" class="photonamewhite"><div style="float: right; width: 100px; position: relative; height: 25px;" class=smallphotoname align="right"><a href="#" class="curhand" title="Previous" onclick="moveRight('div_hall',90)">«prev</a>   <a href="#" title="next" onclick="moveLeft('div_hall',90)">next»</a></div></td>
                  </tr>
                  <tr>
                    <td  bgcolor="#999999" >
                   
                    <DIV style="MARGIN-LEFT: 5px; OVERFLOW: hidden; background-color:#666666; WIDTH: 276px; POSITION: relative; HEIGHT: 184px">
                        <DIV id="div_hall" style="LEFT: 0px; WIDTH:<%=(photo.Items.Count%6)==0?(photo.Items.Count/6)*270:((photo.Items.Count/6)+1)*270%>px; POSITION: absolute; TOP: 0px">
                              
                               <asp:DataList ID=photo runat =server   ItemStyle-BackColor="#666666"  BackColor=#666666
                                 RepeatDirection=Horizontal RepeatLayout=Table   ItemStyle-Width=90 ItemStyle-Height=90 ItemStyle-CssClass=smallphotoname >
                                <ItemTemplate>
                                <a  onclick='getvedio(<%=Request.QueryString["vid"]%>,<%#Eval("vediosno")%>)' class=filterimage><img src='<%#"../../"+Eval("Urlimage") %>'  width="80" style="cursor:hand;border-color:DarkGray" height="80" border="2" ><br>
                                     </a></ItemTemplate>
                                     
                               </asp:DataList>
                               </DIV>
                               </DIV>
                             
                    </td>
                  </tr>
                
              </table>
//using method in javascript ///

function moveRight(divname,owidth)

 var crossobj=document.getElementById(divname) ;
 leftpos = parseInt(crossobj.style.left) + owidth ;
 
 if ( leftpos < 0 )
  crossobj.style.left = parseInt(crossobj.style.left) + owidth ;
 else
  crossobj.style.left = 0 ;

}

function moveLeft(divname,owidth)
{
 var crossobj=document.getElementById(divname) ;
 var contentwidth=crossobj.offsetWidth ;
 leftpos = (contentwidth - 300) * (-1)  ;

 if ( parseInt(crossobj.style.left) > leftpos )
  crossobj.style.left = parseInt(crossobj.style.left) - owidth ;
}

Datapager in asp.net 3.5

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <style type="text/css">       
      th
      {
        background-color:#eef4fa;
        border-top:solid 1px #9dbbcc;
        border-bottom:solid 1px #9dbbcc;
      }
      .itemSeparator { border-right: 1px solid #ccc }
      .groupSeparator
      {
        height: 1px;
        background-color: #cccccc;
      }
    </style>

</head>
<body>
    <form id="form1" runat="server">
    <div>    
      <asp:DataPager runat="server" ID="BeforeListDataPager"
        PagedControlID="ProductsListView"
        PageSize="18">
        <Fields>
          <asp:NextPreviousPagerField ButtonType="Link"
            ShowFirstPageButton="true"
            ShowNextPageButton="false"
            ShowPreviousPageButton="false"
            FirstPageText="« Prev" />
          <asp:NumericPagerField ButtonCount="10" />
          <asp:NextPreviousPagerField ButtonType="Link"
            ShowLastPageButton="true"
            ShowNextPageButton="false"
            ShowPreviousPageButton="false"
            LastPageText=" Next »" />
            </Fields>
            </asp:DataPager>

      <asp:ListView ID="ProductsListView"
        DataSourceID="SqlDataSource1"
        GroupItemCount="3"
        runat="server">
        <LayoutTemplate>
          <table cellpadding="2" width="640px" id="tbl1" runat="server">
            <tr>
              <th colspan="5">PRODUCTS LIST</th>
            </tr>
            <tr runat="server" id="groupPlaceholder"></tr>
          </table>
        </LayoutTemplate>
        <GroupTemplate>
          <tr runat="server" id="tr1">
            <td runat="server" id="itemPlaceholder"></td>
          </tr>
        </GroupTemplate>
        <GroupSeparatorTemplate>
          <tr id="Tr1" runat="server">
            <td colspan="5">
                <div class="groupSeparator"><hr></div>
              </td>
          </tr>
        </GroupSeparatorTemplate>
        <ItemTemplate>
          <td id="Td1" align="center" runat="server">
            <asp:Label ID="lblcomp" Text='<%#Eval("companyname") %>' runat=server></asp:Label>
          </td>
        </ItemTemplate>
        <ItemSeparatorTemplate>
          <td id="Td2" class="itemSeparator" runat="server"> </td>
        </ItemSeparatorTemplate>
      </asp:ListView>
     <asp:DataPager runat="server" ID="Afterpagerlist"
        PagedControlID="ProductsListView"
        PageSize="18">
        <Fields>
          <asp:NextPreviousPagerField ButtonType="Link"
            ShowFirstPageButton="true"
            ShowNextPageButton="false"
            ShowPreviousPageButton="false"
            FirstPageText="« Prev" />
          <asp:NumericPagerField ButtonCount="10" />
          <asp:NextPreviousPagerField ButtonType="Link"
            ShowLastPageButton="true"
            ShowNextPageButton="false"
            ShowPreviousPageButton="false"
            LastPageText=" Next »" />
            </Fields>
            </asp:DataPager>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT top 200 [CompanyName] FROM [Registration]">
        </asp:SqlDataSource>   </div>
    </form>
</body>
</html>

Tuesday, June 17, 2008

Edit ,Delete,Update in Gridview



    Untitled Page
    


    
update college/univercity name in COLLEGEPATH table:
<%#Eval("RegID")%> <%#Eval("companyname")%>
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 multieditepage : System.Web.UI.Page
{
    advReport adv = new advReport();
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {

            this.DataBind1();
        }

    }

    protected void cancel(object sender, GridViewCancelEditEventArgs e)
    {
        dg.EditIndex = -1;
        this.DataBind1();
    }
    protected void edit(object sender, GridViewEditEventArgs e)
    {
        dg.EditIndex = e.NewEditIndex;
        this.DataBind1();
    }
    protected void update(object sender, GridViewUpdateEventArgs e)
    {
        string regid = ((TextBox)(dg.Rows[e.RowIndex].FindControl("txtreg"))).Text;
        string name = ((FileUpload)(dg.Rows[e.RowIndex].FindControl("upfile"))).FileName;
       
            adv.updateevents(regid, name);
            dg.EditIndex = -1;
            this.DataBind1();
     
    }
   protected void delete(object sender, GridViewDeleteEventArgs e)
    {
   
        int regid = Convert.ToInt32(dg.DataKeys[e.RowIndex].Value);
        adv.deleterecord(regid);
        dg.EditIndex = -1;
      this.DataBind1();
    }
    protected void DataBind1()
    {
         DataSet ds = new DataSet();
      
        SqlDataAdapter myAdapter = new SqlDataAdapter("collegepathupdate", adv.connect());
       
        myAdapter.Fill(ds);
        PagedDataSource objPds = new PagedDataSource();
        objPds.DataSource = ds.Tables[0].DefaultView;

        objPds.AllowPaging = true;
        objPds.PageSize = 13;

        objPds.CurrentPageIndex = CurrentPage;

        lblfind.Text = "Page: " + (CurrentPage + 1).ToString() + " of "
            + objPds.PageCount.ToString() + "    Total Records :(" + ds.Tables[0].Rows.Count.ToString() + ")";

        // Disable Prev or Next buttons if necessary
        cmdPrev.Enabled = !objPds.IsFirstPage;
        cmdNext.Enabled = !objPds.IsLastPage;
        dg.DataSource = objPds;
        dg.DataBind();

    }

    protected void cmdPrev_Click(object sender, System.EventArgs e)
    {
        // Set viewstate variable to the previous page
        CurrentPage -= 1;

        // Reload control
        DataBind1();
    }

    protected void cmdNext_Click(object sender, System.EventArgs e)
    {
        // Set viewstate variable to the next page
        CurrentPage += 1;

        // Reload control
        DataBind1();
    }
    public int CurrentPage
    {
        get
        {
            // look for current page in ViewState
            object o = this.ViewState["_CurrentPage"];
            if (o == null)
                return 0; // default to showing the first page
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_CurrentPage"] = value;
        }
    }
   
}

public class advReport
{
   public advReport()
    {
    }

 public void updateevents(string regid,string name)
    {
        int chk=1;
      
        SqlCommand cmd = new SqlCommand("insert into collegepath(regid,collegeurl,updatechk) values(@regid,@name,@chk)", connect());
        cmd.Parameters.Add("@regid", SqlDbType.Int).Value = Convert.ToInt32(regid);
        cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = name;
        cmd.Parameters.Add("@chk", SqlDbType.Int).Value = chk;

       
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();
    }
public void deleterecord(int regid)
    {
        SqlCommand cmd = new SqlCommand("delete from registration where regID=@regid", connect());
        cmd.Parameters.Add("@regid", SqlDbType.Int).Value = regid;
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();

    }
}

Saturday, June 7, 2008

Tag Cloud in Asp.net

<script runat="server">

    public string st;
    protected void Page_Load(object sender, EventArgs e)
    {
        st = CategoryCloud();
    }
    private string CategoryCloud()
   {   
        String theme = "<a class='weight{weight}' href=#?tag={url}'>{cat}</a> ";
        StringBuilder sb = new StringBuilder();
        double max = 0;
        System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("server=.;database=northwind;uid=sa;pwd=sa");
        DataTable ds = new DataTable();
        System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter("SELECT a.CategoryID,a.CategoryName, COUNT"
         +"(b.ProductID) AS NumberOfProducts FROM Categories AS a INNER JOIN Products AS b"
         +" ON a.CategoryID = b.CategoryID GROUP BY a.CategoryID, a.CategoryName ORDER BY a.CategoryName", con);
         sda.Fill(ds);
        double.TryParse(ds.Compute("max(NumberOfProducts)", null).ToString(), out max);
        foreach (DataRow rv in ds.Rows)
        {
            double Percent = (double.Parse(rv["NumberOfProducts"].ToString()) / max) * 100;
            int weight = 0;
            if (Percent >= 99)
                //heaviest
                weight = 1;
            else if (Percent >= 70)
                weight = 2;
            else if(Percent >= 40)
                weight = 3;
            else if (Percent >= 20)
                weight = 4;
            else if (Percent >= 3)
                //weakest
                weight = 5;
            else
                weight = 0;
                        
            if (weight > 0)
               sb.Append(theme.Replace("{weight}", weight.ToString()).Replace("{cat}", rv["categoryname"].ToString()).Replace("{url}", HttpUtility.UrlEncode(rv["categoryname"].ToString())));
        }
         return sb.ToString();
    }

 

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <style>
#tagCloud
{
 width:238px;
 border:solid 1px #ccc;
 padding:1px;
 margin-bottom:10px;
 text-align:inherit;
 line-height:0.5em; color:blue;
 height:40px;
}

#tagCloud A
{
 text-decoration:none;
 margin-left:5px;
 margin-right:5px;
 font-family:Trebuchet MS, Verdana, Arial;
 text-transform:lowercase;
}

#tagCloud A:hover
{
 color:#00cc00;
 text-decoration:underline;
 line-height:0.9em;
}

#tagCloud A.weight1
{
 color: #ff9900;
 font-size: 14pt;
 font-weight:bolder;
 text-decoration:underline;
}
#tagCloud A.weight2
{
 color: #4169e1;
 font-size:12pt;
 font-weight:bolder;
}
#tagCloud A.weight3
{
 color: #009eff;
 font-size: 11pt;
 font-weight:bolder;
 text-decoration:underline;
}
#tagCloud A.weight4
{
 color: #4188cf;
 font-size: 10pt;
 
}
#tagCloud A.weight5
{
 color: #83bcd8;
 font-size: 8pt;
 
}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div id="tagCloud" >
       <%=st %>
   </div>
    </form>
</body>
</html>

Friday, May 23, 2008

keyword searching result from database in C#

public static DataSet RelatedKeyword(string keyword)

{string[] arr =keyword.Replace("& ","").Split(' ');

DataSet ds = new DataSet();

DataSet dsTemp = new DataSet();

bool flag = false;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["remote"].ConnectionString);

// DBAccess db = new DBAccess();

SqlDataAdapter sda;

foreach (string s in arr)

{ if (s.Length >= 2)

{ sda = new SqlDataAdapter("select distinct top 60 keywordid, keywordname from keyword  where keywordname like '%'+@ksearch+'%'", con);

sda.SelectCommand.Parameters.Add("@ksearch", SqlDbType.VarChar).Value = s;

sda.Fill(dsTemp);

sda.SelectCommand.Parameters.Clear();

ds.Merge(dsTemp);

if (flag == false)

{DataColumn[] pk = new DataColumn[1];

pk[0] = ds.Tables[0].Columns["keywordid"];

ds.Tables[0].PrimaryKey = pk;

flag = true;

}}}

return ds;}

send data from html page to server pages

 


head>

<title>Untitled Page</title>

<script language=javascript>

function submitvalue()

{

var red=document.getElementById('rd');

var val="PH";

if(rd[0].checked==true)

{val="KH";

}

window.location.href="keywordsearch.aspx?kq="+document.getElementById('txtsearch').value+"&stype="+val;

}

</script>

</head>

<body>

<input type=text name="txtsearch" runat=server />

<input type=radio name="rd" value="KH" runat=server checked=checked/>

<input type="radio" name="rd" value="PH" runat=server/>

<input type="button" name="btnsearch" value="search" onclick="submitvalue();"/>

</body>

Friday, May 16, 2008

Open .aspx page with parameter in popup window



<a href=”javascript:return false;” onclick=”javascript:window.open(’sendquery.aspx?rg=” + sd.REGID + “&comp=” + sd.COMPANYNAME + “&city=” + sd.CITYNAME + “‘,’smallwindowsms’,'toolbars=0,crollbars=0,width=600,

height=500,menubar=0,resizable=0′);return false;”>send query</a>

Thursday, May 15, 2008

protect copy of data on page in javascript

<



SCRIPT language=javascript type=text/javascript> 

function disableCtrlKeyCombination(e)

{//list all CTRL + key combinations you want to disable 

var forbiddenKeys = new Array('a', 'n', 'c', 'x', 'v', 'j');

var key;var isCtrl;

if(window.event)

{key = window.event.keyCode; //IE

if(window.event.ctrlKey)

isCtrl = true;

else

isCtrl = false;

}

else

{key = e.which; //firefox

if(e.ctrlKey)

isCtrl = true;

else

isCtrl = false;

}

//if ctrl is pressed check if other key is in forbidenKeys array

if(isCtrl)

{for(i=0; i<forbiddenKeys.length; i++)

{// alert(forbiddenKeys[i]);

//case-insensitive comparation

if(forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase())

{// alert('Key combination CTRL + ' +String.fromCharCode(key) +' has been disabled.');

return false;

}}}

return true;



function click(e) {

if (document.all) {

if (event.button == 2) {

//alert(message);

return false;

}}

if (document.layers) {

if (e.which == 3) {

// alert(message);

return false;

}}}

if (document.layers) {

document.captureEvents(Event.MOUSEDOWN);

}

document.onmousedown=click;

</script>

in body tag write

<body oncontextmenu="return false" onkeypress

="return disableCtrlKeyCombination(event);" onkeydown="return disableCtrlKeyCombination(event);" >
AJAX, asp, Asp.net, asp.net and sql server security, Asp.net IntemIndex, C#, Css, DataBinder.Eval, DataKeyNames, Datalist, Datapager, DataSet, DataTable, DropDownList, FindControl, gridview, JavaScript, jquery, Listview, Paging, Regex, RegularExpression, Repeater, Server side validation, Sql Server, timer, timercallback, Validation, XML, xmlnode, XPath