Reading, Opening Excel File Using C#:
                                                           By using this code you can read Excel sheet data into dataset. First you have to create a project then create file upload control and a submit button and on button click write the following code.

Code:

using System;
using System.Configuration;
using System.Data;
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.Data.OleDb;

public partial class _ParseExcel : System.Web.UI.Page 
{
protected void Page_Load(object sender, EventArgs e)
{ 
}
protected void btnParseExcel_Click(object sender, EventArgs e)
{
string path = System.IO.Path.GetFullPath(uploadFile.PostedFile.FileName);
string connString = "provider=Microsoft.Jet.OLEDB.4.0;" + @"data source="+path +";" + "Extended Properties=Excel 8.0;"; 
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "Table");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch
{
}
finally
{
oledbConn.Close();
} 
}
}
Read more ...

How to disable copy, paste,cut options with a right click using javascript
                                                                     Javascript based techniques can be easily disabling javascript support methods on browsers. The following script also work with IE

Code:

<html>
<head>
</head>
<body oncopy="return false;" onpaste="return false;" oncut="return false;">
    <form id="form1" runat="server">
        <div>
           Try to copy this and paste in your editor
        </div>
    </form>
</body>
</html>



Read more ...

Splitting a string in C#

Posted by Prince | 6:56:00 PM | | 0 comments »

Split a string using c#: 
                                           The String.Split() method used to split one or more string from a line in C Sharp. To split a string we need a separator to set a string length for split. In the following example I'm using the '#'  symbol to separate the strings.

Code:

//Input string = "split#a#string#" 

String[] split; 
split = String.Split('#'); 
str1 = split[0]; //split 
str2 = split[1]; //a 
str3 = split[2]; //string

Read more ...

Extract file name from path - C# / C Sharp:
                                                              The following simple C# code is used to Extract file name from a given path. Here I'm using the Substring() method to get the filename.

Code:
string strFileName = FileInput.PostedFile.FileName.ToLower;
if (strFileName.IndexOf("\\") > -1) {
 strFileName = strFileName.Substring(strFileName.IndexOf("\\"));
}
Read more ...

Get the index of the SelectedRow in a DataGridView:
                                                                                    You can get the index of the Selected Row in a Data Grid View by using the following c# code.

private void gvCustomer_SelectionChanged(object sender, EventArgs e) 
{ 
   if (gvCustomer.SelectedRows.Count == 1) 
    { 
       txtXML.Text = gvCustomer.Rows[gvCustomer.SelectedRows[0].Index].Cells["CustomerCode"].Value.ToString(); 
    } 
}
Read more ...

Validate email address in JavaScript:
                                             This is a script for validate  form box to ensure that the user entered a valid email address. If not, the form submition is canceled, and the surfer prompted to re-enter a valid address.

 This script validate the following assumptions:
  • The mailID should contains a least one character procedding the "@"
  • The mailID should contains a "@" following the procedding character(s)
  • The mailID should contains at least one character following the "@", followed by a dot (.), followed by either a two character or three character string .
Javascript code for validate email address:
<html>
<head>
    <title>Email Validation</title>
    <script type="text/javascript">
var error;
function isValidEmail(){
var str=document.mailValidation.txtEmail.value
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str)){
alert(str +" is  a valid email address");
error=false;
}
else{
alert("Please enter a valid email address!");
error=false;
}

return (error)
}
    </script>

</head>
<body>
    <form name="mailValidation">
    Enter Your Email Address:<br />
    <input type="text" size="15" name="txtEmail">
    <input type="submit" value="Submit" onclick="return isValidEmail();">
    </form>
</body>
</html>

Demo:

Enter Your Email Address:




Read more ...

Send Email using ASP.Net and C#

Posted by Prince | 7:54:00 PM | | 0 comments »

Send Email from your GMAIL account using ASP.Net and C#:
                                                    This article is provide a demo for send Emails  from your GMAIL account using ASP.Net and C#:
First create an aspx file named "SendGmail.aspx" with required input controls and action buttons. Please refer the below screen shot.


Give the id for from textbox as "txtFrom" and "txtTo", "txtSubject", "txtMessage"  respectively.
Then add the following code into the "Send Email" button's OnClick method in thecode behind. Before appropriate name space (if you need).

Code:
protected void btnSendEmail_Click(object sender, EventArgs e)
    {
        
//Create Mail Message Object with content that you want to send with mail.
        
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(txtFromMail.Text, txtToMail.Text, txtSubject.Text, txtMeaasge.Text);
        
mailMessage.IsBodyHtml = false;      
        
//Proper Authentication Details need to be passed when sending email from gmail
        
System.Net.NetworkCredential mailAuthentication = new
        
System.Net.NetworkCredential("YourGmailID""YourGmailPassword");
        
//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
        //For different server like yahoo this details changes and you can
        //get it from respective server.
        
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com"587);
        
//Enable SSL
        
mailClient.EnableSsl = true;
        
mailClient.UseDefaultCredentials = false;
        
mailClient.Credentials mailAuthentication;
        
mailClient.Send(mailMessage);
    
}
You can download full code for send email using csharp from here

Please leave some comment, if this post useful to you.
Read more ...

The type or namespace name 'MySql' could not be found:
                                  If you remove or delete the MySql.Data reference from your project library, you will get this type of errors. To resolve this you just follow the below steps.
 Solution:
Step 1: Download the Connector/Net from http://dev.mysql.com/downloads/connector/net/1.0.html

Step 2: Run the downloaded .exe file in to your system.

Step 3: Open your project in Visual Studio --> open references --> delete MySql.Data (old) reference.

Step 4: Right click on references and Add new assembly references for MySql.Data

Step 5: Build your library and you will get Build Succeed.
Read more ...


Show how many characters remaining in a html text box using javascript:
                                                                                     The following  javascript will help you to show how many characters are remaining for a textbox or textarea, The label placed next to the text box shown the number of character remaining.

<script type="text/javascript">
function txtCounters(id,max_length,myelement)
{
counter 
= document.getElementById(id);
field = document.getElementById(myelement).value;
field_length field.length;
 if 
(field_length <max_length)  {
//Calculate remaining characters
 
remaining_characters max_length-field_length;
//Update the counter on the page
  
counter.innerHTML remaining_characters;  }
 } 
</script>

<label for="txtName">Enter Your Text : </label>
<input type="text" id="txtName" size="50" maxlength="50" onkeyup="javascript:txtCounters('txtCounter',50,'txtName')"> <div id="txtCounter"><b>50</b></div>characters remaining.
Demo:

50
characters remaining.
Read more ...

Create Folder Using C#:

Posted by Prince | 7:55:00 PM | | 0 comments »

Create Folder Using C#:
          By using the following code you can give the user the ability to enter a directory name, check to see if it already exists and if not then create the folder and upload the files there.
                          First create a text box name as "txtFolderName" and a submit button name as "Create Folder" . It's just look like...


                Next, the bellow c# code used to validate if folder name exists and create a folder with name of "Image"
protected void btnCreateFolder_Click(object sender, EventArgs e)
    {
 
          if (!System.IO.Directory.Exists(MapPath(MyTree.SelectedValue + "\\" + txtFolderName.Text)))
          {           
            System.IO.Directory.CreateDirectory(MapPath(txtFolderName.Text));
            lblError.Text = "Created Successfully";
            txtFolderName.Text = "";     
          }             else
            {
                
lblError.Text = "Folder Already Exist";
            }
 

    }

Now you can see your new folder for your specified path and then leave some comment to encourage us.
Read more ...


 Save image in image type datatype:
                                            This is the  sample code for save image in image type datatype in mssql table using csharp.

Code for create database
CREATE TABLE Images(
ImageID 
INT IDENTITY(1,1PRIMARY KEY,
ImageData IMAGE)
In C# code behind: 
protected void btnSaveImage_Click(object sender, EventArgs e)
    {
        
if (FileUpload1.HasFile)
        {
            
byte[] ImageData ReadImage(FileUpload1.PostedFile.FileName);
            
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ToString());
            string 
query "INSERT INTO Images VALUES(@ImageData)";
            
SqlCommand com = new SqlCommand(query, con);
            
com.Parameters.AddWithValue("@ImageData", (object)ImageData);
            
con.Open();
            
com.ExecuteNonQuery();
            
con.Close();
        
}
    }

    
byte[] ReadImage(string ImagePath)
    {
        
byte[] ImageData = null;
        
FileInfo fi = new FileInfo(ImagePath);
        long 
NumberOfBytes fi.Length;
        
FileStream fs = new FileStream(ImagePath, FileMode.Open, FileAccess.Read);
        
BinaryReader br = new BinaryReader(fs);
        
ImageData br.ReadBytes((int)NumberOfBytes);
        return 
ImageData;
    
}
Write your comments after successfully run this code.
Read more ...

Random Password Generation Using C#

Posted by Prince | 4:30:00 PM | | 0 comments »



Generating Random Password Using C#:
                                                              The following method would be useful for generating random password using C#. You just give length of the password as input and get the random password.

Code:
   public static string GenerateRandomPassword(int length)
    {
        
char[] chars "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();
        string 
password = string.Empty;
        
Random random = new Random();

        for 
(int 0i < lengthi++)
        {
            
int random.Next(1,chars.Length);
            
//Don't Allow Repetation of Characters
            
if (!password.Contains(chars.GetValue(x).ToString()))
                password +
chars.GetValue(x);
            else
                
i--;
        
}
        
return password;
    
}
Its a simple logic instead by generating a random number between 1 and Length of characters. It also checks that same character is not repeated in generated password and finally return the randomly generated password string of desired length.
Read more ...


Dynamically change body background color using  javascript:
                                                                                           This is the sample code for Dynamically change the body/div/text background color using javascript. By using this code you can change the text color while the background changed dynamically.

Code:
<html>
<head>
    
<title>Dynamically change background color</title>
    
<script language="javascript" type="text/javascript">
var count=0;
function 
changeColor()
{
    setTimeout(
"showColorChange()",500);
}
function showColorChange()
{
    
var bg =new Array("red","darkblue","sky","yellow","blue","pink","green");
    var 
txt =new Array("black","white","green","blue","pink","red","yellow");
    if
(count<=6)
    {        
document.getElementById("divChangeColor").style.backgroundColor=bg[count++];
        document
.getElementById("txtChangeColor").style.color=txt[count++];
        
setTimeout("showColorChange()",500);
    
}
    
else
    
{
        count
=0;
        
changeColor();
    
}
}
    
</script>

</head>
<body onload="changeColor()">
    
<div id="divChangeColor" style="width: 300px; height: 300px; background-color: Gray">
        
<span id="txtChangeColor"><b>Look at me & my background</b></span>
    
</div>
</body>
</html>

Demo:







Look at me & my background
Read more ...

Related Posts Plugin for WordPress, Blogger...