Yasserzaid’s Weblog

December 25, 2008

Highlight Gridview Row when checbox is checked

Filed under: ASP.Net — yasserzaid @ 9:41 pm

Hi

try this example:

add Gridview and in Gridview add Template field
and in ItemTemplate add checkbox(Id = 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());

}

}
}

Good Luck

Send Multiple Email at the Same time (create Newsletter)

Filed under: ASP.Net — Tags: , — yasserzaid @ 9:40 pm

We want to create a newsletter where user enter his full name and his email which send him email of a deaily news in website
In other word this is a way to send email to multiple user at the same time

– First :- create database called (Database) has table named (Person_Data) has the following fields:
Id –> (int , Primary key , Identity)
FullName –> nnarchar(50)
Email –> nnarchar(50)

– Second :- craete website has the following pages
1) AddPerson.aspx
2) DataSaved.aspx
3) SendEmail.aspx
4) EmailSend.aspx

–**AddPerson.aspx :-
add two Textbox (txt_Full , txt_Email) and two RequiredFieldValidator control and button (Save)

–** AddPerson.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
{
public int add_Person(string Name, string Email)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data_ConnectionString"].ConnectionString);
string quey = “INSERT INTO [Person_Data] ([FullName], [Email]) VALUES (@FullName, @Email)”;
SqlCommand comm = new SqlCommand();
comm.CommandText = quey;
comm.CommandType = CommandType.Text;
comm.Connection = conn;
comm.Parameters.Add(“@FullName”,SqlDbType.NVarChar,50).Value=Name;
comm.Parameters.Add(“@Email”, SqlDbType.NVarChar, 50).Value = Email;
conn.Open();
int x = comm.ExecuteNonQuery();
conn.Close();
return x;
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)
{
int y = add_Person(txt_Full.Text, txt_Email.Text);
if (y > 0)
{
Response.Redirect(“~/DataSaved.aspx”);
}
else
{
ClientScript.RegisterStartupScript(Type.GetType(“System.String”), “messagebox”, ” “);
}
}
}

–** SendEmail.aspx
add Gridview and SQLDataSource control to select all data in Gridview1

–** 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.Data.SqlClient;
using System.Web.Mail;

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

//– send Email button
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data_ConnectionString"].ConnectionString);
string query = “SELECT Email FROM [Person_Data]“;
SqlCommand comm = new SqlCommand();
comm.CommandText = query;
comm.Connection = conn;
comm.CommandType = CommandType.Text;
SqlDataReader dr;
//— Send Email —-
string Email = “yasser021@gmail.com“;
string EmailPassword = “XXXXX”;
string subject = “NewsLetter”;
string body = “You are applied in newsletter”;
//—-
try
{
conn.Open();
dr = comm.ExecuteReader(CommandBehavior.CloseConnection);
string To=”";
while (dr.Read())
{
To = dr["Email"].ToString();
//–
bool s = MailSender.SendEmail(Email, EmailPassword, To, subject, body, MailFormat.Html, “”);
//if (s == true)
//{
// Response.Redirect(“~/EmailSend.aspx”);
//}
//else
//{
// ClientScript.RegisterStartupScript(Type.GetType(“System.String”), “messagebox”, ” “);
//}
}
dr.Close();
}
catch (Exception ex)
{
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}

Don’t forget i create a class called MailSender.cs
that used to send Email

Good Luck

How to Refresh Page after time

Filed under: ASP.Net — yasserzaid @ 9:35 pm

Hi

In Page_Load of page write this code :

HtmlMeta RedirectMetaTag = new HtmlMeta();
RedirectMetaTag.HttpEquiv = “Refresh”;
Response.AppendHeader(“Refresh”, “5″);

Good Luck

Get DayNames in a given Culture

Filed under: ASP.Net — yasserzaid @ 9:32 pm

Sometimes we may need to have the day names in a week for a given culture. With ASP.NET CultureInfo class you can loop through the DateTimeFormat.DayNames and get them. Here is the example of it

using System.Globalization;
CultureInfo ci = new CultureInfo(“ar-ae”);
// gets the day names of arabic, arab emirates
foreach (string day in ci.DateTimeFormat.DayNames)
Response.Write(day + ” “);

Depending on the culture you want, you can get the CultureInfo reference for that corresponding culture. The DateTimeFormat also provides other values like month names, first day of week etc.,

Good Luck

ASP.NET Regular Expression for date format

Filed under: ASP.Net — yasserzaid @ 9:31 pm

In ASP.Net Many times required to Validate Date Fromat Enter in Control.in Regular Expression Following RE used to Validate Date Format.

dd/mm/yyyy Format (optional mm,optional dd)
([1-9]0[1-9][12][0-9]3[01])[- /.]([1-9]0[1-9]1[012])[- /.][0-9]{4}$

mm/dd/yyyy (optional mm,optional dd)
^([1-9]0[1-9]1[012])[- /.]([1-9]0[1-9][12][0-9]3[01])[- /.][0-9]{4}$

mm/dd/yyyy (Exact Format)
^([01]\d)/([0-3]\d)/(\d{4})$

Good Luck

Prevent Multiple Login at the same time

Filed under: ASP.Net — yasserzaid @ 9:30 pm

Hi

Try this:
protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
e.Cancel = Membership.GetUser(Login1.UserName).IsOnline;
}

or try this code

void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
MembershipUser u = Membership.GetUser(Login1.UserName); Response.Write(u.IsOnline);
if (u.IsOnline)
{
Login1.FailureText = “A user with this username is already logged in.”; e.Cancel = true;
}
else
{
Login1.FailureText = String.Empty;
e.Cancel = false;
}
}

Good Luck

Select top and last five record from Database

Filed under: SQL Server — yasserzaid @ 9:28 pm

In Query try this:

FOR TOP 5
select top 5 * from table

//——————-

FOR LAST 5
select top 5 * from table order by primarykey_columnname desc

Good Luck

Captcha Verification Image

Filed under: ASP.Net — Tags: , — yasserzaid @ 9:13 pm

Hi

try this example to create Contact us Page with Verification Image (Captcha)

Step1 :Create CaptchaImage.aspx Page

in code behind:

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.Drawing;
using System.Drawing.Imaging;

public partial class CaptchaImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Random Rand = new Random();
        int iNum = Rand.Next(10000, 99999);
        Bitmap Bmp = new Bitmap(90, 50);
        Graphics Gfx = Graphics.FromImage(Bmp);
        Font Fnt = new Font(“Verdana”, 12, FontStyle.Bold);
        Gfx.DrawString(iNum.ToString(), Fnt, Brushes.Yellow, 15, 15);
        // Create random numbers for the first line
        int RandY1 = Rand.Next(0, 50);
        int RandY2 = Rand.Next(0, 50);

        // Draw the first line
        Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2);
        // Create random numbers for the second line
        RandY1 = Rand.Next(0, 50);
        RandY2 = Rand.Next(0, 50);
        // Draw the second line
        Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2);
        Bmp.Save(Response.OutputStream, ImageFormat.Gif);
        Session["Number"] = iNum;
    }
}

step 2: Create Default.aspx page

<%@ PAGE LANGUAGE=”C#” AUTOEVENTWIREUP=”true” CODEFILE=”Default.aspx.cs” INHERITS=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<HTML XMLNS=”http://www.w3.org/1999/xhtml“>
<HEAD RUNAT=”server”>

</HEAD>
<BODY>
    <FORM ID=”form1″ RUNAT=”server”>
        <H2>Contact Us Form</H2>
        <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 WIDTH=80%>
            <TR>
                <TD>
                    <strong>Full Name</strong></TD>
                <TD>:</TD>
                <TD style=”width: 431px”><ASP:TEXTBOX ID=txtName RUNAT=server></ASP:TEXTBOX>
                    <asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server” ControlToValidate=”txtName”
                        ErrorMessage=”Enter Your Name”>*</asp:RequiredFieldValidator></TD>
            </TR>
            <TR>
                <TD>
                    <strong>Email Address</strong></TD>
                <TD>:</TD>
                <TD style=”width: 431px”><ASP:TEXTBOX ID=txtEmail RUNAT=server></ASP:TEXTBOX>
                    <asp:RequiredFieldValidator ID=”RequiredFieldValidator2″ runat=”server” ControlToValidate=”txtEmail”
                        Display=”Dynamic” ErrorMessage=”Enter Email”>*</asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID=”RegularExpressionValidator1″ runat=”server” ControlToValidate=”txtEmail”
                        ErrorMessage=”Enter Valid Email” ValidationExpression=”\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”>*</asp:RegularExpressionValidator></TD>
            </TR>
            <TR>
                <TD>
                    <strong>Subject </strong>
                </TD>
                <TD>:</TD>
                <TD style=”width: 431px”><ASP:TEXTBOX ID=txtSubject RUNAT=server></ASP:TEXTBOX>
                    <asp:RequiredFieldValidator ID=”RequiredFieldValidator3″ runat=”server” ControlToValidate=”txtSubject”
                        ErrorMessage=”Enter Subject”>*</asp:RequiredFieldValidator></TD>
            </TR>
            <TR>
                <TD VALIGN=top>
                    <strong>Body</strong></TD>
                <TD VALIGN=top>:</TD>
                <TD style=”width: 431px”><ASP:TEXTBOX ID=txtBody RUNAT=server TEXTMODE=multiLine ROWS=10 COLUMNS=50></ASP:TEXTBOX>
                    <asp:RequiredFieldValidator ID=”RequiredFieldValidator4″ runat=”server” ControlToValidate=”txtBody”
                        Display=”Dynamic” ErrorMessage=”Enter your Message”>*</asp:RequiredFieldValidator>
                    <asp:CustomValidator ID=”CustomValidator1″ runat=”server” ControlToValidate=”txtBody”
                        ErrorMessage=”Message not more than 20 characters” OnServerValidate=”CustomValidator1_ServerValidate”>*</asp:CustomValidator></TD>
            </TR>
             <TR>
                <TD VALIGN=top>
                    <strong>Verification Image</strong></TD>
                <TD VALIGN=top>:</TD>
                <TD style=”width: 431px”><IMG SRC=”CaptchaImage.aspx” /></TD>
            </TR>
            <TR>
                <TD VALIGN=top>
                    <strong>Please Enter the Number Above</strong></TD>
                <TD VALIGN=top>:</TD>
                <TD style=”width: 431px”><ASP:TEXTBOX ID=txtNumber RUNAT=server></ASP:TEXTBOX></TD>
            </TR>
             <TR>
                <TD COLSPAN=3><ASP:BUTTON ID=btnSubmit RUNAT=server TEXT=”Submit” ONCLICK=”btnSubmit_Click” /></TD>
            </TR>
        </TABLE>
        <br />
        <asp:ValidationSummary ID=”ValidationSummary1″ runat=”server” HeaderText=”Please Enter the following:”
            Height=”85px” Font-Bold=”True” />
    </FORM>
</BODY>
</HTML>

in code behind:

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

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

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Session["Number"].ToString().Trim() == txtNumber.Text)
        {
            try
            {
                // method to send email here

            }
            catch (Exception ex)
            {

            }
        }
        else
        {
            Response.Write(“Verification Email not match. Please re-enter”);
        }
    }

Hope it helps

Good Luck
    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        //args.IsValid = (args.Value.Length <= 20);

        if (txtBody.Text.Length > 20)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }
}

AJAX Slider Show with Dynamic Image URL

Filed under: AJAX, ASP.Net — Tags: , — yasserzaid @ 9:05 pm

Hi

try this example to use AJAX Slider Show to display Dynamic Image URL from database

where i save image name in my database and upload image in folder in my website root (Album folder)

Setp 1: Create database has Album table has the following fields:

Id -> PK , Idntity

Picture -> nvarchar(50)

Step2 : Create Webservice

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Collections.Generic;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

    public WebService ()
    {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }
    //— for slide show
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public  AjaxControlToolkit.Slide[] GetSlides()
    {
        //———-another way————

        //string strSQL = “SELECT * FROM Album”;
        //SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["School_SystemConnectionString"].ConnectionString);
        //conn.Open();

        //SqlCommand comm = new SqlCommand(strSQL, conn);
        //SqlDataAdapter da = new SqlDataAdapter(comm);
        //DataTable tblData = new DataTable();
        //da.Fill(tblData);
        ////conn.Close();

        //AjaxControlToolkit.Slide[] slides = new AjaxControlToolkit.Slide[tblData.Rows.Count];

        //for (int i = 0; i < tblData.Rows.Count; i++)
        //{

        //    DataRow dr = tblData.Rows[i];
        //    slides[i] = new AjaxControlToolkit.Slide(“Album/” + dr["Picture"].ToString(), dr["Description"].ToString(), “”);
        //}
        //return slides;

        //———–another way (work)——–

        string strSQL = “SELECT * FROM Album”;
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["School_SystemConnectionString"].ConnectionString);
        conn.Open();

        SqlCommand comm = new SqlCommand(strSQL, conn);
        SqlDataAdapter da = new SqlDataAdapter(comm);
        DataTable tblData = new DataTable();
        da.Fill(tblData);
        //conn.Close();

        AjaxControlToolkit.Slide[] slides = new AjaxControlToolkit.Slide[tblData.Rows.Count];
        int i = 0;
        foreach (DataRow row in tblData.Rows)
        {
            slides[i] = new AjaxControlToolkit.Slide(“Album/” + row["Picture"].ToString(), row["Description"].ToString(), “”);
            i++;
        }
        return slides;

    }    
}

step3 : Create Web Form

.aspx

 <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
        </asp:ScriptManager>
      
       <asp:Image ID=”imgShowImage” runat=”server”
                Height=”300″
                Style=”border: 1px solid black;width:auto”
                AlternateText=”" />
        <br />

        <asp:Label runat=”Server” ID=”imageLabel1″/><br /><br />
            <asp:Button runat=”Server” ID=”prevButton” Text=”Prev” Font-Size=”Larger” />
            <asp:Button runat=”Server” ID=”playButton” Text=”Play” Font-Size=”Larger” />
            <asp:Button runat=”Server” ID=”nextButton” Text=”Next” Font-Size=”Larger” />
           
            <cc1:SlideShowExtender ID=”slideshowextend1″ runat=”server”
                TargetControlID=”imgShowImage”
                SlideShowServiceMethod=”GetSlides”
                AutoPlay=”true”
                ImageDescriptionLabelID=”imageLabel1″
                NextButtonID=”nextButton”
                PlayButtonText=”Play”
                StopButtonText=”Stop”
                PreviousButtonID=”prevButton”
                PlayButtonID=”playButton”
                Loop=”true” PlayInterval=”1000″ SlideShowServicePath=”WebService.asmx” />

.aspx.cs

protected void Page_Load(object sender, EventArgs e)
    {

        string strSQL = “SELECT [Picture], [Id] FROM [Album]“;
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["School_SystemConnectionString"].ConnectionString);
        conn.Open();

        SqlCommand comm = new SqlCommand(strSQL, conn);
        SqlDataAdapter da = new SqlDataAdapter(comm);
        DataTable tblData = new DataTable();
        da.Fill(tblData);
        conn.Close();

        // set the initial image
        if (tblData.Rows.Count > 0)
        {
            imgShowImage.ImageUrl = “Album/” + tblData.Rows[0]["Picture"].ToString();
            //imageLabel1.Text = tblData.Rows[0]["Description"].ToString();
        }  
    }

Hope it helps…

Good Luck

Older Posts »

Blog at WordPress.com.