Showing posts with label How to. Show all posts
Showing posts with label How to. Show all posts

Saturday, May 10, 2014

JQuery Allow specific number of Alphabets into text box in asp.net

Title:Allow only number of Alphabets in to Text box in asp.net using JQuery

Description:
As per previous article ,we have done validation on the text box which has to hold some value while doing the insertion.Now i would like describe and give an example on JQuery validation ,which will allow only 10 characters into text box.So here i will put condition text box length while performing the validation i:e is less then 10 ,it will show error message through alert box

Example:
<html>
<head runat="server">
<script type="text/javascript" src="Javascript/jquery-1.3.1.min.js"></script>
<script type="text/javascript" language="javascript">

$(document).ready(function() {

$('#allowOnlyChars').click(function() {

if ($("#OnlyChars").val().length < 10) {

alert('Valid data'+"#OnlyChars").val());

return true
}
else {
alert('Please: you should enter only 10 characters')
return false;
}
})
});
</script>
</head>
<body>
<form id="validateForm" runat="server">
<asp:TextBox ID="OnlyChars" runat="server"></asp:TextBox>
<asp:Button ID="allowOnlyChars" runat="server" Text="Validate" OnClick="allowOnlyChars_Click" />
</form>
</body>
</html>

Monday, July 15, 2013

how to compare two xml files in asp.net using c#

Title:How to compare XML files in Asp.net using C#

Description:

Now i would like to give an examples on Comparing of XML documents using C# code.Asp.net provide an algorithm which is "hash algorithm",can be used for encryption.So based on those methods i will do the comparison of files In the below method i have use two parameters which indicates the path of XML files

Examples:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Security.Cryptography;

private void CompareXMLDocumnet(string ActualDocumnet,string GenratedDocument)
{
if (File.Exists(ActualDocumnet) && File.Exists(GenratedDocument))
{
HashAlgorithm HA = HashAlgorithm.Create();
FileStream XmlFstream1 = new FileStream(ActualDocumnet, FileMode.Open);
FileStream XmlFstream2 = new FileStream(GenratedDocument, FileMode.Open);
byte[] Actual_Xmlhash1;
byte[] Genrated_Xmlhash2;
Actual_Xmlhash1= HA.ComputeHash(XmlFstream1);
Genrated_Xmlhash2= HA.ComputeHash(XmlFstream2);
XmlFstream1.Close();
XmlFstream2.Close();
if (Convert.ToBase64String(Actual_Xmlhash1) == Convert.ToBase64String(Genrated_Xmlhash2))
{
Response.Write(" similar="">
}
else
{
throw new Exception("Files are different");
}
}
}

Sunday, July 14, 2013

get the current month and year in asp.net

Title:How to get current month and year in asp.net using c#.net

Description:
As per previous articles we have seen how get month and year using JQuery. Now i would like to explain and give the example on the same concept in c#.net.The C#.net provide the object "Date Time" which has some properties to get the retired data.As per our discussion i will use the two methods to get the current month and year.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int year = DateTime.Now.Year;
int month = DateTime.Now.Month;
int date = (DateTime.Now.Day)+2;
Response.Write(year.ToString()+ month.ToString()+date.ToString());
}
}

Monday, July 1, 2013

Get dropdownlist selcted value in gridview in Asp.net

Title:
how Get Drop down List selected value  in grid view using c# in asp.net
Requirement: 
.Frame Work and Sql Server
Explanation:
Here i will show how to fire selected index event of drop down in grid view.When we work with drop down list in grid view ,Most  of  the confusion about how to get the selected value of DDL.By using this event(SelectedindexChanged) we can do it.
As per requirement have to display details of selected record details in report page.By using this ,will get Drop down selected value in grid view. In the above i have fetched the drop down list selected value which in grid view.

protected void ddlorders_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow GvOrderrow= (GridViewRow)ddlorders.NamingContainer;
DropDownList ddlOrdr_name= ((DropDownList)(GvOrderrow.FindControl(“ddlorders"))).SelectedValue;
if((ddlOrdr_name.SelectedValue.ToString()) =="")
{
Response.Write("No order Exist");
}
else
{
Respose.Redirect("Report.aspx?order='"+ CurrentOrdr+"'");
}


Sunday, May 12, 2013

how to export gridview to csv file in asp.net

Title: How to export grid view data to CSV or Text file in asp.net using c#.net

Description:
As per previous articles we have seen how to Bind CSV data to Grid view in asp.net,Export Grid view Data to Word Document,Export Grid view data to PDF document,Import XML data to GridView in Asp.net .Here i would like explain about how to export grid view data to CSV file in asp.net.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Export2CSV.aspx.cs" Inherits="Export2CSV" EnableEventValidation="false" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GvOrderDetails" runat="server" AutoGenerateColumns="False" >
</asp:GridView>
<asp:Button ID="btnExportCSV" runat="server" Text="Gridview To CSV" onclick="btnExportCSV_Click" />
<div>
</div>
</form>
</body>
</html>
Code behind:In the below Grid view data bind has done while page loading.when we fire click event the data colud be export to CSV file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


public partial class Export2CSV : System.Web.UI.Page
{
SqlConnection Econ = new SqlConnection(ConfigurationManager.ConnectionStrings["Exportconn"].ToString());
DataSet ds = new DataSet();
  
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlCommand cmd = new SqlCommand("select * from orders", Econ);
SqlDataAdapter Gda = new SqlDataAdapter(cmd);
Gda.Fill(ds);
GvOrderDetails.DataSource = ds;
GvOrderDetails.DataBind();
}
}

protected void btnExportCSV_Click(object sender, EventArgs e)
{
     
SqlDataAdapter Cda = new SqlDataAdapter("SELECT* FROM Orders",Econ);
DataTable Gdt = new DataTable();
Cda.Fill(ds);
    //Bind data to Data table
Gdt = ds.Tables[0];
StreamWriter Exportsw = new StreamWriter("E:\\OrderCSVReport.csv", false);
int CSVCount = Gdt.Columns.Count;
for (int i = 0; i < CSVCount; i++)
{
Exportsw.Write(Gdt.Columns[i]);
if (i < CSVCount - 1)
{
Exportsw.Write(",");
}
}
Exportsw.Write(Environment.NewLine);

foreach (DataRow Gdr in Gdt.Rows)
{
for (int i = 0; i < CSVCount; i++)
{
if (!Convert.IsDBNull(Gdr[i]))
{
Exportsw.Write(Gdr[i].ToString());
}
if (i < CSVCount - 1)
{
Exportsw.Write(",");
}
}
Exportsw.Write(Environment.NewLine);
}
Exportsw.Close();
}
}
}

Tuesday, April 30, 2013

How to send a mail in asp.net

Title: How to send an email in asp.net using c#.net

Description:
In previous posts i have given send a mail with attachment in asp.net,Send mail using service,send a Email with html Format in Asp.Net.In the same way i just given an example on sending email concept in asp.net.The following example has two text boxes which are used to give the subject and name to mail message
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Send a mail in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtSub" runat="server"></asp:TextBox>
<asp:TextBox ID="txtbody" runat="server"></asp:TextBox>
<asp:Button ID="btnsendmail" runat="server" Text="Send" onclick="btnsendmail_Click" />
</form>
</body>
</html>
Codebehind:
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Mail.Net;

public partial class _sendmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnsendmail_Click(object sender, EventArgs e)
{
try
{
SmtpClient SmtpmServer = new SmtpClient(SmtpserverName);
SmtpmServer.Credentials = new System.Net.NetworkCredential(Username, PWD);
MailMessage MlMsg = new MailMessage();
MlMsg.From = new MailAddress("bhaskar7698@gmail.com");
MlMsg.Body = txtbody.Text;;
MlMsg.IsBodyHtml = true;
MlMsg.To.Add(mulebhaskarareddy@gmail.com);
MlMsg.Subject = txtSub.Text;
SmtpmServer.Send(MlMsg);
Respose.Write("Mail sent successfully");
}
catch (Exception em)
{
Respose.Write(em.Message.Tostring());
}
}
}

Sunday, July 1, 2012

How to Bind data to gridview in asp.net

Title: How to bind data to grid view in asp.net using c#.net

Description:
This is the basic concept of the data binding to data source controls in asp.net.Now i would like to explain and given example on bind data to drop down list in grid view,In this post i will explain how to bind the data to grid view example in asp.net.Here the stored procedure has been used to get the data from sql database.In the same way we can see how to call a stored procedure in this example

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Bind data to gridview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grvdoc" AllowSorting="True" Runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

Code Behind:

protected void Page_Load(Object Sender, EventArgs E) 
{
SqlConnection con=new SqlConnection("Data Source=Test;Initial Catalog=binddata;Integrated Security=true")
SqlCommand cmd = new SqlCommand("fiilldocgridview", con);
cmd.CommandType = CommandType.StoredProcedure;con.Open();
SqlDataAdapter ad = new SqlDataAdapter(cmd);DataSet ds = new DataSet();
try
{
da = new SqlDataAdapter(cmd);
da.Fill(ds, "DoctorsTable");
grvdoc.DataSource = ds;
grvdoc.DataBind();
}
catch
{
throw;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
}
filldocgridview Stored Procedure:

CREATE PROCEDURE [dbo].[fiilldocgridview]
AS
SELECT * FROM  binddata

Thursday, June 28, 2012

how to get browser name in Jquery/javascript

Title: JQuery Get browser name in Asp.net

Description:
While working with web application we need to set or get some browser compatibility settings as per requirement.Now i would like to describe how to resolve some design issues of asp button  control based on browser using JQuery.In Java script we have an object "navigator" ,which can be used to get the browser name in java script.Here i converted the navigator user value  to upper case letters ,then based on  condition i will filter the browser.
Javascript:
<script>
window.onload(GetBrowserDemo());
function GetBrowserDemo()
{
var btnid=document.getElementById("<%=btntest.ClientID%>");
var browservalue = navigator.userAgent.toUpperCase(); 
if(browservalue .indexOf("FIREFOX") > -1)
{ 
alert('FireFox');
btnid.val="Test"
} 
else if(browservalue .indexOf("MSIE") > -1)
{ 
alert('IE');
btnid.val="Edit";
} 
else if (browservalue .indexOf("CHROME") > -1)
{
alert('Chrome');
btnid.val="update";
} 
}
</script>
Jquery:
$(document).ready(function() {
if ($.browser.msie){
alert('It is IE');
}
if( $.browser.opera){
alert('It is Opera');
}
if ($.browser.mozilla){
alert('It is Mozilla);
}
if( $.browser.safari ){
alert('It is Safari');
}
});
}
In JQuery ,It has an object "browser" to get the current browser name .if we use the JQuery ,we  have to add the jquery reference library . Please refer this link 

Jquery browser Objet with examples

Wednesday, March 28, 2012

Datatable to Gridview in asp.net

Title: How to bind the data to grid view using data table in asp.net c#.net

Description:
Here i will show how to transfer the data the from data table to Grid view .For this i have generated custom data table " dtOrders" and add desired columns to it.Then i created a object to add the row data into data table and expression property is used to get the desirable format of data.

Example:
DataTable dtOrder = new DataTable();
dtOrder.Columns.Add("OrderId"); 
dtOrder.Columns.Add("Name");  
dtOrder.Columns.Add("Quantity");  
dtOrder.Rows.Add(new Object[] { "12", "pharmacy", "2000" });
dtOrder.Columns[3].Expression = string.Format("{0},{1},{2}", "OrderId", "Name", "Quantity"); 
gvOrders.DataSource = dtOrders;    
gvOrders.DataBind();

Tuesday, December 27, 2011

sql bulk copy in .net

Title:How to use SQL bulk copy in Asp.net using C#.net

Description:
SQL bulk copy is a concept of copying records from source database to destination database in asp.net.Here the source database can be any data base.The destination should be SQL server.Because SQL bulk copy is compatible with sql server.The advantage of SQL bulk copy concept is copying records will be faster with less burden of of developer.This process requires three steps.Here i have taken one button to perform this operation
1.Creating data reader and write into source data-base table
2.Creating sqlbulkcopy component with destination database component
3.Providing data reader to bulk copy component for writing to destination database table.

Imports System.Data.Oledb
Imports System.Data.SqlClient
//button click event
private sub button1_Click
Dim cn As New OleDbConnection("provider=msdaora.1;user Id=scott;password=tiger")
Dim cmd As New OleDbCommand("select*from dept",cn)
Dim dr As OleDbDataReader
cn.Open()
dr=cmd.ExcuteReader()
//creating destination Database connection and bulk copy component
Dim Dcn As New OleDbConnection("user Id=sa;password=;Database=invoice")
Dcn.Open()
Dim Bcopy As New SqlBulkCopy(Dcn)
Bcopy.DestinationTableName="dept"
//provide data reader to bulk copy component for reading from source and copying destination
Dcopy.WriteToServe(dr)
//Writretoserver will read using Dr and write to sqlserver table
dr.Close()
Cn.Close()
Dcn.close()
MsgBox("Copied Succesfully")
End Sub
)
C#:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.Oledb;
using System.Data.SqlClient;


//button click event

OleDbConnection cn = new OleDbConnection("provider=msdaora.1;user Id=scott;password=tiger");
OleDbCommand cmd = new OleDbCommand("select*from dept", cn);
OleDbDataReader dr = default(OleDbDataReader);
cn.Open();
dr = cmd.ExcuteReader();
//creating destination Database connection and bulk copy component
OleDbConnection Dcn = new OleDbConnection("user Id=sa;password=;Database=invoice");
Dcn.Open();
SqlBulkCopy Bcopy = new SqlBulkCopy(Dcn);
Bcopy.DestinationTableName = "dept";
//provide data reader to bulk copy component for reading from source and copying destination
Dcopy.WriteToServe(dr);
//Writretoserver will read using Dr and write to sqlserver table
dr.Close();
Cn.Close();
Dcn.close();
Interaction.MsgBox("Copied Succesfully");

Thursday, November 24, 2011

how to select data from multiple tables in sql server

Title:How to retrieve the data from set of tables in SQL server

Description:
As per recent articles we have seen how to get the data from single table in SQL server.Now i want explain the same concept with multiple tables.The SQLserver has provided a Keyword which is used to get data from set of  tables using SQL query i:e"INTERSECT" keyword.Here i will show to get empid ,name from employee table by comparing with empid column in Department table

SELECT empid, name FROM Employee
WHERE empid IN
SELECT empid FROM Employee INTERSECT SELECT empid FROM Department) 
Here i have shown one more query to get the data from different table with out join
SELECT em.empid,em.name FROM Employee em,Department de WHERE em.empid=de.empid 

Tuesday, November 22, 2011

Changing column name and Datatype in Table in Sql

Title:How to Change column name and datatype in SQL server

Description:
This kind scenario will happen when we have to change the data base filed name or data type as per requirement.As per my application i need change the column type to Null.The SQL server provides a default stored procedure "sp_changename",which can make the things easier.Here i have used ALTER command To change the column name and data type in the table

Syntax:
Alter table TableName alter column ColumnName DataType NULL/NOT NULL
EXEC sp_changename        
@objname = ' TableName. OldColumnName’,
@newname = 'New ColumnName',
@objtype = 'COLUMN'

Example:
Alter table Organisation alter column name int null
EXEC sp_changename
@objname = 'Oraganisation.name',
@newname = 'name',
@objtype = 'COLUMN'

Saturday, November 19, 2011

Allow only numeric values from Keyboard using jquery

Title: How to allow only number in asp.net using JQuery

Description:As we know this is the validation kind of functionality of a control in any web application.the below example will describe how to allow only number when you click on the keyboard.So the required field will not the characters from the board

function NumericOnly(e) {
var presskey;
if (navigator.appName.lastIndexOf("Microsoft Internet Explorer") > -1)
presskey= e.keyCode;else
presskey= e.which;if ((presskey== 0 || presskey== 8 || presskey== 9))       
return true;
if ((presskey> 47 && presskey< 58))
return true;
else { e.returnValue = null; return false;
}
}

Bel