Tuesday, 12 March 2013

PASSING VALUE FROM ONE FORM TO ANOTHER USING C#


This an example of transferring a value from Form1 to Form2..

IN THE FORM1 TYPE THE FOLLOWING CODE


   public partial class Form1 : Form
    {
        public Form1()
        {

            InitializeComponent();
         }

        public static string Sno;  //Declaring a Global variable ID

    private void button1_Click(object sender, EventArgs e)
        {

         Sno = textBox1.Text;    //Type any value in the textbox and click the button
         Form2 f2 = new Form2();
         f2.Show();
        }
      }

IN THE FORM2 TYPE THE FOLLOWING CODE

  public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
         }

  private void Form2_Load(object sender, EventArgs e)
        {

          int v1 =  int.Parse(Form1.Sno);  //Getting the Sno value from Form1
          Label1.Text  = Sno.ToString();  //Displaing the Sno value got from Form1
        }
     }

Sunday, 10 March 2013

HOW TO CALCULATE COLUMN TOTAL IN DATAGRIDVIEW USING C#


// POPULATE THE DATAGRIDVIEW AND THEN INCLUDE THE FOLLOWING CODE IN ANY EVENT.HERE I AM USING IT IN A BUTTON CLICK EVENT.
private void button1_Click(object sender, EventArgs e)
{

int Total = 0;

for (int i = 0; i < dataGridView1.Rows.Count; i++)

{

Total += Convert.ToInt32(dataGridView1.Rows[i].Cells["Columnname"].Value);

}

textBox1.Text = Total.ToString();
}

Wednesday, 30 January 2013

DYNAMIC TOOLTIP FROM DATABASE TO DISPLAY IMAGE DURING MOUSEOVER IN GRIDVIEW

This will display the image and other required fields from database during the mouseover in the gridview column or row using handler(ashx).

IN THE ASPX PAGE
<html>
<head>
<%-- Java script for tooltip display--%>

<script language="javascript" type="text/javascript">
        // Declare General Variables
        var sTooTipId = 'divTooTip';
        var sToolTipPlacement = "Right"; // Right, Left

        // For Hiding tool tip
        function HideTooTipImage() {
            // Get the Div element which was created dynamically on ShowToolTipImage function
            var divTip = document.getElementById(sTooTipId);
            if (divTip) {
                while (divTip.childNodes.length > 0)
                // Remove all child content which are added inside on the Div content
                    divTip.removeChild(divTip.childNodes[0]);
            }
            // Invisible th Div (which removed all child content)
            divTip.style.visibility = "hidden";

        }

        function MoveToolTipImage(event) {

            // Verify if the Div content already present?
            if (document.getElementById(sTooTipId)) {

                // Get the Div content
                var newDiv = document.getElementById(sTooTipId);

                if ('pageX' in event) { // all browsers except IE before version 9
                    var pageX = event.pageX;
                    var pageY = event.pageY;
                }
                else { // IE before version 9
                    var pageX = event.clientX + document.documentElement.scrollLeft;
                    var pageY = event.clientY + document.documentElement.scrollTop;
                }

                if (sToolTipPlacement == "Right")
                    newDiv.style.left = (pageX + 17) + "px";
                else // Left
                    newDiv.style.left = (pageX - (parseInt(newDiv.style.width) + 17)) + "px";

                // Portion of div when hide by browser top
                if ((pageY - (parseInt(newDiv.style.height) + 3)) < 0)
                // Showing below the cursor
                    newDiv.style.top = pageY + "px";
                else
                // Showing above the cursor
                    newDiv.style.top = (pageY - (parseInt(newDiv.style.height) + 3)) + "px";

                // Finally visibling the div which has the image
                newDiv.style.visibility = "visible";
            }
        }
        // For showing tool tip
        function ShowToolTipImage(event, pId) {

            var newDiv = null;

            // Verify if the Div content already present?
            if (!document.getElementById(sTooTipId)) {

                // If not create a new Div element
                newDiv = document.createElement("div");
                // Set the id for the Div element to refer further
                newDiv.setAttribute("id", sTooTipId);

                // Add it to the page
                document.body.appendChild(newDiv);

            }
            else {
                // Get the Div content which was invisible on HideTooTipImage function
                newDiv = document.getElementById(sTooTipId);
            }

            var url = '';

            // Here the pId is the id of the image + a flag
            // (0 - when no image stored on the database or
            // 1 - when image stored on the in database)
            // which indicate whether the image required to show or not
            if (pId.split(",")[1] == 'False ')
                url = "Images/ImageNotAvailable.jpg";
            else
                url = "Imagehandler.ashx?ProductID= " + pId.split(",")[0];
         

            /*// Create an html image element
            var NewImg = document.createElement("img");

            NewImg.setAttribute("src", url);

            //        // Setting the style - if u required set what style you required
            //        NewImg.style.width = "100%";
            //        NewImg.style.height = "100%";
            // Adding the image element to div created
            newDiv.appendChild(NewImg);*/

            var strImageContent =
        '<div class="border_preview"> ' +
        '   <div id="loader_container"> ' +
        '       <div id="loader"> ' +
        '           <div align="center">Loading image preview...</div> ' +
        '           <div id="loader_bg"> ' +
        '               <div id="progress"> </div>' +
        '           </div> ' +
        '       </div> ' +
        '   </div> ' +
        '   <div class="preview_temp_load"> ' +
        '       <img id="previewImage" onload="javascript:remove_loading();" src="' + url + '" border="0" width="100%" height="100%"> ' +
        '   </div> ' +
        '</div>';
            newDiv.innerHTML = strImageContent;

            // Here I am setting the style for example purpose,
            // you can modify what you required.
            // You can even set the css class also.
            newDiv.style.zIndex = 999;
            newDiv.style.width = "200px";
            newDiv.style.height = "80px";

            // Make absolute to the div for floating on the screen.
            newDiv.style.position = "absolute";

            if ('pageX' in event) { // all browsers except IE before version 9
                var pageX = event.pageX;
                var pageY = event.pageY;
            }
            else { // IE before version 9
                var pageX = event.clientX + document.documentElement.scrollLeft;
                var pageY = event.clientY + document.documentElement.scrollTop;
            }


            if (sToolTipPlacement == "Right")
                newDiv.style.left = (pageX + 17) + "px";
            else // Left
                newDiv.style.left = (pageX - (parseInt(newDiv.style.width) + 17)) + "px";

            // Portion of div when hide by browser top
            if ((pageY - (parseInt(newDiv.style.height) + 3)) < 0)
            // Showing below the cursor
                newDiv.style.top = pageY + "px";
            else
            // Showing above the cursor
                newDiv.style.top = (pageY - (parseInt(newDiv.style.height) + 3)) + "px";

            // Finally visibling the div which has the image
            newDiv.style.visibility = "visible";
        }

        var t_id = setInterval(animate, 20);
        var pos = 0;
        var dir = 2;
        var len = 0;

        function animate() {
            var elem = document.getElementById('progress');
            if (elem != null) {
                if (pos == 0) len += dir;
                if (len > 32 || pos > 79) pos += dir;
                if (pos > 79) len -= dir;
                if (pos > 79 && len == 0) pos = 0;
                elem.style.left = pos + "px";
                elem.style.width = len + "px";
            }
        }
        function remove_loading() {
            var targelem = document.getElementById('loader_container');
            targelem.style.display = 'none';
            targelem.style.visibility = 'hidden';
        }
</script>
<%-- CSS for tooltip display--%>
<style type="text/css">
    /*Styles*/
    .border_preview{
            z-index:100;
            position:absolute;
            background: #fff;
            border: 1px solid #444;
            padding:3px;
            width:100%;
    }
    #loader_container {text-align:left;position:absolute;}
    #loader {
        font-family:Tahoma, Helvetica, sans;
        font-size:10px;
        color:#000000;
        background-color:#FFFFFF;
        padding:10px 0 16px 0;
        margin:0 auto;
        display:block;
        width:135px;
        border:1px solid #6A6A6A;
        text-align:left;
        z-index:255;
    }
    #progress {
        height:5px;
        font-size:1px;
        width:1px;
        position:relative;
        top:1px;
        left:10px;
        background-color:#9D9D94
    }
    #loader_bg {
        background-color:#EBEBE4;
        position:relative;
        top:8px;left:8px;height:7px;
        width:113px;font-size:1px
    }
    .title_h2 {
        color:#000;
        text-align: left;
        padding:12px 0 0 18px;
        margin:0;
        font-size:14px;
    }
    .preview_temp_load {
        vertical-align:middle;
        text-align:center;
        padding: 0px;
    }
    .preview_temp_load img{
        vertical-align:middle;
        text-align:center;
    }
</style>
</head>
<body>
<form id="form1" runat="server">
 <%-- using the rescpective handler and girdview binding function bind the gridview --%>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="525px">
   
       <Columns>
            <asp:TemplateField  HeaderText="Model">
                <ItemTemplate>                 
                <img id="imgPhoto" src='<%# "Imagehandler.ashx?ProductID= " + Eval ("ProductID") %> '
                        onmouseover="ShowToolTipImage(event, this.alt)"
                        onmouseout="HideTooTipImage()"
                        onmousemove="MoveToolTipImage(event)"
                        alt="<%# Eval("ProductID") %>,<%# Eval("Pname") %>" 
                        width="50px" height="50px" 
                        title="<%# Eval("Pname") %>" 
                        style="cursor:hand" />
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Product">
                <ItemTemplate>
                   <asp:Label ID="lblname" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Pname") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="u/p(र)">
                <ItemTemplate>
                     <asp:Label ID="lbluprice" runat="server"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
      
        </Columns>
        </asp:GridView>
</form>
<body>
</html>

Thursday, 20 December 2012

SEARCH TEXTBOX FOR GRIDVIEW USING JQUERY

 IN THE ASPX PAGE
<html>
<head runat="server">
<%-- Jquery link  --%>  
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<%-- Script  --%>   
 <script type="text/javascript">
     $(document).ready(function () {
         $('#txtcatsearch').keyup(function (event) {
             var searchKey = $(this).val().toLowerCase();
<%--3 is the column name in the gridview used to search  --%>   
             $("#catgridview tr td:nth-child(3)").each(function () {
                 var cellText = $(this).text().toLowerCase();
                 if (cellText.indexOf(searchKey) >= 0) {
                     $(this).parent().show();
                 }
                 else {
                     $(this).parent().hide();
                 }
             });
         });
     });
 </script>
</head>
<body>
<asp:TextBox ID="txtcatsearch" runat="server"></asp:TextBox>
 <asp:GridView ID="catgridview" runat="server">  
 </asp:GridView><%-- Fill the gridview using either databind in the cs page or by anyother type  --%>
</body>
</html>

Thursday, 6 December 2012

DROPDOWN LIST BINDING AND SELECTED INDEX CHANGE EVENT

CREATE A TABLE

CREATE TABLE Nametable
(
    [Nameid] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL
)

IN THE ASPX PAGE

   <form id="form1" runat="server">
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
        onselectedindexchanged="DropDownList1_SelectedIndexChanged" >
    </asp:DropDownList>
    <br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
   </form>

IN THE ASPX.CS PAGE (dropdown binding and selected index change event)
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class Default7 : System.Web.UI.Page
{
    //Configuring the connection string and calling it from web.config
    static string sathya = ConfigurationManager.ConnectionStrings["SQLCON"].ConnectionString;
    SqlConnection satcon = new SqlConnection(sathya);
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            binddrop();
        }
    }
//Binding the dropdown list with the sql database
    private void binddrop()
    {
        satcon.Open();
        da = new SqlDataAdapter("select * from Nametable",satcon);
        DataSet ds = new DataSet();
        da.Fill(ds);
        satcon.Close();
        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Nameid";
        DropDownList1.DataBind();
    }
//SelectedIndexChanged event displaying the number according the name selected in the dropdown list
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int Nameid = Convert.ToInt32(DropDownList1.SelectedValue);        satcon.Open();
        SqlCommand cmd = new SqlCommand("select * from Mobiletable where Nameid=" + Nameid , satcon)
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        TextBox1.Text = dr["Number"].ToString(); //Displaying the output filed "Number" in the texbox
        satcon.Close();
       }
}

Wednesday, 28 November 2012

POP UP DIV USING JAVASCRIPT

 <html>
<head>
<%-- JAVASCRIPT CODING  --%>  
 <script type="text/javascript" >
            function openpopup(id) {
                //Calculate Page width and height
                var pageWidth = window.innerWidth;
                var pageHeight = window.innerHeight;
                if (typeof pageWidth != "number") {
                    if (document.compatMode == "CSS1Compat") {
                        pageWidth = document.documentElement.clientWidth;
                        pageHeight = document.documentElement.clientHeight;
                    } else {
                        pageWidth = document.body.clientWidth;
                        pageHeight = document.body.clientHeight;
                    }
                }
                //Make the background div tag visible...
                var divbg = document.getElementById('bg');
                divbg.style.visibility = "visible";

                var divobj = document.getElementById(id);
                divobj.style.visibility = "visible";
                if (navigator.appName == "Microsoft Internet Explorer")
                    computedStyle = divobj.currentStyle;
                else computedStyle = document.defaultView.getComputedStyle(divobj, null);
                //Get Div width and height from StyleSheet
                var divWidth = computedStyle.width.replace('px', '');
                var divHeight = computedStyle.height.replace('px', '');
                var divLeft = (pageWidth - divWidth) / 2;
                var divTop = (pageHeight - divHeight) / 2;
                //Set Left and top coordinates for the div tag
                divobj.style.left = divLeft + "px";
                divobj.style.top = divTop + "px";
                //Put a Close button for closing the popped up Div tag
                if (divobj.innerHTML.indexOf("closepopup('" + id + "')") < 0)
                    divobj.innerHTML = "<a href=\"#\" onclick=\"closepopup('" + id + "')\"><span  class=\"close_button\">X</span></a>" + divobj.innerHTML;
            }
            function closepopup(id) {
                var divbg = document.getElementById('bg');
                divbg.style.visibility = "hidden";
                var divobj = document.getElementById(id);
                divobj.style.visibility = "hidden";
            }
</script>

 <%-- CSS CODING  --%>  
 <style type="text/css">
.popup {
      background-color: #DDD;
      height: 600px; width: 500px;
      border: 5px solid #666;
      position: absolute; visibility: hidden;
      font-family: Verdana, Geneva, sans-serif;
      font-size: small; text-align: justify;
      padding: 5px; overflow: auto;
      z-index: 999;
}
.popup_bg {
      position: absolute;
      visibility: hidden;
      height: 100%; width: 100%;
      left: 0px; top: 0px;
      filter: alpha(opacity=70); /* for IE */
      opacity: 0.7; /* CSS3 standard */
      background-color: #999;
      z-index: 1;
}
.close_button {
      font-family: Verdana, Geneva, sans-serif;
      font-size: small; font-weight: bold;
      float: right; color: #666;
      display: block; text-decoration: none;
      border: 2px solid #666;
      padding: 0px 3px 0px 3px;
}
body { margin: 0px; }
</style>
</head>
<body>
<%--CALLING THE OPENPOPUP FUNCTION  --%>
 <a href = "#" onclick="openpopup('popup1')"> CLICK HERE TO OPEN POPUP DIV </a>
 <div id="popup1" class="popup">
    HI, DUDE...
    WELCOME TO OUR POP UP DIV
 </div>
<div id="bg" class="popup_bg"></div> 
</body>
</html>

RETRIEVING THE IMAGE FROM DATABASE AND DISPLAYING IN DATALIST

CREATE TABLE

CREATE TABLE Tablename
(
[ImageID] [int] IDENTITY(1,1) NOT NULL,
[Images] [image] NULL,
[ImageName] [varchar](max) NULL,
)

IN THE ASPX

<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" DataKeyField="ImageID" CellPadding="15" Width="500px">
       <ItemTemplate>
                <div>
                      <asp:Image ID ="img" Width ="120px" Height="120px"  runat="server" 
ImageUrl ='<%#   "Handler.ashx?ImageID= " + Eval ("ImageID") %> '></asp:Image>
               </div>
</br>
                <div>
                   <asp:Label ID ="lblName" ForeColor="#FFFFFF"  runat="server"
Text ='<%# Eval ("ImageName") %>'></asp:Label>
 <br />
       </ItemTemplate>
</asp:DataList>

IN THE HANDLER PAGE 

Add New Item -> Select Generic handler -> Add the below coding in the Handler.ashx

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public class Handler : IHttpHandler {
    static string constr = ConfigurationManager.ConnectionStrings["addname"].ConnectionString;
    SqlConnection con = new SqlConnection(constr); //Configuring using connection string from the  webconfig
    
    public void ProcessRequest (HttpContext context)   
    {
        string imgID = context.Request.QueryString["ImageID"].ToString();
        SqlCommand cmd = new SqlCommand("select * from Tablename where ImageID=" + imgID, con);
        con.Open();
        SqlDataReader Dr = cmd.ExecuteReader();
        Dr.Read();    
        context.Response.BinaryWrite((byte[]) Dr["Images"]);
        con.Close();
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

IN THE ASPX.CS

//These namespaces should be included
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class Default : System.Web.UI.Page
{
    static string constr = ConfigurationManager.ConnectionStrings["giricon"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);//Calling connection string from the web.config
    SqlDataAdapter adp = new SqlDataAdapter();
    DataTable dt = new DataTable();
 protected void Page_Load(object sender, EventArgs e)
    {
     if (!Page.IsPostBack)
        {
           binding();
        }
    }
 private void binding()
    {
        adp = new SqlDataAdapter("Select * from tablename", con);
        adp.Fill(dt);
        adp.Dispose();
        DataList1.DataSource = dt;
        DataList1.DataBind();
    }
}
back to top