Monday, November 28, 2016

Download File From GridView Using ASP.Net



 <asp:FileUpload ID="FileUpload1" runat="server" />  
 <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="UploadFile" />  
 <hr />  
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded">  
   <Columns>  
     <asp:BoundField DataField="Text" HeaderText="File Name" />  
     <asp:TemplateField>  
       <ItemTemplate>  
         <asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>  
       </ItemTemplate>  
     </asp:TemplateField>  
     <asp:TemplateField>  
       <ItemTemplate>  
         <asp:LinkButton ID = "lnkDelete" Text = "Delete" CommandArgument = '<%# Eval("Value") %>' runat = "server" OnClick = "DeleteFile" />  
       </ItemTemplate>  
     </asp:TemplateField>  
   </Columns>  
 </asp:GridView>  



Namespaces

You will need to import the following namespaces. C# using System.IO;


 Uploading the File and saving in directory or folder  
 When the file is selected in APS.Net FileUpload control and the Upload button is clicked the following event handler is triggered. Below I have folder Uploads in the root directory of my ASP.Net Website where I am saving the uploaded file.  
 C#  
 protected void UploadFile(object sender, EventArgs e)  
 {  
   string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);  
   FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);  
   Response.Redirect(Request.Url.AbsoluteUri);  
 }  


 Displaying the files from folder or directory in ASP.Net GridView  
 Here I am reading all the files from the Uploads directory which I have created and then binding the fetched files to the ASP.Net GridView control.  
 C#  
 protected void Page_Load(object sender, EventArgs e)  
 {  
   if (!IsPostBack)  
   {  
     string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));  
     List<ListItem> files = new List<ListItem>();  
     foreach (string filePath in filePaths)  
     {  
       files.Add(new ListItem(Path.GetFileName(filePath), filePath));  
     }  
     GridView1.DataSource = files;  
     GridView1.DataBind();  
   }  
 }  


 Downloading the Uploaded File from ASP.Net GridView  
 The following event handler is executed when the lnkDownload LinkButton is clicked in the ASP.Net GridView Row. Using the CommandArgument property of the ASP.Net LinkButton, I get the path of the file using which I am downloading the file.  
 C#  
 protected void DownloadFile(object sender, EventArgs e)  
 {  
   string filePath = (sender as LinkButton).CommandArgument;  
   Response.ContentType = ContentType;  
   Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));  
   Response.WriteFile(filePath);  
   Response.End();  
 }  

Deleting the Uploaded File from ASP.Net GridView  
 The following event handler is executed when the lnkDelete LinkButton is clicked in the ASP.Net GridView Row. Using the CommandArgument property of the ASP.Net LinkButton, I get the path of the file using which I am deleting the file.  
 C#  
 
 protected void DeleteFile(object sender, EventArgs e)  
 {  
   string filePath = (sender as LinkButton).CommandArgument;  
   File.Delete(filePath);  
   Response.Redirect(Request.Url.AbsoluteUri);  
 }  

Wednesday, November 23, 2016

DropDownList Example in ASP.NET using C#

DropDownList Example in ASP.NET using C#

DropDownList.aspx (source code):

 <%@ Page Title="" Language="C#" MasterPageFile="~/RoseindiaMaster.master"  
 AutoEventWireup="true" CodeFile="DropDownList.aspx.cs" Inherits="DropDownList" %>  
 <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">  
 <style type="text/css">  
 .style3  
 {  
 color: #800000;  
 }  
 </style>  
 </asp:Content>  
 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">  
 <div>  
 <h2 style="color:Green">DropDownList in ASP.NET 4 , C#</h2>  
 <strong><span class="style3">Enter first number:</span>  
 </strong>  
 <br />  
 <asp:TextBox ID="txt1" runat="server" Text="12"/>  
 <br />  
 <br />  
 <span class="style3">  
 <strong>Enter second number:  
 </strong>  
 </span>  
 <br />  
 <asp:TextBox ID="txt2" runat="server" Text="3" />  
 <br />  
 <br />  
 <span class="style3">  
 <strong>Select operation:  
 </strong>  
 </span>  
 <br />  
 <asp:DropDownList ID="drp1" runat="server" Width="145px"   
 Font-Bold="True" ForeColor="#006666"   
 onselectedindexchanged="drp1_SelectedIndexChanged" AutoPostBack="True">  
 <asp:ListItem>----Select----</asp:ListItem>  
 <asp:ListItem>Addition</asp:ListItem>  
 <asp:ListItem>Subtraction</asp:ListItem>  
 <asp:ListItem>Multiplication</asp:ListItem>  
 <asp:ListItem>Division</asp:ListItem>  
 </asp:DropDownList>  
 </div>  
 <br />  
 <asp:Label ID="label1" runat="server" Font-Bold="True" ForeColor="#000099" />  
 </asp:Content>  

DropDownList.aspx.cs (C# code file):

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 public partial class DropDownList : System.Web.UI.Page  
 {  
 protected void Page_Load(object sender, EventArgs e)  
 {  
 }  
 protected void drp1_SelectedIndexChanged(object sender, EventArgs e)  
 {  
 double firstno = Convert.ToDouble(txt1.Text);  
 double secondno = Convert.ToDouble(txt2.Text);  
 if(drp1.SelectedIndex == 1)  
 {  
 double add = firstno + secondno;  
 label1.Text = "Addition is :" + add;  
 }  
 if (drp1.SelectedIndex == 2)  
 {  
 double sub = firstno - secondno;  
 label1.Text = "Subtraction is :" + sub;  
 }  
 if (drp1.SelectedIndex == 3)  
 {  
 double mul = firstno * secondno;  
 label1.Text = "Multiplication is :" + mul;  
 }  
 if (drp1.SelectedIndex == 4)  
 {  
 double div = firstno / secondno;  
 label1.Text = "Division is :" + div;  
 }  
 }  
 }  

OUTPUT


Tuesday, November 22, 2016

Dynamically change GridView Cell Background Color based on condition in ASP.Net using C#

The GridView Cell’s background color will be dynamically changed based on its value in the RowDataBound event of GridView.
GridView HTML Markup
The following HTML markup consists of an ASP.Net GridView consisting of two BoundField columns.


  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound = "OnRowDataBound">
    <Columns>
        <asp:BoundField DataField="Item" HeaderText="Item" ItemStyle-Width = "100"/>
        <asp:BoundField DataField="Quantity" HeaderText="Quantity" ItemStyle-Width = "100"/>
    </Columns>
</asp:GridView>

Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Drawing;

Binding the ASP.Net GridView control
I have created a dynamic DataTable with some dummy data and it is used to populate the GridView control in the Page Load event.

 protected void Page_Load(object sender, EventArgs e)  
 {  
   if (!IsPostBack)  
   {  
     DataTable dt = new DataTable();  
     dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Item"), new DataColumn("Quantity") });  
     dt.Rows.Add("Shirt", 145);  
     dt.Rows.Add("Jeans", 0);  
     dt.Rows.Add("Trousers", 190);  
     dt.Rows.Add("Tie", 30);  
     dt.Rows.Add("Cap", 0);  
     dt.Rows.Add("Hat", 90);  
     dt.Rows.Add("Scarf", 290);  
     dt.Rows.Add("Belt", 150);  
     GridView1.DataSource = dt;  
     GridView1.DataBind();  
   }  
 }  

Changing the Background color of GridView Row as per condition dynamically
Inside the OnRowDataBound event handler of the GridView, the Cell value is compared with different quantity ranges and based on the following quantity range values, the background color of the GridView Cell will change.
 protected void OnRowDataBound(object sender, GridViewRowEventArgs e)  
 {  
   if (e.Row.RowType == DataControlRowType.DataRow)  
   {  
     TableCell cell = e.Row.Cells[1];  
     int quantity = int.Parse(cell.Text);  
     if (quantity == 0)  
     {  
       cell.BackColor = Color.Red;  
     }  
     if (quantity > 0 && quantity <= 50)  
     {  
       cell.BackColor = Color.Yellow;  
     }  
     if (quantity > 50 && quantity <= 100)  
     {  
       cell.BackColor = Color.Orange;  
     }  
   }  
 }  


Insert, Update, Delete In GridView Using ASP.Net C#

Using Gridview & SIngle store Procedure Insert, Update, Delete In GridView with sql server



I have set the primary key on the id column and I have set the Identity specification to Yes.
Now we have a table to perform these operations for. Now let us start to create the Stored Procedure.
The Stored Procedure is created using the keyword "Create Procedure" followed by the procedure name. Let us create the Stored Prcedure named "EmpEntry" as in the following:

 create Procedure EmpEntry  
 (  
  --variable declareations   
  @Action Varchar (10),  --to perform operation according to string ed to this varible such as Insert,update,delete,select     
  @id int=null,  --id to perform specific task  
  @FnameVarchar (50)=null,  -- for FirstName  
  @MName Varchar (50)=null,  -- for MName  
  @Lname Varchar (50)=null  -- for LastName  
 )  
 as  
 Begin   
  SET NOCOUNT ON;  
 If @Action='Insert'  --used to insert records  
 Begin  
   Insert Into employee (FirstName,MName,LastName)values(@Fname,@MName,@Lname)  
 End   
 else if @Action='Select'  --used to Select records  
 Begin  
   select *from employee  
 end  
 else if @Action='Update' --used to update records  
 Begin  
   update employeeset FirstName=@Fname,MName=@MName,LastName=@Lname where id=@id  
  End  
  Else If @Action='delete' --used to delete records  
  Begin  
   delete from employeewhere id=@id  
  end  
  End  

The comments in the Stored Procedure above clearly explain which block is used for which purpose, so I have briefly explained it again. I have used the @Action variable and assigned the string to them and according to the parameter ed to the Stored Procedure the specific block will be executed because I have kept these blocks or conditions in nested if else if conditional statements.
"The most important thing is that I have assigned null to each variable to avoid the effect on the parameter ed to the Stored Procedure because we are ing a different number of parameters but not the same number of parameters to the Stored Procedure to perform these tasks."
Now create the one sample application "Empsys" as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Web Application" (to avoid adding a master page).
  3. Provide the web site a name such as  "Empsys" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - "Default.aspx page".
  5. Drag and drop one button, three textboxes, one GridView and one hidden field to the hidden value to the database and one label on the 
     section of the Default.aspx page.
Then switch to the design view;
 <form id="form1"runat="server">  
   <div>  
 First Name <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
 Middle Name<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
 Last Name <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>  
     <asp:ButtonID="Button1"runat="server"Text="save"onclick="Button1_Click" />  
   </div>  
 <asp:HiddenField ID="HiddenField1" runat="server"/>  
  <asp:GridViewID="GridView1"runat="server" >  
    </asp:GridView>  
 </form>  

Now use the following GridView event properties to perform events such as update, delete, edit cancel and so on. Let us see what the properties are:
  • DataKeyNames: This property I have used to the the row index of GridView  
  • OnRowEditing: This property is used to handle the event when the user clicks on the edit button
  • OnRowCancelingEdit: This property is used to handle the event when the user clicks on the Cancel button that exists after clicking on the edit button
  • OnRowDeleting: This property is used to handle the event when the user clicks on the delete button that deletes the row of the GridView
  • OnRowUpdating: This property is used to handle the event when the user clicks on the update button that updates the Grid Record 
Now my grid will look such as the following:
   
  

On the preceding GridView properties I have assigned the method name to be called for particular operations.

 Method to Insert Data in Database   
 Right-click from the design page and view the code and then write the following code in the default.aspx.cs page to save the inserted records in the database:  
 protected void empsave(object sender, EventArgs e)  
 {  
    connection();  
    query = "studentEntryView";     //Stored Procedure name   
    SqlCommand com = new SqlCommand(query, con); //creating SqlCommand object  
    com.CommandType = CommandType.StoredProcedure; //here we declaring command type as stored Procedure  
     /* adding paramerters to SqlCommand below *\  
    com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();//for ing hidden value to preform insert operation  
     com.Parameters.AddWithValue("@FName",TextBox1.Text.ToString());    //first Name  
     com.Parameters.AddWithValue("@Mname ", TextBox2.Text.ToString());   //middle Name  
     com.Parameters.AddWithValue("@LName ",TextBox3.Text.ToString());    //Last Name  
     com.ExecuteNonQuery();           //executing the sqlcommand  
     Label1.Visible = true;  
     Label1.Text = "Records are Submitted Successfully";  
 }  
 Now create the mehtod to view the records in the GridView:  
 public void viewdata()  
 {  
   connection();  
   query = "studentEntryView";  
   SqlCommand com = new SqlCommand(query, con);  
   com.CommandType = CommandType.StoredProcedure;  
   com.Parameters.AddWithValue("@Action", HiddenField2.Value).ToString();  
   DataSet ds =new DataSet();  
   SqlDataAdapter da = new SqlDataAdapter(com);  
   da.Fill(ds);  
   GridView1.DataSource = ds;  
   GridView1.DataBind();  
 }  
 The following is method for the "OnRowEditing" Event:  
 protected void edit(objectsender, GridViewEditEventArgs e)  
 {  
   GridView1.EditIndex= e.NewEditIndex;  
   gedata();  
 }  
 The following is method for the "OnRowCancelingEdit" Event:  
 protected void canceledit(object sender, GridViewCancelEditEventArgs e)  
 {  
   GridView1.EditIndex = -1;  
   gedata();  
 }  
 The following is method for the "OnRowDeleting" Event:  
 protected void delete(object sender, GridViewDeleteEventArgs e)  
 {  
    connection();  
    int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());  
    HiddenField1.Value = "Delete";  
    query = "EmpEntry";  
    com = new SqlCommand(query, con);  
    com.CommandType =CommandType .StoredProcedure;  
    com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();  
    com.Parameters.AddWithValue("id", SqlDbType.Int).Value = id;  
    com.ExecuteNonQuery();  
    con.Close();  
    gedata();           
  }  
 The following is method for the "OnRowUpdating" Event:  
 protected void update(object sender, GridViewUpdateEventArgs e)  
 {  
    connection();  
    int id=int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());  
    HiddenField1.Value = "update";  
    query = "EmpEntry";  
    com = new SqlCommand(query, con);  
    com.CommandType = CommandType.StoredProcedure;  
    com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();  
    com.Parameters.AddWithValue("@FName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString());  
    com.Parameters.AddWithValue("@MName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString());  
    com.Parameters.AddWithValue("@LName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString());  
    com.Parameters.AddWithValue("@id", SqlDbType.int ).Value = id;  
    com.ExecuteNonQuery();  
    con.Close();  
    GridView1.EditIndex = -1;  
    gedata();  
 }  

Brief introduction to the codeIn the sample code above I have used the two string queries for giving the Stored Procedure name and the constr for storing the connection from the web.config file and another thing is that I have used a hidden field by which I am ing the action values that are required to our Stored Procedure.

Now our application is ready to use, press F5 or other as you know, then enter the some values to TextBox and press the "Save" button.


Now after clicking on the "Save" button, the hidden field value takes the value "Insert" and es it to the Stored Procedure as the action and because of this the Stored Procedure will execute a particular type of block.

Now at page load I have called the method, so after that the grid will fill as in:




Now click on the Edit button that calls the edit method as shown in the following grid:



If you click on the "Cancel" button then the editcancel method will be called and edit mode will be cancelled. Now enter some values into the grid TextBox and click on an update button that calls the update method and then the records in the GridView will be updated as in:




Monday, November 21, 2016

RadioButton value save into Database in ASP.Net using C#

 RadioButton value save into  Database in ASP.Net using C# 


 <table border="0" cellpadding="0" cellspacing="0">  
   <tr>  
     <td>  
       Name:  
     </td>  
     <td>  
       <asp:TextBox ID="txtName" runat="server" />  
     </td>  
   </tr>  
   <tr>  
     <td>  
       Gender:  
     </td>  
     <td>  
       <asp:RadioButton ID="rbMale" Text="Male" runat="server" GroupName="Gender" />  
       <asp:RadioButton ID="rbFemale" Text="Female" runat="server" GroupName="Gender" />  
     </td>  
   </tr>  
   <tr>  
     <td>  
     </td>  
     <td>  
       <asp:Button Text="Submit" runat="server" OnClick="Submit" />  
     </td>  
   </tr>  
 </table>  


 protected void Submit(object sender, EventArgs e)  
 {  
   string name = txtName.Text.Trim();  
   string gender = string.Empty;  
   if (rbMale.Checked)  
   {  
     gender = "M";  
   }  
   else if (rbFemale.Checked)  
   {  
     gender = "F";  
   }  
   string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
   using (SqlConnection con = new SqlConnection(constr))  
   {  
     using (SqlCommand cmd = new SqlCommand("INSERT INTO Persons(Name, Gender) VALUES(@Name, @Gender)"))  
     {  
       cmd.Connection = con;  
       cmd.Parameters.AddWithValue("@Name", name);  
       cmd.Parameters.AddWithValue("@Gender", gender);  
       con.Open();  
       cmd.ExecuteNonQuery();  
       con.Close();  
     }  
   }  
 }  

CheckBox Control in c#

CheckBoxes allow the user to make multiple selections from a number of options. CheckBox to give the user an option, such as true/false or yes/no. You can click a check box to select it and click it again to deselect it.



 using System;  
 using System.Drawing;  
 using System.Windows.Forms;  
 namespace WindowsFormsApplication1  
 {  
   public partial class Form1 : Form  
   {  
     public Form1()  
     {  
       InitializeComponent();  
     }  
     private void button1_Click(object sender, EventArgs e)  
     {  
       string msg = "";  
       if (checkBox1.Checked == true)  
       {  
         msg = "net-informations.com";  
       }  
       if (checkBox2.Checked == true)  
       {  
         msg = msg + "  vb.net-informations.com";  
       }  
       if (checkBox3.Checked == true)  
       {  
         msg = msg + "  csharp.net-informations.com";  
       }  
       if (msg.Length > 0)  
       {  
         MessageBox.Show (msg + " selected ");  
       }  
       else  
       {  
         MessageBox.Show ("No checkbox selected");  
       }  
       checkBox1.ThreeState = true;  
     }  
   }  
 }  

Saturday, November 19, 2016

Calculator using ASP.net

Basic Calculator in C#

Process to create calculator

First we need to create a TextBox and 16 Buttons as in the following:
  • 10 Buttons for numbers (0-9)
  • 5 Buttons to perform operation (addition (+), Subtraction (-) , Multiplication (*), Division (/) ,Clear (CLR) )
  • 1 Buttons for evaluation (=)
Here is the code for the "Default.aspx" page:


 <html xmlns="http://www.w3.org/1999/xhtml">  
 <head id="Head1" runat="server">  
   <title></title>  
   <style type="text/css">  
   .cal  
   {  
     position:absolute;  
     top:50px;  
     left:150px;  
     right:400px;  
     height:500px;  
     bottom:100px;  
     background-color:Teal;  
     }  
   </style>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
   <div class="cal">  
     <asp:Label ID="l" Text=" BASIC CALCULATOR" runat="server" Style="margin-left: 200px"  
       Font-Bold="False" Font-Italic="False"></asp:Label>  
     <asp:TextBox ID="t" runat="server" Style="margin-left: 100px; margin-top: 24px;"  
       Width="335px" Height="41px"></asp:TextBox>  
     <asp:Button ID="b1" Text="1" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="b1_Click" />  
     <asp:Button ID="b2" Text="2" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="b2_Click" />  
     <asp:Button ID="b3" Text="3" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="b3_Click" />  
     <asp:Button ID="add" Text="+" runat="server" Height="37px" Style="margin-left: 0px;  
       margin-top: 0px;" Width="57px" OnClick="add_Click" />  
     <asp:Button ID="b4" Text="4" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="b4_Click" />  
     <asp:Button ID="b5" Text="5" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="b5_Click" />  
     <asp:Button ID="b6" Text="6" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="b6_Click" />  
     <asp:Button ID="sub" Text="-" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="sub_Click" />  
     <asp:Button ID="b7" Text="7" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="b7_Click" />  
     <asp:Button ID="b8" Text="8" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="b8_Click" />  
     <asp:Button ID="b9" Text="9" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="b9_Click" />  
     <asp:Button ID="mul" Text="*" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="mul_Click" />  
     <asp:Button ID="b0" runat="server" Text="0" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="b0_Click" />  
     <asp:Button ID="clr" runat="server" Text="CLR" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="clr_Click" />  
     <asp:Button ID="eql" runat="server" Text="=" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="eql_Click" />  
     <asp:Button ID="div" Text="/" runat="server" Height="37px" Style="margin-left: 0px"  
       Width="57px" OnClick="div_Click" />  
   </div>  
   </form>  
 </body>  
 </html>  

Here is the code for the "Default.aspx.cs" page (the code for all the buttons) :

 Here is the code for the "Default.aspx.cs" page (the code for all the buttons) :  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 public partial class _Default : System.Web.UI.Page  
 {  
   static float a, c, d;  
   static char b;  
   protected void Page_Load(object sender, EventArgs e)  
   {  
   }  
   protected void b1_Click(object sender, EventArgs e)  
   {  
     if ((t.Text == "+") || (t.Text == "-") || (t.Text == "*") || (t.Text == "/"))  
     {  
       t.Text = "";  
       t.Text = t.Text + b1.Text;  
     }  
     else  
       t.Text = t.Text + b1.Text;  
   }  
   protected void b2_Click(object sender, EventArgs e)  
   {  
     if ((t.Text == "+") || (t.Text == "-") || (t.Text == "*") || (t.Text == "/"))  
     {  
       t.Text = "";  
       t.Text = t.Text + b2.Text;  
     }  
     else  
       t.Text = t.Text + b2.Text;  
   }  
   protected void b3_Click(object sender, EventArgs e)  
   {  
     if ((t.Text == "+") || (t.Text == "-") || (t.Text == "*") || (t.Text == "/"))  
     {  
       t.Text = "";  
       t.Text = t.Text + b3.Text;  
     }  
     else  
       t.Text = t.Text + b3.Text;  
   }  
   protected void b4_Click(object sender, EventArgs e)  
   {  
     if ((t.Text == "+") || (t.Text == "-") || (t.Text == "*") || (t.Text == "/"))  
     {  
       t.Text = "";  
       t.Text = t.Text + b4.Text;  
     }  
     else  
       t.Text = t.Text + b4.Text;  
   }  
   protected void b5_Click(object sender, EventArgs e)  
   {  
     if ((t.Text == "+") || (t.Text == "-") || (t.Text == "*") || (t.Text == "/"))  
     {  
       t.Text = "";  
       t.Text = t.Text + b5.Text;  
     }  
     else  
       t.Text = t.Text + b5.Text;  
   }  
   protected void b6_Click(object sender, EventArgs e)  
   {  
     if ((t.Text == "+") || (t.Text == "-") || (t.Text == "*") || (t.Text == "/"))  
     {  
       t.Text = "";  
       t.Text = t.Text + b6.Text;  
     }  
     else  
       t.Text = t.Text + b5.Text;  
   }  
   protected void b7_Click(object sender, EventArgs e)  
   {  
     if ((t.Text == "+") || (t.Text == "-") || (t.Text == "*") || (t.Text == "/"))  
     {  
       t.Text = "";  
       t.Text = t.Text + b7.Text;  
     }  
     else  
       t.Text = t.Text + b7.Text;  
   }  
   protected void b8_Click(object sender, EventArgs e)  
   {  
     if ((t.Text == "+") || (t.Text == "-") || (t.Text == "*") || (t.Text == "/"))  
     {  
       t.Text = "";  
       t.Text = t.Text + b8.Text;  
     }  
     else  
       t.Text = t.Text + b8.Text;  
   }  
   protected void b9_Click(object sender, EventArgs e)  
   {  
     if ((t.Text == "+") || (t.Text == "-") || (t.Text == "*") || (t.Text == "/"))  
     {  
       t.Text = "";  
       t.Text = t.Text + b9.Text;  
     }  
     else  
       t.Text = t.Text + b9.Text;  
   }  
   protected void b0_Click(object sender, EventArgs e)  
   {  
     if ((t.Text == "+") || (t.Text == "-") || (t.Text == "*") || (t.Text == "/"))  
     {  
       t.Text = "";  
       t.Text = t.Text + b0.Text;  
     }  
     else  
       t.Text = t.Text + b0.Text;  
   }  
   protected void add_Click(object sender, EventArgs e)  
   {  
     a = Convert.ToInt32(t.Text);  
     t.Text = "";  
     b = '+';  
     t.Text += b;  
   }  
   protected void sub_Click(object sender, EventArgs e)  
   {  
     a = Convert.ToInt32(t.Text);  
     t.Text = "";  
     b = '-';  
     t.Text += b;  
   }  
   protected void mul_Click(object sender, EventArgs e)  
   {  
     a = Convert.ToInt32(t.Text);  
     t.Text = "";  
     b = '*';  
     t.Text += b;  
   }  
   protected void div_Click(object sender, EventArgs e)  
   {  
     a = Convert.ToInt32(t.Text);  
     t.Text = "";  
     b = '/';  
     t.Text += b;  
   }  
   protected void eql_Click(object sender, EventArgs e)  
   {  
     c = Convert.ToInt32(t.Text);  
     t.Text = "";  
     if (b == '/')  
     {  
       d = a / c;  
       t.Text += d;  
       a = d;  
     }  
     else if (b == '+')  
     {  
       d = a + c;  
       t.Text += d;  
       a = d;  
     }  
     else if (b == '-')  
     {  
       d = a - c;  
       t.Text += d;  
       a = d;  
     }  
     else  
     {  
       d = a * c;  
       t.Text += d;  
       a = d;  
     }  
   }  
   protected void clr_Click(object sender, EventArgs e)  
   {  
     t.Text = "";  
   }  
 }  

Friday, November 18, 2016

What Is Angular?

What Is Angular?

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. Angular's data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.
Angular is what HTML would have been, had it been designed for applications. HTML is a great declarative language for static documents. It does not contain much in the way of creating applications, and as a result building web applications is an exercise in what do I have to do to trick the browser into doing what I want?
The impedance mismatch between dynamic applications and static documents is often solved with:
  • a library - a collection of functions which are useful when writing web apps. Your code is in charge and it calls into the library when it sees fit. E.g., jQuery.
  • frameworks - a particular implementation of a web application, where your code fills in the details. The framework is in charge and it calls into your code when it needs something app specific. E.g., durandalember, etc.
Angular takes another approach. It attempts to minimize the impedance mismatch between document centric HTML and what an application needs by creating new HTML constructs. Angular teaches the browser new syntax through a construct we call directives. Examples include:
  • Data binding, as in {{}}.
  • DOM control structures for repeating, showing and hiding DOM fragments.
  • Support for forms and form validation.
  • Attaching new behavior to DOM elements, such as DOM event handling.
  • Grouping of HTML into reusable components.

A complete client-side solution

Angular is not a single piece in the overall puzzle of building the client-side of a web application. It handles all of the DOM and AJAX glue code you once wrote by hand and puts it in a well-defined structure. This makes Angular opinionated about how a CRUD (Create, Read, Update, Delete) application should be built. But while it is opinionated, it also tries to make sure that its opinion is just a starting point you can easily change. Angular comes with the following out-of-the-box:
  • Everything you need to build a CRUD app in a cohesive set: Data-binding, basic templating directives, form validation, routing, deep-linking, reusable components and dependency injection.
  • Testability story: Unit-testing, end-to-end testing, mocks and test harnesses.
  • Seed application with directory layout and test scripts as a starting point.

Angular's sweet spot

Angular simplifies application development by presenting a higher level of abstraction to the developer. Like any abstraction, it comes at a cost of flexibility. In other words, not every app is a good fit for Angular. Angular was built with the CRUD application in mind. Luckily CRUD applications represent the majority of web applications. To understand what Angular is good at, though, it helps to understand when an app is not a good fit for Angular.
Games and GUI editors are examples of applications with intensive and tricky DOM manipulation. These kinds of apps are different from CRUD apps, and as a result are probably not a good fit for Angular. In these cases it may be better to use a library with a lower level of abstraction, such as jQuery.

The Zen of Angular

Angular is built around the belief that declarative code is better than imperative when it comes to building UIs and wiring software components together, while imperative code is excellent for expressing business logic.
  • It is a very good idea to decouple DOM manipulation from app logic. This dramatically improves the testability of the code.
  • It is a really, really good idea to regard app testing as equal in importance to app writing. Testing difficulty is dramatically affected by the way the code is structured.
  • It is an excellent idea to decouple the client side of an app from the server side. This allows development work to progress in parallel, and allows for reuse of both sides.
  • It is very helpful indeed if the framework guides developers through the entire journey of building an app: From designing the UI, through writing the business logic, to testing.
  • It is always good to make common tasks trivial and difficult tasks possible.
Angular frees you from the following pains:
  • Registering callbacks: Registering callbacks clutters your code, making it hard to see the forest for the trees. Removing common boilerplate code such as callbacks is a good thing. It vastly reduces the amount of JavaScript coding you have to do, and it makes it easier to see what your application does.
  • Manipulating HTML DOM programmatically: Manipulating HTML DOM is a cornerstone of AJAX applications, but it's cumbersome and error-prone. By declaratively describing how the UI should change as your application state changes, you are freed from low-level DOM manipulation tasks. Most applications written with Angular never have to programmatically manipulate the DOM, although you can if you want to.
  • Marshaling data to and from the UI: CRUD operations make up the majority of AJAX applications' tasks. The flow of marshaling data from the server to an internal object to an HTML form, allowing users to modify the form, validating the form, displaying validation errors, returning to an internal model, and then back to the server, creates a lot of boilerplate code. Angular eliminates almost all of this boilerplate, leaving code that describes the overall flow of the application rather than all of the implementation details.
  • Writing tons of initialization code just to get started: Typically you need to write a lot of plumbing just to get a basic "Hello World" AJAX app working. With Angular you can bootstrap your app easily using services, which are auto-injected into your application in a Guice-like dependency-injection style. This allows you to get started developing features quickly. As a bonus, you get full control over the initialization process in automated tests.

Thursday, November 17, 2016

Insert,Update,Delete in asp.net with sqlserver 2008

Insert,Update,Delete in asp.net with sqlserver 2008

 using System;   
 using System.Data;   
 using System.Windows.Forms;   
 using System.Data.SqlClient;   
 namespace InsertUpdateDeleteDemo   
 {   
   public partial class frmMain : Form   
   {   
     SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");   
     SqlCommand cmd;   
     SqlDataAdapter adapt;   
     //ID variable used in Updating and Deleting Record   
     int ID = 0;   
     public frmMain()   
     {   
       InitializeComponent();   
       DisplayData();   
     }   
     //Insert Data   
     private void btn_Insert_Click(object sender, EventArgs e)   
     {   
       if (txt_Name.Text != "" && txt_State.Text != "")   
       {   
         cmd = new SqlCommand("insert into tbl_Record(Name,State) values(@name,@state)", con);   
         con.Open();   
         cmd.Parameters.AddWithValue("@name", txt_Name.Text);   
         cmd.Parameters.AddWithValue("@state", txt_State.Text);   
         cmd.ExecuteNonQuery();   
         con.Close();   
         MessageBox.Show("Record Inserted Successfully");   
         DisplayData();   
         ClearData();   
       }   
       else   
       {   
         MessageBox.Show("Please Provide Details!");   
       }   
     }   
     //Display Data in DataGridView   
     private void DisplayData()   
     {   
       con.Open();   
       DataTable dt=new DataTable();   
       adapt=new SqlDataAdapter("select * from tbl_Record",con);   
       adapt.Fill(dt);   
       dataGridView1.DataSource = dt;   
       con.Close();   
     }   
     //Clear Data   
     private void ClearData()   
     {   
       txt_Name.Text = "";   
       txt_State.Text = "";   
       ID = 0;   
     }   
     //dataGridView1 RowHeaderMouseClick Event   
     private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)   
     {   
       ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());   
       txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();   
       txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();   
     }   
     //Update Record   
     private void btn_Update_Click(object sender, EventArgs e)   
     {   
       if (txt_Name.Text != "" && txt_State.Text != "")   
       {   
         cmd = new SqlCommand("update tbl_Record set Name=@name,State=@state where ID=@id", con);   
         con.Open();   
         cmd.Parameters.AddWithValue("@id", ID);   
         cmd.Parameters.AddWithValue("@name", txt_Name.Text);   
         cmd.Parameters.AddWithValue("@state", txt_State.Text);   
         cmd.ExecuteNonQuery();   
         MessageBox.Show("Record Updated Successfully");   
         con.Close();   
         DisplayData();   
         ClearData();   
       }   
       else   
       {   
         MessageBox.Show("Please Select Record to Update");   
       }   
     }   
     //Delete Record   
     private void btn_Delete_Click(object sender, EventArgs e)   
     {   
       if(ID!=0)   
       {   
         cmd = new SqlCommand("delete tbl_Record where ID=@id",con);   
         con.Open();   
         cmd.Parameters.AddWithValue("@id",ID);   
         cmd.ExecuteNonQuery();   
         con.Close();   
         MessageBox.Show("Record Deleted Successfully!");   
         DisplayData();   
         ClearData();   
       }   
       else   
       {   
         MessageBox.Show("Please Select Record to Delete");   
       }   
     }   
   }   
 }   

INSERT,UPDATE,DELETE in Asp.net Using MYSQL

In the code behind file (Student.aspx.cs) write the code as in the following.

Student.aspx

 <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"  
 CodeBehind="Student.aspx.cs" Inherits="MYSQLCRUDApplication.Student" %>  
 <asp:Content ID="Content1" ContentPlaceHolderID="titleContent" runat="server">  
   Simple Insert Select Update and Delete in ASP.NET using MySQL Database </asp:Content>  
 <asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">  
 </asp:Content>  
 <asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">  
   <table>  
     <tr>  
       <td class="td">Name:</td>  
       <td>  
         <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>  
       <td>  
         <asp:Label ID="lblSID" runat="server" Visible="false"></asp:Label> </td>  
     </tr>  
     <tr>  
       <td class="td">Address:</td>  
       <td>  
         <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>  
       <td> </td>  
     </tr>  
     <tr>  
       <td class="td">Mobile:</td>  
       <td>  
         <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox></td>  
       <td> </td>  
     </tr>  
     <tr>  
       <td class="td">Email ID:</td>  
       <td>  
         <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>  
       <td> </td>  
     </tr>  
     <tr>  
       <td></td>  
       <td>  
         <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />  
         <asp:Button ID="btnUpdate" runat="server" Text="Update" Visible="false"  
 OnClick="btnUpdate_Click" />  
         <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" /></td>  
       <td></td>  
     </tr>  
   </table>  
   <div style="padding: 10px; margin: 0px; width: 100%;">  
     <p>  
       Total Student:<asp:Label ID="lbltotalcount" runat="server" Font-Bold="true"></asp:Label>  
     </p>  
     <asp:GridView ID="GridViewStudent" runat="server" DataKeyNames="SID"   
       OnSelectedIndexChanged="GridViewStudent_SelectedIndexChanged"  
 OnRowDeleting="GridViewStudent_RowDeleting">  
       <Columns>  
         <asp:CommandField HeaderText="Update" ShowSelectButton="True" />  
         <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />  
       </Columns>  
     </asp:GridView>  
   </div>  
 </asp:Content>  
 In the Web.config file create the connection string as in the following.  
 Web.config  
 <connectionStrings>  
   <add name="ConnectionString"  
 connectionString="Server=localhost;userid=root;password=;Database=Testdb"  
 providerName="MySql.Data.MySqlClient"/>  
  </connectionStrings>  

Now, in the code behind file “Student.aspx.cs “ use the following code. Student.aspx.cs

using System;using System.Collections.Generic;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using MySql.Data.MySqlClient; namespace MYSQLCRUDApplication { public partial class Student : System.Web.UI.Page { #region MySqlConnection Connection and Page Lode MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { Try { if (!Page.IsPostBack) { BindGridView(); } } catch (Exception ex) { ShowMessage(ex.Message); } } #endregion #region show message void ShowMessage(string msg) { ClientScript.RegisterStartupScript(Page.GetType(), "validation", ""); } void clear() { txtName.Text = string.Empty; txtAddress.Text = string.Empty; txtMobile.Text = string.Empty; txtEmail.Text = string.Empty; txtName.Focus(); } #endregion


     #region bind data to GridViewStudent  
     private void BindGridView()  
     {   
       Try  
       {  
         if (conn.State == ConnectionState.Closed)  
         {  
           conn.Open();  
         }  
         MySqlCommand cmd = new MySqlCommand("Select * from Student ORDER BY SID DESC;",  
 conn);  
         MySqlDataAdapter adp = new MySqlDataAdapter(cmd);  
         DataSet ds = new DataSet();  
         adp.Fill(ds);  
         GridViewStudent.DataSource = ds;  
         GridViewStudent.DataBind();  
         lbltotalcount.Text = GridViewStudent.Rows.Count.ToString();  
       }  
       catch (MySqlException ex)  
       {  
         ShowMessage(ex.Message);  
       }  
       Finally  
       {  
         if (conn.State == ConnectionState.Open)  
         {  
           conn.Close();  
         }  
       }  
     }    #endregion  




     #region Insert Data  
     protected void btnSubmit_Click(object sender, EventArgs e)  
     {  
       Try  
       {  
         conn.Open();  
         MySqlCommand cmd = new MySqlCommand("Insert into student (Name,Address,Mobile,Email )  
 values (@Name,@Address,@Mobile,@Email)", conn);  
         cmd.Parameters.AddWithValue("@Name",txtName.Text);  
         cmd.Parameters.AddWithValue("@Address", txtAddress.Text);  
         cmd.Parameters.AddWithValue("@Mobile",txtMobile.Text);  
         cmd.Parameters.AddWithValue("@Email",txtEmail.Text);  
         cmd.ExecuteNonQuery();          
         cmd.Dispose();   
         ShowMessage("Registered Inserted successfully......!");         
         clear();  
         BindGridView();  
       }  
       catch (MySqlException ex)  
       {  
         ShowMessage(ex.Message);  
       }  
       Finally  
       {  
         conn.Close();  
       }  
     }  
          #endregion  
   #region SelectedIndexChanged  

     protected void GridViewStudent_SelectedIndexChanged(object sender, EventArgs e)  
     {  
       GridViewRow row = GridViewStudent.SelectedRow;  
       lblSID.Text = row.Cells[2].Text;  
       txtName.Text = row.Cells[3].Text;  
       txtAddress.Text = row.Cells[4].Text;  
       txtEmail.Text = row.Cells[5].Text;  
       txtMobile.Text = row.Cells[6].Text;  
       btnSubmit.Visible = false;  
       btnUpdate.Visible = true;  
     }    #endregion  
     #region Delete Student Data  
     protected void GridViewStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)  
     {  
       Try  
       {  
         conn.Open();  
         int SID = Convert.ToInt32(GridViewStudent.DataKeys[e.RowIndex].Value);  
         MySqlCommand cmd = new MySqlCommand("Delete From student where SID='" + SID + "'",  
 conn);  
         cmd.ExecuteNonQuery();  
         cmd.Dispose();  
         ShowMessage("Student Record Delete Successfully......!");  
         GridViewStudent.EditIndex = -1;  
         BindGridView();  
       }  
       catch (MySqlException ex)  
       {  
         ShowMessage(ex.Message);  
       }  
       Finally  
       {  
         conn.Close();  
       }  
     }    #endregion  


     #region student data update  
     protected void btnUpdate_Click(object sender, EventArgs e)  
     {  
       Try  
       {  
         conn.Open();  
         string SID = lblSID.Text;         
         MySqlCommand cmd = new MySqlCommand("update student Set  
 Name=@Name,Address=@Address,Mobile=@Mobile,Email=@Email where SID=@SID", conn);  
         cmd.Parameters.AddWithValue("@Name", txtName.Text);  
         cmd.Parameters.AddWithValue("@Address", txtAddress.Text);  
         cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);  
         cmd.Parameters.AddWithValue("@Email", txtEmail.Text);  
         cmd.Parameters.AddWithValue("SID",SID);  
         cmd.ExecuteNonQuery();  
         cmd.Dispose();  
         ShowMessage("Student Record update Successfully......!");  
         GridViewStudent.EditIndex = -1;  
         BindGridView(); btnUpdate.Visible = false;  
       }  
       catch (MySqlException ex)  
       {  
         ShowMessage(ex.Message);  
       }  
       Finally  
       {  
         conn.Close();  
       }  
     }    #endregion  
     #region textbox clear  
     protected void btnCancel_Click(object sender, EventArgs e)  
     {  
       clear();  
     }    #endregion  
   }  
 }  

DETECT SHAKE USING JAVASCRIPT

DETECT SHAKE USING JAVASCRIPT

 <!doctype html>  
 <html>  
      <head>  
           <style type="text/css">  
                #box  
                {  
                     width: 300px;  
                     height: 300px;  
                }  
                               #carbonads {   
                  max-width: 300px;   
                  background: #f8f8f8;  
                }  
                .carbon-text {   
                  display: block;   
                  width: 130px;   
                }  
                .carbon-poweredby {   
                  float: right;   
                }  
                .carbon-text {  
                  padding: 8px 0;   
                }  
                #carbonads {   
                  padding: 15px;  
                  border: 1px solid #ccc;   
                }  
                .carbon-text {  
                  font-size: 12px;  
                  color: #333333;  
                  text-decoration: none;  
                }  
                .carbon-poweredby {  
                  font-size: 75%;  
                  text-decoration: none;  
                }  
                #carbonads {   
                  position: fixed;   
                  top: 5px;  
                  right: 5px;  
                }  
           </style>  
           <script type="text/javascript" src="https://cdn.rawgit.com/alexgibson/shake.js/master/shake.js"></script>  
           <script type="text/javascript">  
                function getRandomInt(min, max) {  
                 return Math.floor(Math.random() * (max - min + 1)) + min;  
                }  
                var shakeEvent = new Shake({threshold: 15});  
                shakeEvent.start();  
                window.addEventListener('shake', function(){  
                     var element = document.getElementById("box");  
                  var r = getRandomInt(0, 255);  
                  var g = getRandomInt(0, 255);  
                  var b = getRandomInt(0, 255);  
                  element.style.backgroundColor = "rgb(" + r + "," + g + "," + b + ")";  
                }, false);  
                //stop listening  
                function stopShake(){  
                     shakeEvent.stop();  
                }  
                if(!("ondevicemotion" in window)){alert("Not Supported");}  
           </script>  
      </head>  
      <body>  
           Shake to change color of the box  
           <div id="box"></div>  
           <script type="text/javascript">  
                var element = document.getElementById("box");  
                var r = getRandomInt(0, 255);  
                var g = getRandomInt(0, 255);  
                var b = getRandomInt(0, 255);  
             element.style.backgroundColor = "rgb(" + r + "," + g + "," + b + ")";  
           </script>  
           <script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=qnimate" id="_carbonads_js"></script>  
      </body>  
 </html>