Thursday, 21 February 2013

Delete Insert update image or with out image with the help of grid view

 edit image








Insert value


Delete value in gride view

This is the code which is i use




using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
public partial class BannerManagement : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
               filldata();
              hope();
        }
        Panel1.Visible = false;
        Panel3.Visible = false;
    }
    SqlDataReader dr;
    SqlCommand cmd;
    protected void Button1_Click(object sender, EventArgs e)
    {
        filldata();
        string f = Path.GetFileName(FileUpload1.PostedFile.FileName);
        FileUpload1.SaveAs(Server.MapPath("images/" + f));
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EatProject"].ToString());
        //SqlConnection con = new SqlConnection("Data Source=MNISH-PC\\SQLEXPRESS;Initial Catalog=Rakesh;Integrated Security=True");
        SqlCommand cmd = new SqlCommand("INSERT INTO ImagesPath (Name,ImagePath,Link,Status)VALUES ('" + TextBox2.Text + "','" + "images/" + f + "','" + TextBox3.Text + "', '" + CheckBox1.Checked + "' )", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
    public void filldata()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EatProject"].ToString());
        //SqlConnection con = new SqlConnection("Data Source=MNISH-PC\\SQLEXPRESS;Initial Catalog=Rakesh;Integrated Security=True");
        con.Open();
        string ret = "select * from ImagesPath";
        cmd = new SqlCommand(ret, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        con.Close();
        TextBox2.Text = "";
        TextBox3.Text = "";
               
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        filldata();
        TextBox2.Text = "";
        TextBox3.Text = "";
        Panel3.Visible = false;
        Panel1.Visible = false;

    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        //Label t = (Label)GridView1.Rows[e.RowIndex].FindControl("lable1");
        int id = (int)GridView1.DataKeys[e.RowIndex].Value;
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EatProject"].ToString());
        //SqlConnection con = new SqlConnection("Data Source=MNISH-PC\\SQLEXPRESS;Initial Catalog=Rakesh;Integrated Security=True");
        con.Open();
        string r = "delete from ImagesPath where ID='" + id + "'";
        cmd = new SqlCommand(r, con);
        cmd.ExecuteNonQuery();
        con.Close();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
       
    }
    public void update()
    {
   
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
       
    }
    public void hope()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EatProject"].ToString());

        SqlCommand cmd = new SqlCommand("Select * from ImagesPath", con);

        SqlDataAdapter da = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet();
        da.Fill(ds);
        DropDownList1.DataTextField = "ID";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataSource = ds.Tables[0];
        DropDownList1.DataBind();
    }
  
    protected void Button5_Click(object sender, EventArgs e)
    {
        Panel3.Visible = true;
        Panel1.Visible = false;
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        filldata();

        if (FileUpload2.HasFile)
        {
            string f = Path.GetFileName(FileUpload2.PostedFile.FileName);
            FileUpload2.SaveAs(Server.MapPath("images/" + f));
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EatProject"].ToString());
            con.Open();
            string str = "update ImagesPath set ImagePath='" + "images/" + f + "' where ID='" + DropDownList1.SelectedItem.Text + "'";
            cmd = new SqlCommand(str, con);
            cmd.ExecuteNonQuery();
            con.Close();

        }
        else
        {
            //string f = Path.GetFileName(FileUpload2.PostedFile.FileName);
            //FileUpload2.SaveAs(Server.MapPath("images/" + f));
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EatProject"].ToString());
            con.Open();
            string str = "update ImagesPath set Name='" + TextBox4.Text + "',Link='" + TextBox5.Text + "',Status='" + DropDownList2.SelectedItem.Text + "' where ID='" + DropDownList1.SelectedItem.Text + "'";
            cmd = new SqlCommand(str, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
  
    protected void Button4_Click2(object sender, EventArgs e)
    {
        Panel3.Visible = true;
    }
   
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        Panel1.Visible = true;
        Panel3.Visible = false;
        //hope();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EatProject"].ToString());

        con.Open();
        string str = "select Name,ImagePath,Link,Status from ImagesPath where ID ='" + DropDownList1.SelectedItem.Text + "'";
        cmd = new SqlCommand(str, con);

        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            TextBox4.Text = dr["Name"].ToString();
            Image2.ImageUrl = "~/" + dr["Imagepath"].ToString();
            TextBox5.Text = dr["Link"].ToString();
            //DropDownList2.SelectedValue = dr["Status"].ToString();
           
        }
        con.Close();
    }
}

Tuesday, 19 February 2013

How to bind dropdownlinst from database (Sqlserver 2005)

    public void fill()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EatProject"].ToString());
        SqlCommand cmd = new SqlCommand("Select * from ImagesPath", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DropDownList2.DataTextField = "Status";
        DropDownList2.DataValueField = "Status";
        DropDownList2.DataSource = ds.Tables[0];
        DropDownList2.DataBind();

    }

Monday, 18 February 2013

How to Save Image Along With Details Into Database in ASP.NET

Here we will create three web pages as Default.aspx, employee.aspx and image.aspx. After inserting the records in the Default.aspx page the control moves to employee.aspx where we can see all the records of the employee with images.

 

Table Creation



table.gif
Default.aspx

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"Inherits="Details_with_photo._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>Untitled Page</title></head>
<body>    <form id="form1" runat="server">    <div>    <h2>Employee Details </h2>     <table>       
        <tr>                <td>                    Name</td>                <td>                    <asp:TextBox id="txtname" RunAt="server"></asp:TextBox>                </td>            </tr>             <tr>                <td>                    Address</td>                <td>                    <asp:TextBox id="txtaddress" RunAt="server"></asp:TextBox>                </td>            </tr>            <tr>                <td>                    Image File </td>                <td>                    <input id="Upload" type="file" runat="server" /></td>            </tr>            </table>            <asp:Button id="btn_insert" RunAt="server"  Text="Insert" onclick="btn_insert_Click"></asp:Button>           
            <asp:label id="lblMessage" runat="server" />    </div>    </form></body>
</html>

Default.aspx.cs
using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Data.SqlClient;namespace Details_with_photo
{
    public partial class _Default : System.Web.UI.Page    {
        string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string str;
        SqlCommand com;       
        protected void btn_insert_Click(object sender, EventArgs e)
        {
            insertdata();
        }
        public void insertdata()
        {
            SqlConnection con = new SqlConnection(strConnString);
            con.Open();
            str = "select count(*)from employee where name='" + txtname.Text + "'";

            com = new SqlCommand(str, con);
            int count = Convert.ToInt32(com.ExecuteScalar());
            con.Close();
            if (count > 0)
            {
                lblMessage.Text = "Sorry! you can't take this username";
            }
            else            {
                lblMessage.Text = "You can take this username";
                con.Open();
                int len = Upload.PostedFile.ContentLength;
                byte[] pic = new byte[len + 1];
                Upload.PostedFile.InputStream.Read(pic, 0, len);
                str = "insert into employee values (@name,@address,@photo)";
                com = new SqlCommand(str, con);
                com.Parameters.AddWithValue("@name", txtname.Text);
                com.Parameters.AddWithValue("@address", txtaddress.Text);
                com.Parameters.AddWithValue("@photo", pic);
                com.ExecuteNonQuery();
                con.Close();
                lblMessage.Text = "Employee Details Inserted Successfully!";
                Response.Redirect("employee.aspx");
                con.Close();
            }
       }
    }
}

employee.aspx


 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="employee.aspx.cs"Inherits="Details_with_photo.employee" %> <!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>Untitled Page</title></head>
<body>    <form id="form1" runat="server">    <div>    <asp:repeater runat="server" id="repeater1">       <headertemplate>          <h2>Details of Employee </h2>       </headertemplate>       <itemtemplate>         <b>Id :</b> <%# Eval("id") %>         <br>         <b>Name   :</b> <%# Eval("name")%>         <br>         <b>Address  :</b> <%# Eval("address")%>         <br>       <img  alt="image" src='image.aspx?id=<%# Eval("id")%>'/>         <hr>       </itemtemplate>     </asp:repeater>    </div>    </form></body>
</html>
employee.aspx.csusing System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Data.SqlClient;namespace Details_with_photo
{
    public partial class employee : System.Web.UI.Page    {
        string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string str;
        SqlCommand com;
        protected void Page_Load(object sender, EventArgs e)
        {
         SqlConnection con = new SqlConnection(strConnString);
         con.Open();
         str = "select id,name,address from employee";
         com = new SqlCommand(str, con);
         SqlDataReader reader;
         reader = com.ExecuteReader();
         repeater1.DataSource = reader;
         repeater1.DataBind();
         con.Close();
        }
    }
}


image.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="image.aspx.cs"Inherits="Details_with_photo.image" %> <!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>Untitled Page</title></head>
<
body>    <form id="form1" runat="server">    <div>   
    </div>    </form>
</body>
</
html>

image.aspx.cs
using System;using System.Collections;using System.Configuration;
using
System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Drawing;using System.Drawing.Imaging;using System.IO;using System.Data.SqlClient;namespace Details_with_photo
{
    public partial class image : System.Web.UI.Page    {
        string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string str;
        SqlCommand com;
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(strConnString);
            con.Open();
            str = "select photo from employee where id = '" + Request.QueryString["id"] + "'";
            com=new SqlCommand(str, con);
            MemoryStream stream = new MemoryStream();
            byte[] image = (byte[])com.ExecuteScalar();
            stream.Write(image, 0, image.Length);
            Bitmap bitmap = new Bitmap(stream);
            Response.ContentType = "image/Jpeg";
            bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
            con.Close();
            stream.Close();
        }
    }
}

Output

table1.gif

Previewing Image in ASP.NET Image Control

Introduction

Recently there are so many people asking in forums how to preview the uploaded image, before saving it to the database. In this article, let us see how to preview the uploaded image in ASP.NET before saving it to the database. Also this will explain how to feed a byte array into an image control. We are going to do that using IhttpHandler.

Using the code

1. Create a new website. Add a File Upload control, a button and an image control.

Aspx code

[code]
<table>
        <tr>
            <td class="style3">
                <asp:Label ID="Label1" runat="server" Text="Photo upload" />
            </td>
            <td class="style4">
                <asp:FileUpload runat="server" ID="PhotoUpload" />
            </td>
            <td class="style4">
                <asp:Button runat="server" ID="btnPhotoPreview" Text="Preview" />
            </td>
            <td class="style1">
                <asp:Image runat="server" ID="ImagePreview" Height="164px" Width="125px" />
            </td>
        </tr>
    </table>

[/code]
2. Now add a button click event for the "btnPhotopreview":

[code]
<asp:Button runat="server" OnClick="btnPreview_Click" ID="btnPhotoPreview" Text="Preview" />[/code]
3. We have to add a handler class to show the image. We will pass a session variable for FileBytes for the upload control. In the new handler class, get the session variable and generate the image.

AspImgCntrl1.jpg

When we add the .ashx file, it will have some code inside it:

[code]
<%@ WebHandler Language="C#" Class="ImageHandler" %> using System;using System.Web;
 
public class ImageHandler : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

[Code]
<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System;
using System.Web;

public class ImageHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
   
    public void ProcessRequest (HttpContext context) {
       //Checking whether the imagebytes session variable have anything else not doing anything

        if ((context.Session["ImageBytes"]) != null)
        {
            byte[] image = (byte[])(context.Session["ImageBytes"]);
            context.Response.ContentType = "image/JPEG";
            context.Response.BinaryWrite(image);
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

[/Code]
4. Now inside the button click in our page, get the filebytes from the FileUpload control and save it in a session variable:
[code]
protected void btnPreview_Click(object sender, EventArgs e)
    {
        Session["ImageBytes"] = PhotoUpload.FileBytes;
        ImagePreview.ImageUrl = "~/ImageHandler.ashx";
    }
[/code]

Now run the application and browse the image and preview it:

AspImgCntrl2.jpg

Binding DropDownList With Database in ASP.NET

Introduction

Today, I have provided an article showing you how to bind a DropDownList with a database and display the bound data in a GridView in ASP.NET. In this article, we create a table in a SQL Server database and bind that table with a DropDownList control. After that we select an item in the DropDownList and match with the database table for the records that match with the database. It will display in the GridView control. To do that we create a connection string object to connect the database with the application and read data from the database using the select command to display data in the DropDownList. All you have to do is implement and hook it up to your requirement or need. First, start Visual Studio .NET and make a new ASP.NET web site using Visual Studio 2010.
Creating Table in SQL Server Database
Now create a table named UserDetail with the columns id, name, country and city. Set the identity property=true for id. The table looks as in the following:
img3.jpg
Now insert some values in this table. The table looks like this:
img4.jpg
Now you have to create a web site.
  • Go to Visual Studio 2010
  • New-> Select a website application
  • Click OK
img5.jpg
Now add a new page to the website.
  • Go to the Solution Explorer
  • Right-click on the Project name
  • Select add new item
  • Add new web page and give it a name
  • Click OK
img6.jpg
Design the page and place the required control in it. Now drag and drop one DropDownList control, Button and GridView control on the form. Let's take a look at a practical example.
.aspx Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click1" Style="height: 26px" />
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#999999"
            BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical">
            <AlternatingRowStyle BackColor="#DCDCDC" />
            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#0000A9" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#000065" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>
   
Now add the following namespaces:
using System.Data.SqlClient;
using System.Data;
 
Now write the connection string to connect to the database:
 
string strConnection = "Data Source=.; uid=sa; pwd=wintellect;database=rohatash;";

Now bind the DropDownList with the database table.

SqlConnection con = new SqlConnection(str);
        string com = "Select * from UserDetail";
        SqlDataAdapter adpt = new SqlDataAdapter(com, con);
        DataTable dt = new DataTable();
        adpt.Fill(dt);
        DropDownList1.DataSource = dt;
        DropDownList1.DataBind();
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();

Now double-click on the Button control and add the following code:

SqlConnection con = new SqlConnection(str);
        SqlCommand cmd = new SqlCommand("select * from UserDetail where id = '" + DropDownList1.SelectedValue + "'", con);
        SqlDataAdapter Adpt = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        Adpt.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
        Label1.Text = "record found";

In the code-behind write the following code:
 
Code-behind

To display data in The GridViw use a DataAdapter object to retrieve the data from the database and place that data into a table.

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;

public partial class Default2 : System.Web.UI.Page
{
    string str = "Data Source=.;uid=sa;pwd=wintellect;database=rohatash";
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(str);
        string com = "Select * from UserDetail";
        SqlDataAdapter adpt = new SqlDataAdapter(com, con);
        DataTable dt = new DataTable();
        adpt.Fill(dt);
        DropDownList1.DataSource = dt;
        DropDownList1.DataBind();
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(str);
        SqlCommand cmd = new SqlCommand("select * from UserDetail where id = '" + DropDownList1.SelectedValue + "'", con);
        SqlDataAdapter Adpt = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        Adpt.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
        Label1.Text = "record found";
    }
}
Now run the application and select the name from DropDownList control and click on the Button.
img1.jpg
Now click on the Button.
img2.jpg