Tuesday, August 30, 2016

Upload and Save Image in ASP.NET

In this article I will explain how to upload and save an image and then retrieve that
image in ASP.NET.

For uploading FileUpload Control is used and for displaying the image there is an
Image Control.

Below is the code for that :

HTML Code (.aspx) :


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        &nbsp;<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
        <asp:Label ID="lblMessage" runat="server" Text="" Font-Bold="true" ForeColor="Green"></asp:Label><br />
        <br />
        <asp:Image ID="Image1" runat="server" Width="250px" Height="250px" />
    </div>
    </form>
</body>
</html>

C# Code (.aspx.cs) :


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class SaveImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            try
            {
                string filename = Path.GetFileName(FileUpload1.FileName);
                FileUpload1.SaveAs(Server.MapPath("~/images/") + filename);
                lblMessage.Text = "File has been uploaded successfully!";
                Image1.ImageUrl = Server.MapPath("~/images/") + filename;
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Uploading file failed : " + ex.Message;
            }
        }
    }
}

Output :
















If we want to validate with certain image types like jpg, jpeg, gif, png,etc. we can get the
extension of the file using the code :

Path.GetExtension(FileUpload1.FileName)

One thing to be noted is that there is restriction provided by .NET framework to the size
of the uploaded file which is termed as maxRequestLength. It actually specify the limit
of the input stream buffering threshold which is used to prevent denial of service attacks.
Default value of maxRequestLength is 4096 KB( 4MB).

In case if we want to upload bigger file, we can set the value of maxRequestLength
in web.config. 

For eg. if I want to set it to 15 MB, below is the code of web.config

<system.web>
        <httpRuntime maxRequestLength="15360" ></httpRuntime>
....
</system.web>

Monday, August 29, 2016

How to write to a Text File in ASP.NET

In this article I will explain how to write to a text file using two methods,
one using File class and the second one using StreamWriter class.

Using File Class :


This class has methods to write to a text file which are WriteAllText and
WriteAllLines and it has methods to append text to a file named AppendAllText
and AppendAllLines.

Below you can find the sample code :

C# Code :



using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

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

    }
    protected void btnWrite_Click(object sender, EventArgs e)
    {
        File.WriteAllText(@"d:\test.txt","Hello how are you?");
    }
}

WriteAllText method creates a text file in the specified path, writes the string
mentioned and then closes the file. If file already exists it will overwrite that file.

Another sample is :

        string[] arr = { "Think Good", "Do Good", "Speak Good" };
        File.WriteAllLines(@"d:\test.txt",arr);

WriteAllLines method creates a text file in the specified path, writes the specified 
strings of the array in separate lines and then closes the file. If file already exists it 
will overwrite that file.

WriteAllBytes method is also similar to the above method but it is used for writing
byte array.

Next is the example of code for appending text to an existing file.

File.AppendAllText(@"d:\test.txt","How do you do?");

AppendAllText method opens the file, append the specified string to that file and
then closes the file. If file doesn't exist, it will create a new one.

Next is the example of code for appending lines to an existing file.

  string[] lines = { "Think Good", "Speak Good" };
  File.AppendAllLines(@"d:\test.txt", lines);

AppendAllLines method opens the file, append the specified strings of the array in
separate lines and then closes the file. If file doesn't exist, it will create a new one.

This method exists from .NET framework 4.0.

Using StreamWriter Class :


StreamWriter  writes characters to a stream in a particular encoding. It has
WriteLine and Write methods for writing to a file.

WriteLine  method writes the specified string  followed by a line terminator to the
text stream

Write method just writes the specified string to the stream.

Below is the sample code :

C# Code :



using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

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

    }
    protected void btnStreamWrite_Click(object sender, EventArgs e)
    {
       using (StreamWriter sr = new StreamWriter(@"d:\test.txt"))
        {
            sr.WriteLine("Think Good, Do Good, Speak Good");
            sr.Write("Hai How are you?");
            sr.Write("Hello Hope you are fine.");
           
        }
    }
}

Output will be like this when you open the text file :

Think Good, Do Good, Speak Good
Hai How are you?Hello Hope you are fine.

You can notice that there is no line separator in second line between
two strings "Hai How are you?" and "Hello Hope you are fine."

StreamWriter is used with using statement in the above code
as using statement will ensure that Dispose method is called
which releases unmanaged resources.

Sunday, August 28, 2016

How to Read a Text File in ASP.NET

In this article I will explain with example how to read a text file.

There are two methods for reading a text file, one using File Class and the other
using StreamReader Class

Using File Class :


The namespace to be included for using File Class is System.IO.
There are two functions named ReadAllText and ReadAllLines of File Class.

ReadAllText opens the file, read all text of that file which is returned as a string 
and then it closes the file.

In case of ReadAllLines, it returns a string array of separate lines of the text file.
It also opens and closes the file by itself.

Below is the sample code :

C# Code :


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class ReadFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnRead_Click(object sender, EventArgs e)
    {
        string str = File.ReadAllText(@"d:\test.txt");
        Label1.Text = str;

        string[] arr = File.ReadAllLines(@"d:\test.txt");
        foreach (string line in arr)
        {
            if (!String.IsNullOrEmpty(Label2.Text))
                Label2.Text += "\t" + line;
            else
                Label2.Text =line;
        }
        
    }
}


Using StreamReader Class :


StreamReader Class is also contained in the namespace System.IO. StreamReader 
Class reads characters from a byte stream in a particular encoding.

Methods used in StreamReader class are ReadLine and ReadToEnd

With StreamReader, files can be read line by line and so it consumes less memory
compared to File.ReadAllLines. StreamReader is efficient in case of bigger files
but in other case, using File class is simple.

C# Code :


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

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

    }
   protected void btnStream_Click(object sender, EventArgs e)
   {
        // using is used as it take care of object disposal
        using (StreamReader sr = new StreamReader(@"d:\test.txt"))
        {
              // Reads line of characters from the current stream and returns as a string
              Label1.Text = sr.ReadLine();

        }
   }
}

In this case it will display the first line of the text file. In order to read all lines,
code is as following :

 protected void btnStream_Click(object sender, EventArgs e)
   {
        using (StreamReader sr = new StreamReader(@"d:\test.txt"))
        {
             string line;
             while ((line = sr.ReadLine()) != null)
            {
                if (!String.IsNullOrEmpty(Label1.Text))
                    Label1.Text += "\t" + line;
                else
                    Label1.Text = line;
            }

        }
   }

In the case if user wants to read till the end, the code is as following:

protected void btnStream_Click(object sender, EventArgs e)
 {
        using (StreamReader sr = new StreamReader(@"d:\test.txt"))
        {
             //  Reads the stream from the current position till the end and return as a string
             Label1.Text = sr.ReadToEnd();

        }
   }

Saturday, August 27, 2016

Refresh an UpdatePanel control at a Timed Interval using AJAX Timer

Using AJAX Timer, we can show real time data at a specific interval.Timer Control allows
to do postbacks at certain intervals.

In order to use AJAX controls , ScriptManager control is required to be added in the web page.

If the Timer is used along with UpdatePanel, user won't feel the postback.

AJAX Timer is used in scenarios of the real time uses without the user feeling the postback
of the page.

Suppose there is a requirement of displaying the latest data from the server on one side of a
page at a timed interval, we can use this method.

Let me show a very basic example of displaying system date. Suppose there is a Timer
control and a Label inside the UpdatePanel and Label displays the date with time on
Timer's Tick event.

HTML Code (.aspx) :


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="Updatepanel1" runat="server">
            <ContentTemplate>
                <asp:Timer ID="Timer1" runat="server" Interval="2000" OnTick="Timer1_Tick">
                </asp:Timer>
                <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

C# Code (.aspx.cs ) :


 protected void Timer1_Tick(object sender, EventArgs e)
    {
        Label1.Text = "Current time is : " +DateTime.Now.ToLongTimeString();
    }

AJAX Timer can be used for updating content of one or more UpdatePanel.
It can be used for updating the content of control inside another UpdatePanel.
In next example I will show this case. Suppose I want to display latest data
at specified interval in a GridView and the Timer is outside GridView's
UpdatePanel, below is the code for it :

HTML Code (.aspx) :


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:Timer ID="Timer1" runat="server" Interval="2000" OnTick="Timer1_Tick">
                </asp:Timer>
        <asp:UpdatePanel ID="Updatepanel1" runat="server">
            <ContentTemplate>
              <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"                    BackColor="White"  BorderColor="#E7E7FF" BorderStyle="None"
BorderWidth="1px" CellPadding="3" GridLines="Horizontal">
                    <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
                    <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
                    <Columns>
                        <asp:BoundField DataField="AGN_NAME" HeaderText="Name" SortExpression="AGN_NAME" />
                        <asp:BoundField DataField="AGN_TEL" HeaderText="Telephone" SortExpression="AGN_TEL" />
                        <asp:BoundField DataField="AGN_ID" HeaderText="User ID" SortExpression="AGN_ID" />
                    </Columns>
                    <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C"
 HorizontalAlign="Right" />
                    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True"
 ForeColor="#F7F7F7" />
                    <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
                    <AlternatingRowStyle BackColor="#F7F7F7" />
                </asp:GridView>
            </ContentTemplate>
           <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
            </Triggers>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>


C# Code (.aspx.cs) :



 protected void Timer1_Tick(object sender, EventArgs e)
 {
         DataSet ds = new DataSet();
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

        using (SqlConnection dbConnection = new SqlConnection(connectionString))
        using (SqlCommand dbCommand = new SqlCommand())
        {
            dbCommand.CommandText = "select * from Agents";
            dbCommand.Connection = dbConnection;
            dbConnection.Open();

            SqlDataAdapter da = new SqlDataAdapter(dbCommand);
            da.Fill(ds);

        }
        GridView1.DataSource = ds;
        GridView1.DataBind();
 }

Even though partial updates are not as heavy as real postbacks, as it is contacting the
server on Timer's tick, based on our requirement it is better to use high time intervals
there by reducing the frequency.

Friday, August 26, 2016

Sending Email in ASP.NET

For sending email in ASP.NET , we have to use namespace, System.Net.Mail
which contains its main classes, MailMessage and SmtpClient.

As mail is sent to an SMTP (Simple Mail Transfer Protocol) Server which
forwards to the recipient server, we require an accessible SMTP Server.

Suppose I am sending email on a Button's Click in a web form,
code for this is as following :

C# Code (.aspx.cs) :


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;

public partial class TestEmail : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.To.Add("To Address");
            mailMessage.From = new MailAddress("From Address");
            mailMessage.Subject = "Test e-mail from the website";
            mailMessage.Body = "Hi, this is a test e-mail!";
            SmtpClient smtpClient = new SmtpClient("smtp.domain.com");
            smtpClient.Send(mailMessage);
            lblMessage.Text="E-mail sent!";
        }
        catch (Exception ex)
        {
            lblMessage.Text = "E-mail sending failed - error : " + ex.Message;
        }

    }
}

We can set various properties of the MailMessage class.
Suppose we want to send as an HTML format with HTML
tags and styles, we can concatenate strings and pass to the Body
and set IsBodyHtml to true.

If we want to set the priority, we can use Priority property.
For eg. if we want to send a high priority email, add the following code  :

mailMessage.Priority = MailPriority.High;

If we want to send attachment, we can create instance of Attachment class
inside System.Net.Mail and implement as :

Attachment attach = new Attachment(Server.MapPath(strFileName));
mailMessage.Attachments.Add(attach);

Normally we can send mail without providing credentials but some SMTP servers
require credentials for authenticating.

We can set SMTP details in web.config file as :

<configuration>
  <system.net>
    <mailSettings>
      <smtp>
        <network 
             host="Host Name" 
             port="Port Number"
             userName="username"
             password="password" />
      </smtp>
    </mailSettings>
  </system.net>
  <system.web>
    ...
  </system.web>
</configuration>

In  this case of using web.config, no need to specify SmtpClient Details
in code. It will take automatically from web.config.

Server side implementation code is as following :

  SmtpClient smtpClient = new SmtpClient();
  smtpClient.Send(mailMessage);

Thursday, August 25, 2016

Using RadioButton Control in ASP.NET

RadioButton is a button control with Text that can be selected by the user.

In the case if user has to select one value from a group of values, we can add
more than one RadioButton to the webpage and provide the same GroupName.
GroupName is the property used for grouping values of RadioButtons.
In this case if a user select any one of the values, automatically it will clear
selection from the other values, if selected.

Programmatically we can know whether the RadioButton is selected by using
Checked property.

For specifying styles and other attributes there are many properties for a RadioButton
like any other web control. Also in an input form it can be set to validation controls for
validation.

If in case any logic has to be done on server side on its selection, we can set AutoPostBack
property to true and write the logic inside onCheckedChanged event.

Let me explain with an example of a webpage with two RadioButtons for
selecting the gender.

HTML Code (.aspx) :


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Gender : "></asp:Label>
        <asp:RadioButton ID="RadioButton1" runat="server" Text="Male" GroupName="gender"
            AutoPostBack="True" OnCheckedChanged="RadioButton_CheckedChanged" />
        <asp:RadioButton ID="RadioButton2" runat="server" Text="Female" GroupName="gender"
            AutoPostBack="True" OnCheckedChanged="RadioButton_CheckedChanged" />
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="" Font-Bold="true" ForeColor="DarkGreen"></asp:Label>
    </div>
    </form>
</body>
</html>

C# Code (.aspx.cs) :


 protected void RadioButton_CheckedChanged(object sender, EventArgs e)
 {
        if (RadioButton1.Checked)
            Label2.Text = "You selected : " + RadioButton1.Text;
        else
            Label2.Text = "You selected : " + RadioButton2.Text;
 }

Output :



Wednesday, August 24, 2016

SQL Group By

SQL Group By clause is used along with select statement to group identical
data.

Group by is used typically with aggregate functions like count,max,avg,sum,min, etc.
In this case it will return one row for each group.

It can group more than one column.

In a query using Group by, Column names other than that in aggregate function
should present in Group by clause.

In a Select query it is used after the where condition and before the Order by Clause.

SQL Having Clause requires Group by to be present in the query.

Let me explain some examples of various Group By statements of  SQL.

General syntax is : 

SELECT column-names FROM table-name WHERE condition
GROUP BY column-names

Suppose there are two tables named Department and Employee with data as follows:

Department :









Employee :






An example of Group by with where condition is :

SELECT Dept_code,name FROM Employee WHERE Salary>4000 
GROUP BY Dept_code,Name

Output :







Syntax with Aggregate function :

SELECT column-name1, fun(column_name2) FROM table-name 
GROUP BY column-name1

An example for this is :

SELECT Dept_code,count(name) AS count FROM Employee
GROUP BY Dept_Code

Output :









Another example is :

SELECT Dept_Code, SUM(SALARY) as 'Total Salary' FROM Employee
GROUP BY Dept_Code

Output :









Another example with Join :

SELECT Dept_name,name FROM Employee E INNER JOIN Department D 
ON E.Dept_code=D.Dept_code
WHERE Salary>2000 GROUP BY Dept_name,name

Output :












Syntax with Order By Clause :

SELECT column-names FROM table-name WHERE condition
GROUP BY column-names
ORDER BY column-names

An example is :

SELECT Dept_code,name FROM Employee WHERE Salary>4000 
GROUP BY Dept_code,name
ORDER BY name

Output :








Having Clause :

Having clause is used for filtering records with summarized Group By results.

The difference between Having and Where condition is that Where condition
filters by applying condition for each record where as Having applies
condition for Aggregate function.

Having Clause in a query must have a Group By clause.

Syntax for Having Clause is :


SELECT column-names FROM table-name WHERE condition
GROUP BY column-names
HAVING condition.

An example is :

SELECT Dept_code,count(name) AS count FROM Employee 
GROUP BY Dept_code
HAVING COUNT(name)>1 

Output  :









Syntax for Having Clause with Order By :

SELECT column-names FROM table-name WHERE condition
GROUP BY column-names
HAVING condition
ORDER BY column-names

An example is :

SELECT Dept_code,count(name) AS count FROM Employee 
GROUP BY Dept_code
HAVING COUNT(name)>1 ORDER BY Dept_code desc

Output  :



Tuesday, August 23, 2016

Common String functions and manipulations in C#

In this article I will explain some commonly used String functions
in C#. Even though there are many, here I will explain only the most
commonly used ones.

(1) string.IsNullOrEmpty() :

This function specifies whether the value of the string is null or empty.

For eg.

string str = "Praise the Lord";

string.IsNullOrEmpty(str);

Will return false in this case.

(2) Length :

This will return the number of characters in the string
For eg.
string str = "Praise the Lord";
int i=str.Length;

Here value of "i" will be 15.


(3) Contains :

This function determines whether the string contains the specified element.
For eg.
string str = "Praise the Lord";
bool val = str.Contains('j'); // characters can be specified inside single quotes

bool val2=str.Contains("the");  // string can be specified inside double quotes

Here value of  val will be false and that of val2 will be true.

(4) EndsWith :

This function determines whether the string ends with the specified string element.
For eg.
string str = "Praise the Lord";
bool val=str.EndsWith("Lord");

Here the value of val will be true.

(5) Equals :

This function determines whether the string is equal to the specified string element.
For eg.
string str = "Praise the Lord";
string str2="abc";
bool val=str.Equals(str2);

Here the value of val will be false.

(6) IndexOf :

This function returns the integer value that represents the index of the first occurrence 
of the specified string or character element.
For eg.
string str = "Praise the Lord";
int val = str.IndexOf('t');  // characters can be specified inside single quotes
int val2 = str.IndexOf("the"); // string can be specified inside double quotes

Here the values of val and val2 will be 7.

(7) Insert :

This will insert the specified string at the specified index position of the string.
For eg.
string str = "Praise the Lord";
string val=str.Insert(15, " Jesus");

Here the value of val will be "Praise the Lord Jesus".

(8) LastIndexOf :

This will return an integer value of the index of the last occurrence of the specified
element in the string.
For eg.
string str = "Praise the Lord";
int val = str.LastIndexOf('e');
int val2 = str.LastIndexOf("the");


Here the values of val  will be 9 and that of val2 will be 7.

(9) Remove :

This function deletes the characters from the string. If the parameter for length 
is not specified it will delete all the characters starting from the index specified.
If length is specified it will delete that number of characters from the index specified.
For eg.
string str = "abcdefg";
string val = str.Remove(3);
string val2 = str.Remove(3,2);

Here the output of val will be "abc" and that of val2 will be "abcfg".

(10) Replace :

This function replaces all the occurrences of the specified string or character with the
new value.
For eg.
string str = "abcdefg";
string val = str2.Replace("abc","*");
string val2 = str2.Replace('a', '#');

In this case output of val is "*defg" and that of val2 is "#bcdefg"

(11) Split :

This function returns a string array that contains the substrings of the string
delimited by the character element specified.
For eg.
string str = "abc,def,ghi";
string[] arr = str.Split(',');

Here it will return an array with elements abc,def and ghi.

(12) StartsWith :

This function determines whether the string starts with the specified string value.
For eg.
string str = "Praise the Lord";
bool val=str.StartsWith("Praise");

Here the value of val will be true.

(13) Substring :

This function retrieves the substring starting from the specified index of the string.
If length is specified, it will retrieve substring of the specified length from the
specified index of the string.
For eg.
string str = "Praise the Lord";
string sub1 = str.Substring(11);
string sub2 = str.Substring(11,2);

Here value of sub1 is "Lord" and that of sub2 is "Lo".

(14) ToLower :

This function returns a copy of the string after converting to Lower Case.
For eg.
string str = "Praise the Lord";
string str2 = str.ToLower();

Here value of str2 will be "praise the lord".

(14) ToUpper :

This function returns a copy of the string after converting to UpperCase.
For eg.
string str = "Praise the Lord";
string str2 = str.ToUpper();

Here value of str2 will be "PRAISE THE LORD".

(15) Trim :

This function removes all leading and trailing white space characters from the string
For eg.
string str = " ab c ";
string str2 = str.Trim();

Here output of str2 will be "ab c".

(16) TrimStart :

This function removes all leading white space characters from the string.
It can also be used for removing all leading occurrences of a set of characters 
specified in a character array element.

For eg.
string str = " ab c ";
string str2 = str.TrimStart();

Here output of str2 will be "ab c ".

(17) TrimEnd :

This function removes all trailing white space characters from the string.
It can also be used for removing all trailing occurrences of a set of characters 
specified in a character array element.

For eg.
string str = " ab c ";
string str2 = str.TrimEnd();

Here output of str2 will be " ab c".


Monday, August 22, 2016

Using Conditional Operator in GridView

In this article I will show how to use Conditional Operator in a GridView.

Conditional Operator ( ? : ) is a ternary operator which takes three operands.
Its syntax is
condition ? first expression : second expression

It works in a way that if the condition is true, it will evaluate the first expression and
if it is false, second expression is evaluated.

Consider an example in which a GridView is binded with User data and
it has a template field which displays User Type based on the integer value
stored in the database.

HTML Code (.aspx) :


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" 
BorderColor
="#E7E7FF"
BorderStyle
="None"
BorderWidth
="1px"
CellPadding
="3"
GridLines
="Horizontal">
            <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
            <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
            <Columns>
                <asp:BoundField DataField="AGN_NAME" HeaderText="Name" SortExpression="AGN_NAME" />
                <asp:BoundField DataField="AGN_TEL" HeaderText="Telephone" SortExpression="AGN_TEL" />
                <asp:BoundField DataField="AGN_ID" HeaderText="User ID" SortExpression="AGN_ID" />
                <asp:TemplateField HeaderText="User Type" SortExpression="AGN_TYPE">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%#(DataBinder.Eval(Container, "DataItem.AGN_TYPE").ToString()=="1") ? "Active":"In active"%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
            <AlternatingRowStyle BackColor="#F7F7F7" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Here you can see in the template field if  the value of 
DataBinder.Eval(Container, "DataItem.AGN_TYPE") is 1, then output
will be displayed as "Active" else "In active".

C# Code (.aspx.cs) :


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class grid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            getData();
    }
    protected void getData()
    {
        DataSet ds = new DataSet();
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

        using (SqlConnection dbConnection = new SqlConnection(connectionString))
        using (SqlCommand dbCommand = new SqlCommand())
        {
            dbCommand.CommandText = "select * from Agents";
            dbCommand.Connection = dbConnection;
            dbConnection.Open();

            SqlDataAdapter da = new SqlDataAdapter(dbCommand);
            da.Fill(ds);

        }
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

Output :




Sunday, August 21, 2016

Using Javascript window.open method

In this article I will show how to use window.open() method of Javascript
to open a new window from a web page.

Let us consider you want to open a window on click of an anchor tag as
following :

HTML Code (.aspx) :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function openWindow() {
            window.open("http://www.google.com", "myWindow", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
        }
        
    </script>
</head>
<body>
    <form id="form1" runat="server">
      <div>
        <a href="#" onclick="openWindow();">Pop Up</a
      </div>
    </form>
</body>
</html>

Normal syntax is window.open(URL, WindowName, Window Features).
Actually following four parameters are allowed :

(1) URL :
This specifies the URL of the page to be opened. 

If the value is blank as below, it will open a blank window

 window.open("""myWindow""toolbar=yes,scrollbars=yes,resizable=yes,top=500,
left=500,width=400,height=400");

If the web page is in the same project only file name is required and no need to
specify the full URL as :

window.open("Default.aspx""myWindow""toolbar=yes,scrollbars=yes,resizable=yes,
top=500,left=500,width=400,height=400");

(2) Window Name :
This specifies the window name or target attributes which are :

_blank :
This is the default value if nothing is specified. It will open the URL
into a new window.
_parent :
In this case URL is loaded into the parent frame.
_self :
In this case URL replaces the current page.
_top :
In this case URL replaces any framesets.

For eg :

  window.open("http://www.google.com""_parent""toolbar=yes,scrollbars=yes,
resizable=yes,top=500,left=500,width=400,height=400");

This will be opened in the parent window.

(3) Window Features :
This specifies various features of the pop up window separated by comma
and without white spaces. 

We can specify following features with yes/no value :
fullscreen, channelmode, directories, menubar, location, resizable, scrollbars,
status, titlebar, toolbar.

And can specify pixel values for the following :
top, width, height, left

(3) replace :
This specifies whether in history a new entry is required for the URL or  replaces
the current entry in the history

If it is true, URL replaces the current entry in the history and if it is
false, a new entry is created in the history.

Note : All parameters are optional.

In HTML code, we can see that href value of the anchor tag is specified as "#".
We can also specify with void value as :

 <a href="javascript:void(0);" onclick="openWindow();">Pop Up</a