Daily Archives: August 22, 2012

ListView in VB.NET

Introduction:-

Here we are going to see about the ListView control in Vb.Net…   List views displays a collection of items that can be displayed using one of five different views, such as,

1) LargeIcon

2) Details

3)SmallIcon

4)List

5)Tile

create a class like below…

Public Class ListViewData
    Public Sub FillListView(ByRef MyListView As ListView, _ ByRef myData As SqlDataReader)
        Dim lvwColumn As ColumnHeader
        Dim itmListItem As ListViewItem

        Dim strTest As String
        Dim shtCntr As Short

        MyListView.Clear()
        For shtCntr = 0 To myData.FieldCount() – 1
            lvwColumn = New ColumnHeader()
            lvwColumn.Text = myData.GetName(shtCntr)
            MyListView.Columns.Add(lvwColumn)
        Next
        Do While myData.Read
            itmListItem = New ListViewItem()
            strTest = IIf(myData.IsDBNull(0), “”, myData.GetString(0))

‘ Here GetString or GetInt32 will varies regarding your

first Column you are selecting from Database
            itmListItem.Text = strTest

            For shtCntr = 1 To myData.FieldCount() – 1
                If myData.IsDBNull(shtCntr) Then
                    itmListItem.SubItems.Add(“”)
                Else
                    itmListItem.SubItems.Add(myData(shtCntr))
                End If
            Next shtCntr

            MyListView.Items.Add(itmListItem)
        Loop
    End Sub
End Class

and then in Button Click we want to code this

 Private Sub Submit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Submit.Click

Dim myCon As SqlConnection
Dim sqlCmd As SqlCommand = New SqlCommand(“SELECT * FROM EmployeeDetails“)
Dim myData As SqlDataReader
‘Dim itmListItem As ListViewItem
Dim lvhHelper As ListViewData = New ListViewData()
myCon = New SqlConnection(“Data Source=HARIHARAN;Initial Catalog=TestingForVB;Integrated Security=True“)
Try
myCon.Open()
sqlCmd.Connection = myCon
myData = sqlCmd.ExecuteReader
lvhHelper.FillListView(ListView1, myData)
myCon.Close()
Catch eSql As System.Data.SqlClient.SqlException
MessageBox.Show(eSql.ToString)
End Try
   End Sub

The Output is :-

Leave a comment

Filed under .Net

PHP Data Object

 PHP Data Object is a Database Connection Abstraction Library for PHP 5.

PDO Introduction

  • a Lightweight DBMS connection abstract library (data access abstraction library)
  • PDO can use exceptions to handle errors, which means anything you do with PDO should be wrapped in a try/catch block.
  • PDO is a database access layer providing a uniform method of access to multiple databases.
  • PHP5 is written in compiled language like C & C++

PDO - db abstraction layer

Database Support

Activation PHP Data Objects Extension

To use PDO, check whether PDO extension exist or not. Try to open your php extension folder. For example, in my computer, the directory: app/php5/ext.

PDO library at PHP extension folder

Then, open your php.ini. Usually within c:/windows (depend on your php installation). Uncomment at line extension=php_pdo.dll, extension=php_pdo_mysql.dll. If still not exist, write them.

PDO library at PHP extension folder

Restart your apache. You can restart from services. If, you use windows XP, you can access from start > control panel > Performance and Maintenance > Administrative Tools > Services. Find apache, then click restart.

Restart apache

Now, we test to connect to database. We use mysql server. Before test, please create a database named “test”. Then create table “books” with query like this:

CREATE TABLE `books` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(150) NOT NULL,
  `author` varchar(150) NOT NULL,
  `description` varchar(255) NOT NULL,
  `on_sale` tinyint(1) NOT NULL,
  PRIMARY KEY  (`id`)
);

Following query for sample data:

INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (1, 'PHP AJAX', 'Andreas', 'This is good book for learning AJAX', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (2, 'PHP Eclipse ', 'George', 'Nice book', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (3, 'PHP Prado', 'Junyian', '-', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (4, 'PHP Zend Framework', 'Ozulian', 'great', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (5, 'PHP Web Services', 'Bobi', '', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (6, 'PHP API', 'Hugo', '', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (7, 'PHP SEO', 'Monteo', '', 1);

Now, this is sample connection to mysql database:


<?php
$host 	= "localhost";
$db	= "test";
$user	= "root";
$pass	= "admin";

$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);

$sql = "SELECT * FROM books";
$q	 = $conn->query($sql) or die("failed!");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
  echo $r['title'];
}

?>

Prepared Statement

PHP Extension for MySQL and SQLite don’t offer this functionality. Ok, I will show a sample. I believe, from that sample you will understand what is prepare statement.

A prepared statement is a precompiled SQL statement that can be executed multiple times by sending just the data to the server.

It has the added advantage of automatically making the data used in the placeholders safe from SQL injection attacks.

You use a prepared statement by including placeholders in your SQL.

<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

$title = 'PHP AJAX';

// query
$sql = "SELECT * FROM books WHERE title = ?";
$q = $conn->prepare($sql);
$q->execute(array($title));

$q->setFetchMode(PDO::FETCH_BOTH);

// fetch
while($r = $q->fetch()){
  print_r($r);
}

?>
in this simple example, query depends on a variabel (we write with ?).


$sql = "SELECT * FROM books WHERE title = ?";

Now, we manipulate this query to create the prepared statement and execute it:

$q = $conn->prepare($sql);
$q->execute(array($title))

Another sample:

$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
 

Positional and Named Placeholders

Positional Placeholders

$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));

The query above used question marks to designate the position of values in the prepared statement. These question marks are called positional placeholders.

We must take care of proper order of the elements in the array that we are passing to the PDOStatement::execute() method.

Named Placeholders

$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like :title AND author like :author ";
$q = $conn->prepare($sql);
$q->execute(array(':author'=>$author,
                  ':title'=>$title));

This use descriptive names preceded by a colon, instead of question marks. We don't care about position/order of value. That's why it called named placeholders.

 

Insert and Update Statement Use Prepared Statement

Example for Insert

<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// new data
$title = 'PHP Security';
$author = 'Jack Hijack';

// query
$sql = "INSERT INTO books (title,author) VALUES (:title,:author)";
$q = $conn->prepare($sql);
$q->execute(array(':author'=>$author,
                  ':title'=>$title));

?>

Example for Update

<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// new data
$title = 'PHP Pattern';
$author = 'Imanda';
$id = 3;
// query
$sql = "UPDATE books 
        SET title=?, author=?
		WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($title,$author,$id));

?>

Selecting Data

Fetch data into arrays or objects

  • PDO::FETCH_ASSOC: returns an array indexed by column name
  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and number
  • PDO::FETCH_BOUND: Assigns the values of your columns to the variables set with the ->bindColumn() method
  • PDO::FETCH_CLASS: Assigns the values of your columns to properties of the named class. It will create the properties if matching properties do not exist
  • PDO::FETCH_INTO: Updates an existing instance of the named class
  • PDO::FETCH_LAZY: Combines PDO::FETCH_BOTH/PDO::FETCH_OBJ, creating the object variable names as they are used
  • PDO::FETCH_NUM: returns an array indexed by column number
  • PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names

I think this post most helpful one for your PDO !!!

All the best!!!


Leave a comment

Filed under php

Whether the Email Existing or Not using Asp.Net

Introduction:-

                                           Everyone are looking for Exact Validation in the Web Pages.  Exactly they are need to check the Email by using the Regular Expression for validations… But here i have an another Idea…  Here we are checking the given Mail Id is Valid or Not…….

Here the Code is Given, in the  Default.aspx page we want to do like below

Default.aspx:-

<html xmlns=”http://www.w3.org/1999/xhtml&#8221;>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>

Enter Email Address :
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
&nbsp;

<asp:Button ID=”btnCheck” runat=”server” onclick=”btnCheck_Click”
            Text=”Check ” />
</div>
</form>
</body>
</html>

 

Then we want to consider the Code behind page,

Default.aspx.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Sockets;
using System.IO;
using System.Text;

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

}
protected void btnCheck_Click(object sender, EventArgs e)
{
TcpClient tClient = new TcpClient(“gmail-smtp-in.l.google.com”, 25);
string CRLF = “\r\n”;
byte[] dataBuffer;
string ResponseString;

NetworkStream netStream = tClient.GetStream();
StreamReader reader = new StreamReader(netStream);

ResponseString = reader.ReadLine();

/* Perform HELO to SMTP Server and get Response */
dataBuffer = BytesFromString(“HELO KirtanHere” + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();

dataBuffer = BytesFromString(“MAIL FROM:<yourmail@gmail.com>” + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();

/* Read Response of the RCPT TO Message to know from google if it exist or not */
dataBuffer = BytesFromString(“RCPT TO:<“+TextBox1.Text.Trim()+”>”+CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);

ResponseString = reader.ReadLine();
if (GetResponseCode(ResponseString) == 550)
{
  Response.Write(“Mai Address Does not Exist !<br/><br/>”);
            Response.Write(“<B><font color=’red’>Original Error from Smtp Server :</font></b>”+ResponseString);

}

/* QUITE CONNECTION */
dataBuffer = BytesFromString(“QUITE” + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
tClient.Close();

}
private byte[] BytesFromString(string str)
{
return Encoding.ASCII.GetBytes(str);
}
private int GetResponseCode(string ResponseString)
{
return int.Parse(ResponseString.Substring(0, 3));
}
}

 

by this way we can validate the Email whether that are Existing in Gmail or Not……….
Note: This can only for validate the Gmail Id

 

 

Leave a comment

Filed under .Net

Basic String Operation in PHP

Use this coding to understand basic string operation.

<?php
$x=1;
switch($x)
{
case 1:
echo “<h2>StripSlashes</h2>”;
$str=”Student’s listen here”;
echo “Using AddSlashes:<font color=blue>”.addslashes($str).”</font><br>”;
echo “Using StripSlashes:<font color=blue>”.stripslashes($str).”</font>”;
break;

case 2:
echo “<h2>StripCSlashes</h2>”;
$str=”Students listen here”;
echo “Using AddCSlashes:<font color=blue>”.addcslashes($str,’a..z’).”</font><br>”;
echo “Using StripCSlashes:<font color=blue>”.stripcslashes($str).”</font>”;
break;

case 3:
echo “<h2>Strnatcasecmp</h2>”;
echo strnatcasecmp(‘HELLP’,’hellp’).”<br>”;
break;
case 4:
echo “<h2>Strnatcmp</h2>”;
echo strnatcmp(‘HELLP’,’hellp’);
break;
case 5:
echo “<h2>Strip_tags</h2>”;
echo strip_tags(“<b><i>vijay</i></b>”,'<b>’);
break;
case 6:
echo “<h2>Strpbrk</h2>”;
echo strpbrk(‘hello da’, ‘ea’);
break;
case 7:
echo “<h2>Str_rot13</h2>”;
echo str_rot13(‘a’);
break;
case 8:
echo “<h2>Convert_Uuencode</h2>”;
$u= convert_uuencode(“abc”);
echo “Encoded: “.$u;
echo “<h2>Convert_Uudecode</h2>”;
echo “decode: “. convert_uudecode($u);
break;
case 9:
echo “<h2>Metaphone</h2>”;
echo metaphone(‘world’);
break;
case 10:
echo “<h2>Number_format</h2>”;
echo number_format(10000000,2,”,”,”.”);
break;
case 11:
echo “<h2>Parse_str</h2>”;
parse_str(‘a=10&v=name’,$arr);
print_r($arr);
break;
case 12:
echo “<h2>Sha1</h2>”;
echo sha1(‘vijay’);
$en= sha1_file(‘new.txt’,true);
file_put_contents(‘new.txt’, $en);
break;
case 13:
echo “<h2>bin2hex</h2>”;
$bn= bin2hex(‘vijay’);
echo $bn;
echo pack(‘H*’,$bn);
default:
echo “<h2>Give range b/w 1 to 13</h2>”;
}
?>

Leave a comment

Filed under php

Basic File Operations in PHP

Use this coding to understand basic file operation

<?php
$x=1;
switch($x)
{
case 1:
$file=’localhost/new.txt’;
//echo “<h2>Base name:</h2>”.basename($file);
echo “<h2>Base name:</h2>”.basename($file,’.txt’);
echo “<h2>Path information:</h2>”;
print_r(pathinfo($file));
//print_r(pathinfo($file),PATHINFO_FILENAME);
echo “<h2>Absolute Path:</h2>”.realpath(‘new.txt’);
echo “<h2>Directory Name:</h2>”.dirname($file);
break;

case 2://mode permissions

$file=’new.txt’;
chmod($file, 0700);
break;

case 3://clear cache
$f=’new.txt’;
$f1=fopen($f,’a+’);
echo “<h2>File size</h2>”.filesize($f);
ftruncate($f1,500);
//clearstatcache();
echo “<h2>File size</h2>”.filesize($f);
break;

case 4://copy file info to another
copy(‘new.txt’, ‘new1.txt’);
echo “<h2>data copied</h2>”;
break;
case 5:// To Know Disk spaces
echo “<h2>Total space in c directory:</h2>”. disk_total_space(‘c:’);
echo “<h2>Free space in c directory:</h2>”. disk_free_space(‘c:’);
break;
case 6://Match Function
echo “<h2>Using Match Function</h2>”;
$file=”new1.txt”;
if(fnmatch(‘new*’, $file))
{
echo “Pattern Matched”;
}
else
{
echo “Pattern Not Mached”;
}
break;
case 7://Pass thru function
echo “<h2>Pass Through Function</h2>”;

$file=fopen(‘new1.txt’,’r’);

fgets($file);
//rewind($file);//rewind goes beginning of file
echo fpassthru($file);
fclose($file);
echo “<h2>Read File</h2>”;
echo “<br>”;
echo readfile(‘new.txt’);
break;

case 8:
$file=’html.html’;
$f1=fopen($file,’r’);
echo fgetss($f1,100,'<b>’);
break;
case 9:
print_r(glob(“*.txt”));
break;
case 10:
print_r(parse_ini_file(“test.ini”,true));
break;
case 11:
echo tempnam(‘http://localhost/File&#8217;,’TMPO’);
break;
case 12:
$temp = tmpfile();

fwrite($temp, “Testing, testing.”);
//Rewind to the start of file
rewind($temp);
//Read 1k from file
echo fread($temp,1024);

//This removes the file
fclose($temp);
break;
}

?>

2 Comments

Filed under php

GridView Controls in Asp.Net

Introduction:-

I have one gridview I need to write code to insert data into gridview after that I need to edit that gridview data and update it and if I want to delete the record in grdview we need to delete record simply by click on delete button of particular row to achieve these functionalities I have used some of gridview events those are

  • Onrowcancelingedit
  • Onrowediting
  • Onrowupdating
  • Onrowcancelingedit
  • Onrowdeleting

Create the Database in SQL SERVER Like Below:-

// Create a Example Table and the Snapshot will be given below

Create Table Grid

(

ID int IDENTITY,

Name varchar(20),

Designation varchar(30)

)

insert into Grid values(‘Santhosh’,’Manager’)
insert into Grid values(‘Prakash’,’Developer’)
insert into Grid values(‘Chitra’,’Associate Manager’)
insert into Grid values(‘Dinesh’,’Asst Manager’)
insert into Grid values(‘Kavitha’,’General Manager’)

Default.aspx:-

<head id=”Head1″ runat=”server”>
<title>Insert,Update,Delete using GridView in Asp.net</title>
<style type=”text/css”>
.Gridview
{
font-family: Verdana;
font-size: 10pt;
font-weight: normal;
color: black;
}
</style>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ DataKeyNames=”Name” runat=”server” AutoGenerateColumns=”false” CssClass=”Gridview” HeaderStyle-BackColor=”#61A6F8″ ShowFooter=”true” HeaderStyle-Font-Bold=”true” HeaderStyle-ForeColor=”White” OnRowCancelingEdit=”GridView1_RowCancelingEdit” OnRowDeleting=”GridView1_RowDeleting” OnRowEditing=”GridView1_RowEditing” OnRowUpdating=”GridView1_RowUpdating” OnRowCommand=”GridView1_RowCommand”>
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<%–Image Button for Update button–%>
<asp:ImageButton ID=”imgbtnUpdate” CommandName=”Update” runat=”server” ImageUrl=”~/Images/update.jpg” ToolTip=”Update” Height=”20px” Width=”20px” />
<%–Image Button for Cancelbutton–%>
<asp:ImageButton ID=”imgbtnCancel” runat=”server” CommandName=”Cancel” ImageUrl=”~/Images/Cancel.jpg” ToolTip=”Cancel” Height=”20px” Width=”20px” />
</EditItemTemplate>
<ItemTemplate>
<%–Image Button for Edit button–%>
<asp:ImageButton ID=”imgbtnEdit” CommandName=”Edit” runat=”server” ImageUrl=”~/Images/Edit.jpg” ToolTip=”Edit” Height=”20px” Width=”20px” />
<%–Image Button for Delete button–%>
<asp:ImageButton ID=”imgbtnDelete” CommandName=”Delete” Text=”Delete” runat=”server”
ImageUrl=”~/Images/delete.jpg” ToolTip=”Delete” Height=”20px” Width=”20px” />
</ItemTemplate>
<FooterTemplate>
<%–Image Button for AddNewItem button–%>
<asp:ImageButton ID=”imgbtnAdd” runat=”server” ImageUrl=”~/Images/AddNewitem.jpg”
CommandName=”AddNew” Width=”30px” Height=”30px” ToolTip=”Add new User” ValidationGroup=”validaiton” />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Name”>
<EditItemTemplate>
<asp:Label ID=”lbleditusr” runat=”server” Text='<%#Eval(“Name”) %>’ />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID=”lblitemUsr” runat=”server” Text='<%#Eval(“Name”) %>’ />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtftrusrname” runat=”server” />
<asp:RequiredFieldValidator ID=”rfvusername” runat=”server” ControlToValidate=”txtftrusrname” Text=”*” ValidationGroup=”validaiton” />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Designation”>
<EditItemTemplate>
<asp:TextBox ID=”txtDesg” runat=”server” Text='<%#Eval(“Designation”) %>’ />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID=”lblDesg” runat=”server” Text='<%#Eval(“Designation”) %>’ />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtftrDesignation” runat=”server” />
<asp:RequiredFieldValidator ID=”rfvdesignation” runat=”server” ControlToValidate=”txtftrDesignation”
Text=”*” ValidationGroup=”validaiton” />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No records Found…………
</EmptyDataTemplate>
</asp:GridView>
</div>
<div>
<asp:Label ID=”lblresult” runat=”server”></asp:Label>
</div>
</form>
</body>
</html>

Default.aspx.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace GridView
{
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(“Data Source=HARIHARAN;Initial Catalog=TestingForums;Integrated Security=True”);

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
// Here We are Binding the Employee Details into the Gridview

protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand(“Select Name,Designation from Grid”, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = “No Records Found”;
}
}
// OnrowEditing Will be Raised Here for GridView

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
// Onrowupdating Event Will be Raised Here for GridView to update The Database


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string username = GridView1.DataKeys[e.RowIndex].Values[“Name”].ToString();
TextBox txtDesignation = (TextBox)GridView1.Rows[e.RowIndex].FindControl(“txtDesg”);
con.Open();
SqlCommand cmd = new SqlCommand(“update Grid set Designation='” + txtDesignation.Text + “‘ where Name='” + username + “‘”, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.Text = username + ” Details Updated successfully”;
GridView1.EditIndex = -1;
BindEmployeeDetails();
}

// OnrowCancellingEdit Event Will be Raised Here for GridView


protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindEmployeeDetails();
}

// OnrowDeleting Event Will be Raised Here for GridView to delete the Records in the Table


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string username = GridView1.DataKeys[e.RowIndex].Values[“Name”].ToString();
con.Open();

SqlCommand cmd = new SqlCommand(“delete from Grid where
Name='” + username + “‘”, con);

int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.Text = username + ” details deleted successfully”;
}
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals(“AddNew”))
{
TextBox txtUsrname = (TextBox)GridView1.FooterRow.FindControl(“txtftrusrname”);
TextBox txtDesgnation=(TextBox)GridView1.FooterRow.FindControl(“txtftrDesignation”);
con.Open();
SqlCommand cmd =new SqlCommand(“insert into Grid(Name,Designation) values(‘” + txtUsrname.Text + “‘,'” + txtDesgnation.Text + “‘)”, con);

int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.Text = txtUsrname.Text + ” Details inserted successfully”;
}
else
{
lblresult.Text = txtUsrname.Text + ” Details not inserted”;
}
}
}
}
}

The Outputs Will Be


1) This output Represents the First View of An Page

2) This Output represents the Adding New Users

3) This Output represents After Adding of new Users

4) This Output Represents After Clicking of Edit Button

5) This Output Represents Updated Grid View

6) This Output represents The Deleted Grid View

1 Comment

Filed under .Net

PHP optimisation tips revisited

  • echo is faster than print.
  • Use echo’s multiple parameters instead of string concatenation.
  • Use require() instead of require_once() where possible.
  • require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference.
  • String in single quotes (‘) instead of double quotes (“) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.
  • Since PHP5, the time of when the script started executing can be found in $_SERVER[’REQUEST_TIME’], use this instead of time() or microtime().
  • Error suppression with @ is very slow.

Leave a comment

Filed under php