Page

How to use Detailview in ASP.net

// Default.aspx //


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title> Detail View </title>
</head>
<body>
  <form id="form1" runat="server">
    <div>
        <b>Details View Example</b><br />
       <br />
        <asp:Label ID="lblmsg" runat="server"></asp:Label><br /><br />
       <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="400px" AutoGenerateRows="False"
            CellPadding="4" ForeColor="#333333" GridLines="None" OnItemUpdating="DetailsView1_ItemUpdating"
            OnModeChanging="DetailsView1_ModeChanging" 
            OnItemCommand="DetailsView1_ItemCommand" AllowPaging="true" 
            oniteminserting="DetailsView1_ItemInserting" 
            onitemdeleting="DetailsView1_ItemDeleting" 
            onpageindexchanging="DetailsView1_PageIndexChanging">
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
           <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
           <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
          <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
          <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <Fields>
              <asp:TemplateField HeaderText="ID">
                   <ItemTemplate>
                      <asp:Label ID="lbleno" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ID") %>'></asp:Label>
                    </ItemTemplate>
                   <EditItemTemplate>
                        <asp:TextBox ID="txteno" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ID") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                
                <asp:TemplateField HeaderText="Student Name">
                   <ItemTemplate>
                       <asp:Label ID="lblempname" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'></asp:Label>
                  </ItemTemplate>
                   <EditItemTemplate>
                      <asp:TextBox ID="txtempname" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'></asp:TextBox>
                   </EditItemTemplate>
              </asp:TemplateField>
                
               <asp:TemplateField HeaderText="Address">
                   <ItemTemplate>
                       <asp:Label ID="lblsal" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Address") %>'></asp:Label>
                   </ItemTemplate>
                  <EditItemTemplate>
                        <asp:TextBox ID="txtsal" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Address") %>'></asp:TextBox>
                   </EditItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowDeleteButton="True"></asp:CommandField>
               <asp:CommandField ShowInsertButton="True"></asp:CommandField>
               <asp:CommandField ShowEditButton="True" CancelText="Cancel" EditText="Edit" UpdateText="Update" /> 
            </Fields>
          <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
           <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
       </asp:DetailsView>
  </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;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page 
{
    SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Pubs"].ConnectionString);
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadDet();
        }
    }
    void LoadDet()
    {
        sqlcon.Open();
        sqlcmd = new SqlCommand("select * from Add_Record", sqlcon);
        da = new SqlDataAdapter(sqlcmd);
        da.Fill(dt);
        sqlcon.Close();
        DetailsView1.DataSource = dt;
        DetailsView1.DataBind();
    }

    //Below code is used to display page wise records

    protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
    {
        DetailsView1.PageIndex = e.NewPageIndex;
        LoadDet();
    }
    protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e)
    {
        if (e.CancelingEdit == true)
        {
            DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
            LoadDet();
        }

    }

    //Below code is used to update record details 

    protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        string eno = ((TextBox)DetailsView1.FindControl("ID")).Text.ToString();
        string empname = ((TextBox)DetailsView1.FindControl("Name")).Text.ToString();
        string Add = ((TextBox)DetailsView1.FindControl("Address")).Text.ToString();
        sqlcon.Open();
        sqlcmd = new SqlCommand("UPDATE Add_Record SET Name='" + empname + "', Address='" + Add + "' WHERE ID='" + eno + "' ", sqlcon);
        sqlcmd.ExecuteNonQuery();
        sqlcon.Close();
        DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
        LoadDet();
    }
    protected void DetailsView1_ItemCommand(object sender, DetailsViewCommandEventArgs e)
    {
        if (e.CommandName == "New")
        {
            DetailsView1.ChangeMode(DetailsViewMode.Insert);
            LoadDet();
        }
        if (e.CommandName == "Edit")
        {
            DetailsView1.ChangeMode(DetailsViewMode.Edit);
            LoadDet();
        }
    }

    //Below code is used to insert record into database  table

    protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        sqlcon.Open();
        string eno = ((TextBox)DetailsView1.FindControl("ID")).Text.ToString();
        string empname = ((TextBox)DetailsView1.FindControl("Name")).Text.ToString();
        string sal = ((TextBox)DetailsView1.FindControl("Address")).Text.ToString();
        SqlCommand cmd = new SqlCommand("select ID from Add_Record where ID = '" + eno + "'", sqlcon);
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
          lblmsg.Text = "User No already exists";
        }
        else
        {
            dr.Close();
            sqlcmd = new SqlCommand("insert into Add_Record values('" + eno + "', '" + empname + "', '" + sal + "')", sqlcon);
            sqlcmd.ExecuteNonQuery();        
            DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);            
        }
        sqlcon.Close();
        LoadDet();
    }

    //Below code is used to delete record from database 

    protected void DetailsView1_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
    {
        string eno = ((Label)DetailsView1.Rows[0].FindControl("lbleno")).Text;
        sqlcon.Open();
        sqlcmd = new SqlCommand("delete from Add_Record where ID = '" + eno + "'", sqlcon);
        sqlcmd.ExecuteNonQuery();
        sqlcon.Close();
        DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
        LoadDet();
    }
}

   
 
SQL TABLE




OUTPUT







Print page content placed inside DIV tag using JavaScript in Asp.net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Print DIV Content using javaScript</title>
    <script language="javascript" type="text/javascript">
        function PrintDivContent(divId) {
            var printContent = document.getElementById(divId);
            var WinPrint = window.open('', '', 'left=0,top=0,toolbar=0,sta­tus=0');
            WinPrint.document.write(printContent.innerHTML);
            WinPrint.document.close();
            WinPrint.focus();
            WinPrint.print();
        }
  </script>
</head>
<body>
    <form id="form1" runat="server">
   <div>
    <div id="divToPrint">
    This is a sample content to print
    sourcecodernp.blogspot.com
    sourcecodernp.blogspot.com
    sourcecodernp.blogspot.com
    </div>
    <br /> 
      
    <asp:ImageButton ID="imgBtnPrint" runat="server" ImageUrl="~/Print_button.png" OnClientClick="javascript:PrintDivContent('divToPrint');" />
  </div>
   </form>
</body>
</html> 
    



OUTPUT SCREEN SHOT







  
      
   
   
   

C Program to Input Password for Validation of User name

#include<stdio.h>
#include<conio.h>

void main() {
   char password[25], ch;
   int i;

   clrscr();
   puts("Enter password : ");

   while (1) {
      if (i < 0) {
         i = 0;
      }
      ch = getch();

      if (ch == 13)
         break;
      if (ch == 8) /*ASCII value of BACKSPACE*/
      {
         putch('b');
         putch(NULL);
         putch('b');
         i--;
         continue;
      }

      password[i++] = ch;
      ch = '*';
      putch(ch);
   }

   password[i] = '\0';
   printf("\nPassword Entered : %s", password);

   getch();
}


OUTPUT

Enter password : **********
Password Entered : sourcecode

C Program to Implement Calender Program to display Day of the month

#include<stdio.h>
#include<conio.h> 
#include<math.h> 

int fm(int date, int month, int year) {
   int fmonth, leap;

   //leap function 1 for leap & 0 for non-leap
   if ((year % 100 == 0) && (year % 400 != 0))
      leap = 0;
   else if (year % 4 == 0)
      leap = 1;
   else
      leap = 0;

   fmonth = 3 + (2 - leap) * ((month + 2) / (2 * month))
         + (5 * month + month / 9) / 2;

   //bring it in range of 0 to 6
   fmonth = fmonth % 7;

   return fmonth;
}


int day_of_week(int date, int month, int year) {

   int dayOfWeek;
   int YY = year % 100;
   int century = year / 100;

   printf("\nDate: %d/%d/%d \n", date, month, year);

   dayOfWeek = 1.25 * YY + fm(date, month, year) + date - 2 * (century % 4);

   //remainder on division by 7
   dayOfWeek = dayOfWeek % 7;

   switch (dayOfWeek) {
      case 0:
         printf("weekday = Saturday");
         break;
      case 1:
         printf("weekday = Sunday");
         break;
      case 2:
         printf("weekday = Monday");
         break;
      case 3:
         printf("weekday = Tuesday");
         break;
      case 4:
         printf("weekday = Wednesday");
         break;
      case 5:
         printf("weekday = Thursday");
         break;
      case 6:
         printf("weekday = Friday");
         break;
      default:
         printf("Incorrect data");
   }
   return 0;
}



int main() {
   int date, month, year;

   printf("\nEnter the year ");
   scanf("%d", &year);

   printf("\nEnter the month ");
   scanf("%d", &month);

   printf("\nEnter the date ");
   scanf("%d", &date);

   day_of_week(date, month, year);

   return 0;
}



OUTPUT

Enter the year 2012
Enter the month 02
Enter the date 29
Date: 29/2/2012

weekday = Wednesday

Insert, update and delete using sql in c#

 // Default.aspx //

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Students" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <div>
      <br />
      <asp:Label id="Label1" runat="server">Select Author:</asp:Label>
    <asp:DropDownList id="lstAuthor" runat="server" AutoPostBack="True" onselectedindexchanged="lstAuthor_SelectedIndexChanged"></asp:DropDownList>   
     <asp:Button id="cmdUpdate" runat="server" Text="Update" onclick="cmdUpdate_Click"></asp:Button> 
     <asp:Button id="cmdDelete" runat="server" Text="Delete" onclick="cmdDelete_Click"></asp:Button>
      <br />
     <asp:Label id="Label11" runat="server" Width="99px" Height="19px">Or:</asp:Label>
      <asp:Button id="cmdNew" runat="server" Width="91px" Height="24px" Text="Create New" onclick="cmdNew_Click"></asp:Button> 
      <asp:Button id="cmdInsert" runat="server" Width="85px" Height="24px" Text="Insert New" onclick="cmdInsert_Click"></asp:Button>
   </div>
   <br />
    <div>
     <asp:Label id="Label10" runat="server" Width="100px">Unique ID:</asp:Label>
    <asp:TextBox id="txtID" runat="server" Width="184px"></asp:TextBox>  
      (required: ###-##-#### form)>br />
      
     <asp:Label id="Label2" runat="server" Width="100px">First Name:</asp:Label>
      <asp:TextBox id="txtFirstName" runat="server" Width="184px"></asp:TextBox><br />
      
      <asp:Label id="Label3" runat="server" Width="100px">Last Name: </asp:Label>
      <asp:TextBox id="txtLastName" runat="server" Width="183px"></asp:TextBox><br />
      
      <asp:Label id="Label4" runat="server" Width="100px">Phone:</asp:Label>
      <asp:TextBox id="txtPhone" runat="server" Width="183px"></asp:TextBox><br />
      
     <asp:Label id="Label5" runat="server" Width="100px">Address:</asp:Label>
    <asp:TextBox id="txtAddress" runat="server" Width="183px"> </asp:TextBox><br />
      
    <asp:Label id="Label6" runat="server" Width="100px">City:</asp:Label>
     <asp:TextBox id="txtCity" runat="server" Width="184px"> </asp:TextBox><br />
      
     <asp:Label id="Label7" runat="server" Width="100px">State:</asp:Label>
      <asp:TextBox id="txtState" runat="server" Width="184px">
<br />      
    <asp:Label id="Label9" runat="server" Width="100px">Zip Code:</asp:Label>
    <asp:TextBox id="txtZip" runat="server" Width="184px"></asp:TextBox>  
      (required: any five digits)<br />
    <br />
      
     <asp:Label id="Label8" runat="server" Width="93px" Height="19px">Contract:</asp:Label> 
     <asp:CheckBox id="chkContract" runat="server"> </asp:CheckBox><br />
   <br />
      
    <asp:Label id="lblResults" runat="server" Width="575px" Height="121px" Font-Bold="True"></asp:Label>
  </div>
 </div>
   </form>
</body>
</html>       
     
        

// Default.aspx.cs //


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;

public partial class Students : System.Web.UI.Page
{
    private string connectionString = WebConfigurationManager.ConnectionStrings["Con"].ConnectionString;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            FillAuthorList();
        }
    }

    private void FillAuthorList()
    {
        lstAuthor.Items.Clear();
        string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors";

        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader;

        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                ListItem newItem = new ListItem();
                newItem.Text = reader["lname"] + ", " + reader["fname"];
                newItem.Value = reader["id"].ToString();
                lstAuthor.Items.Add(newItem);
            }
            reader.Close();
        }
        catch (Exception err)
        {
            lblResults.Text = "Error reading list of names. ";
            lblResults.Text += err.Message;
        }
        finally
        {
            con.Close();
        }
    }

    protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectSQL;
        selectSQL = "SELECT * FROM Authors ";
        selectSQL += "WHERE id='" + lstAuthor.SelectedItem.Value + "'";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader;

        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            reader.Read();

            txtID.Text = reader["id"].ToString();
            txtFirstName.Text = reader["fname"].ToString();
            txtLastName.Text = reader["lname"].ToString();
            txtPhone.Text = reader["phone"].ToString();
            txtAddress.Text = reader["address"].ToString();
            txtCity.Text = reader["city"].ToString();
            txtState.Text = reader["state"].ToString();
            txtZip.Text = reader["zip"].ToString();
            chkContract.Checked = (bool)reader["contract"];
            reader.Close();
            lblResults.Text = "";
        }
        catch (Exception err)
        {
            lblResults.Text = "Error getting author. ";
            lblResults.Text += err.Message;
        }
        finally
        {
            con.Close();
        }

    }
    protected void cmdNew_Click(object sender, EventArgs e)
    {
        txtID.Text = "";
        txtFirstName.Text = "";
        txtLastName.Text = "";
        txtPhone.Text = "";
        txtAddress.Text = "";
        txtCity.Text = "";
        txtState.Text = "";
        txtZip.Text = "";
        chkContract.Checked = false;
        
        lblResults.Text = "Click Insert New to add the completed record.";


    }
    protected void cmdInsert_Click(object sender, EventArgs e)
    {
        if (txtID.Text == "" || txtFirstName.Text == "" || txtLastName.Text == "")
        {
            lblResults.Text = "Records require an ID, first name, and last name.";
            return;
        }
        string insertSQL;
        insertSQL = "INSERT INTO Authors (";
        insertSQL += "id, fname,lname, ";
        insertSQL += "phone, address, city, state, zip, contract) ";
        insertSQL += "VALUES (";
        insertSQL += "@id, @fname, @lname, ";
        insertSQL += "@phone, @address, @city, @state, @zip, @contract)";

        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(insertSQL, con);

        cmd.Parameters.AddWithValue("@id", txtID.Text);
        cmd.Parameters.AddWithValue("@fname", txtFirstName.Text);
        cmd.Parameters.AddWithValue("@lname", txtLastName.Text);
        cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
        cmd.Parameters.AddWithValue("@address", txtAddress.Text);
        cmd.Parameters.AddWithValue("@city", txtCity.Text);
        cmd.Parameters.AddWithValue("@state", txtState.Text);
        cmd.Parameters.AddWithValue("@zip", txtZip.Text);
        cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked));

        int added = 0;
        try
        {
            con.Open();
            added = cmd.ExecuteNonQuery();
            lblResults.Text = added.ToString() + " record inserted.";
        }
        catch (Exception err)
        {
            lblResults.Text = "Error inserting record. ";
            lblResults.Text += err.Message;
        }
        finally
        {
            con.Close();
        }

        if (added > 0)
        {
            FillAuthorList();
        }
    }

    protected void cmdUpdate_Click(object sender, EventArgs e)
    {
        string updateSQL;
        updateSQL = "UPDATE Authors SET ";
        updateSQL += "fname=@fname, lname=@lname, ";
        updateSQL += "phone=@phone, address=@address, city=@city, state=@state, ";
        updateSQL += "zip=@zip, contract=@contract ";
        updateSQL += "WHERE id=@id_original";

        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(updateSQL, con);

        cmd.Parameters.AddWithValue("@fname", txtFirstName.Text);
        cmd.Parameters.AddWithValue("@lname", txtLastName.Text);
        cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
        cmd.Parameters.AddWithValue("@address", txtAddress.Text);
        cmd.Parameters.AddWithValue("@city", txtCity.Text);
        cmd.Parameters.AddWithValue("@state", txtState.Text);
        cmd.Parameters.AddWithValue("@zip", txtZip.Text);
        cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked));
        cmd.Parameters.AddWithValue("@id_original", lstAuthor.SelectedItem.Value);

        int updated = 0;
        try
        {
            con.Open();
            updated = cmd.ExecuteNonQuery();
            lblResults.Text = updated.ToString() + " record updated.";
        }
        catch (Exception err)
        {
            lblResults.Text = "Error updating author. ";
            lblResults.Text += err.Message;
        }
        finally
        {
            con.Close();
        }

        if (updated > 0)
        {
            FillAuthorList();
        }

    }
    protected void cmdDelete_Click(object sender, EventArgs e)
    {
        string deleteSQL;
        deleteSQL = "DELETE FROM Authors ";
        deleteSQL += "WHERE id=@id";

        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(deleteSQL, con);
        cmd.Parameters.AddWithValue("@id ", lstAuthor.SelectedItem.Value);

        int deleted = 0;
        try
        {
            con.Open();
            deleted = cmd.ExecuteNonQuery();
            lblResults.Text = "Record deleted.";
        }
        catch (Exception err)
        {
            lblResults.Text = "Error deleting author. ";
            lblResults.Text += err.Message;
        }
        finally
        {
            con.Close();
        }
        if (deleted > 0)
        {
            FillAuthorList();
        }
    }
}