Friday, April 25, 2008

Export Gridview to Word file

create new website and add Default page and in it add Gridview and button control
We will use Northwind database


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 ExportToWord : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = BindData();
GridView1.DataBind();
}
}

private string ConnectionString
{

get { return @"Data Source=YASER\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"; }

}



private DataSet BindData()
{
// make the query
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
return ds;

}

protected void Button1_Click(object sender, EventArgs e)
{

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

}

public override void VerifyRenderingInServerForm(Control control)
{

}


}

Export Gridview to Exel file

create new website and add Default page and in it add Gridview and button

In Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = BindData();
GridView1.DataBind();
}
}

private string ConnectionString
{

get { return @"Data Source=YASER\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"; }

}

private DataSet BindData()
{
// make the query
string query = "SELECT * FROM Products";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Products");
return ds;

}

protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");

Response.Charset = "";

// If you want the option to open the Excel file without saving than

// comment out the line below

// Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ContentType = "application/vnd.xls";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);

GridView1.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();

}

public override void VerifyRenderingInServerForm(Control control)
{

// Confirms that an HtmlForm control is rendered for the
//specified ASP.NET server control at run time.

}
}

Get List and Number of Online users

First create website and add Registe , Login and WhoIsOnline page in website

In OnlineUser page add lable (lblSessionCount) and Gridview (OnlineUserList) control which is bound to
(UserName (BoundField), IsOnline (CheckBoxField) , Email (BoundField) )


Im WhoIsOnLine.aspx.cs page add

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;

public partial class WhoIsOnLine : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//if (!IsPostBack)
//{
MembershipUserCollection OnlineUsers = new MembershipUserCollection();
MembershipUserCollection AllUsers = new MembershipUserCollection();
AllUsers = Membership.GetAllUsers();

foreach (MembershipUser user in AllUsers)
{
if (user.IsOnline)
{
OnlineUsers.Add(user);

}
}
int OnlineUserCount = OnlineUsers.Count;

lblSessionCount.Text = OnlineUserCount.ToString();
OnlineUserList.DataSource = OnlineUsers;
OnlineUserList.DataBind();
//}
}
}

Send Email (using System.Web.Mail)

First create new website project and add two pages :-
SendEmail.aspx and EmailSent.aspx

and in the page SendEmail.aspx add three TextBox (txtFrom , txtSubject , txtMessage)
and add button (btn_Send) and Lable control
and Required Validator for txtFrom , txtSubject


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.Web.Mail;

public partial class SendEmail : System.Web.UI.Page
{
string strMailOrTel;

protected void Page_Load(object sender, EventArgs e)
{

}
private bool SendMail()
{
try
{
string strTo = "y.ahmed@ewebbers.com";
string strFrom = txtFrom.Text;
string strBody = txtMessage.Text ;
string strSubject = txtSubject.Text ;
SmtpMail.SmtpServer = ("SMTP.ewebbers.com");
SmtpMail.Send(strFrom, strTo, strSubject, strBody);

return true;
}
catch (Exception ex)
{
return false;
}
}

protected void btn_Send_Click(object sender, EventArgs e)
{
bool TrueOrFalse = SendMail();
if ((TrueOrFalse == true))
{
Response.Redirect("~/MailSent.aspx");
}
else
{
Label1.Text = "Try again";
}

}


}

Send Email with attachment (using System.Web.Mail)

First create new website project and add two pages :-
SendEmail.aspx and EmailSent.aspx

and in the page SendEmail.aspx add three TextBox (txtFrom , txtSubject , txtMessage)
and add button (btn_Send) and Lable control
and Required Validator for txtFrom , txtSubject and Fileupload control


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.Web.Mail;
using System.IO;


public partial class SendEmail : System.Web.UI.Page
{
string strPath;

protected void Page_Load(object sender, EventArgs e)
{

}

private bool SendMail()
{
try
{

/* Create a new blank MailMessage */
MailMessage mailMessage = new MailMessage();

mailMessage.From = txtTo.Text;

mailMessage.To = "y.ahmed@ewebbers.com";

mailMessage.Subject = txtSubject.Text ;

msgMail.Body = txtMessage.Text ;

/* We use the following variables to keep track of
attachments and after we can delete them */

string attach1 = null;

/*strFileName has a attachment file name for attachment process. */

string strFileName = null;

if (FileUpload1.PostedFile != null)
{
/* Get a reference to PostedFile object */
HttpPostedFile attFile = FileUpload1.PostedFile;

/* Get size of the file */
int attachFileLength = attFile.ContentLength;

/* Make sure the size of the file is > 0 */
if (attachFileLength > 0)
{
/* Get the file name */
strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

/* Save the file on the server */
FileUpload1.PostedFile.SaveAs(Server.MapPath(strFileName));

/* Create the email attachment with the uploaded file */
MailAttachment attach = new MailAttachment(Server.MapPath(strFileName));

/* Attach the newly created email attachment */
mailMessage.Attachments.Add(attach);

/* Store the attach filename so we can delete it later */
attach1 = strFileName;
}

/* Set the SMTP server and send the email with attachment */
SmtpMail.SmtpServer = ("SMTP.ewebbers.com");

SmtpMail.Send(mailMessage);

/* Delete the attachements if any */
if (attach1 != null)
{
File.Delete(Server.MapPath(attach1));
}
}

return true;
}
catch (Exception ex)
{
return false;
}
}

protected void btn_Send_Click(object sender, EventArgs e)
{
bool TrueOrFalse = SendMail();

if ((TrueOrFalse == true))
{
Response.Redirect("~/MailSent.aspx");
}
else
{
Label1.Text = "Try again";
}
}
}

Monday, April 14, 2008

Highlight Gridview Row when checbox is checked

First thing create Database (Company) with Table (Employee)
which has fields (Id,Name)

Second enter data in Database

Now create new website


In Default.aspx add Gridview and in Gridview add Template field
and in ItemTemplate add checkbox(cbxId)

and in Default.aspx.cs

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.Text;

public partial class SelectGridview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

//-- for Highlight
if ((e.Row.RowType == DataControlRowType.DataRow))
{
StringBuilder script = new StringBuilder();
script.Append("if (this.checked) {");
script.Append("document.getElementById('");
script.Append(e.Row.ClientID);
script.Append("').style.backgroundColor='Blue';");
script.Append("} else {");
script.Append("document.getElementById('");
script.Append(e.Row.ClientID);
script.Append("').style.backgroundColor='';");
script.Append("}");
((CheckBox)e.Row.FindControl("cbxId")).Attributes.Add("onclick", script.ToString());

}

}
}

Send Email Using (System.Net.Mail)

First create new website project and add two pages :-
SendEmail.aspx and EmailSent.aspx

and in the page SendEmail.aspx add three TextBox (txtFrom , txtSubject , txtMessage)
and add button (Send) and Lable control
and Required Validator for txtFrom , txtSubject and also add CustomValidator control for txtMessage as we want the characters in txtMessage not more than 50 characters



In SendEmail.aspx.cs

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.Net.Mail;

public partial class Default2 : System.Web.UI.Page
{
private bool SendMail(string from, string body,string subject)
{
//string mailServerName = "SMTP.ewebbers.com";
string mailServerName = "SMTP.ewebbers.com";
MailMessage message = new MailMessage(from, "y.ahmed@ewebbers.com",subject, body);
SmtpClient mailClient = new SmtpClient();
mailClient.Host = mailServerName;
mailClient.Send(message);
message.Dispose();

return true;
}

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btn_Send_Click(object sender, EventArgs e)
{
bool x=SendMail(txtFrom.Text, txtMessage.Text,txtSubject.Text);
if (x == true)
{
Response.Redirect("~/MailSent.aspx");
}
else
{
Label1.Text = "Try again";
}
}

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (txtMessage.Text.Length > 50)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}

}
}


Note:- we can use javascript with CustomValidator to ensure that user not enter more than 50 characters in txtMessage
so we will add Javascript code in SendEmail.aspx page

// function ValidateComments(sender, args)
// {
// if (args.Value.length > 50)
// args.IsValid = false;
// else
// args.IsValid = true;
// }


and in property of CustomValidator control set ClientValidationFunction="ValidateComments"

Friday, April 4, 2008

Delete Checked in Gridview

First thing create Database (Company) with Table (Employee)
which has fields (Id,Name)

Second enter data in Database

Now create new website

in Default.aspx

write the following javascript code

//function SelectAll(id)
// {
// var frm = document.forms[0];
//
// for (i=0;i < frm.elements.length;i++)
// {
// if (frm.elements[i].type == "checkbox")
// {
// frm.elements[i].checked = document.getElementById(id).checked;
//
// }
// }
//
// }

and add Gridview and button (Delete)and lable (lblMsg)
and in Gridview add Template field and In HeaderTemplate add checkbox (cbxAll) and in ItemTemplate checkbox (cbxId)

and in Default.aspx.cs

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.Header))
{
//adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
((CheckBox)e.Row.FindControl("cbxAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbxAll")).ClientID + "')");
}
}

protected void btn_Delete_Click(object sender, EventArgs e)
{
try
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("cbxId");

if (checkbox.Checked == true)
{
// method to delete by Id

lblMsg.Text = "Selected deleted";
GridView1.DataBind();


}

}
}
catch (Exception ex)
{
lblMsg.Text = ex.Message.ToString();
}
}