JEYAGANESH

JEYAGANESH
Software Developer

Tuesday, 19 June 2012

how to insert images into database and how to retrieve and bind images to gridview using asp.net (or) save and Retrieve images from database using asp.net

Introduction

Here I will explain how insert and retrieve images from database and how to bind images to gridview using asp.net
TableName : image_upload

Column Name
Data Type
Allow Nulls
Id
Int
Yes
imagesimageYes

After that Design your aspx page like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Image
        <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>


<div>
<asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
<Columns>
<asp:BoundField HeaderText = "id" DataField="id" />
<asp:TemplateField HeaderText="Image Id">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("id") %>' Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>

    </form>
</body>
</html>



web.config
------------


<connectionStrings>
        <add name="mmConnectionString" connectionString="server=SAMSUNG\SQLEXPRESS;Integrated Security=true;database=sample;" providerName="System.Data.SqlClient"/>
    </connectionStrings>



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;
namespace WebApplication4
{
   
    public partial class _Default : System.Web.UI.Page
    {
        string strcon = ConfigurationManager.ConnectionStrings["mmConnectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
           

if (!IsPostBack)
{
BindGridData();
}
        }
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT images,ID from [Image]", connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                int image_length = FileUpload1.PostedFile.ContentLength;
                byte[] imgtype=new byte[image_length];
                HttpPostedFile img = FileUpload1.PostedFile;
                img.InputStream.Read(imgtype, 0, image_length);
                SqlConnection con = new SqlConnection(strcon);
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "insert into image_upload values(1,'"+imgtype+"')";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                int count = cmd.ExecuteNonQuery();
                con.Close();
                if (count == 1)
                {

                     BindGridData();
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "alert('image inserted successfully')", true);
                }
            }
        }
    }
}





handler.ashx.cs
---------------


string strcon = ConfigurationManager.AppSettings["mmConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Images from image_upload where ID=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}

Bind XML saving data to DataGridView with Delete and Edit Options in Windows forms applicatons using C# || Insert,Edit,Delete data into XML with DataGridView in Windows forms using C#




n this article am showing following steps:
  1. Save data into XML file .
  2. Retrieve data from XML file and bind that data to DataGridview.
  3. Add two EDIT and DELETE columns to DataGridView.
  4. Write edit,delete coding in dataGridView1_CellContentDoubleClick.
Save data into XML file:
For using XML add the following namespace:
                  using System.Xml;
Write the following code in Save button Click:
private void btnSave_Click(object sender, EventArgs e)
        {
       
                  string path = "AccountDetails.xml";
                XmlDocument doc = new XmlDocument();
                ////If there is no current file, then create a new one
                if (!System.IO.File.Exists(path))
                {
                    //Create neccessary nodes
                    XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
                    XmlComment comment = doc.CreateComment("This is an XML Generated File");
}
                else //If there is already a file
                {
                    //    //Load the XML File
                    doc.Load(path);
}
                    //Get the root element
                    XmlElement root = doc.CreateElement("BankAccount_Details");
                    XmlElement Subroot = doc.CreateElement("BankAccount");
                    XmlElement BankName = doc.CreateElement("BankName");
                    XmlElement AccountNumber = doc.CreateElement("AccountNumber");
                    XmlElement BankType = doc.CreateElement("BankType");
                    XmlElement Balance = doc.CreateElement("Balance");
                    //Add the values for each nodes
                    BankName.InnerText = comboBox1.SelectedItem.ToString();
                    AccountNumber.InnerText = txtAccNumber.Text;
                    if (rbtnCurrent.Checked)
                        BankType.InnerText = rbtnCurrent.Text;
                    else if (rbtnSaving.Checked)
                        BankType.InnerText = rbtnSaving.Text;
                    else
                        BankType.InnerText = rbtnOther.Text;
                    Balance.InnerText = txtBalance.Text;
                    //Construct the document
                    doc.AppendChild(declaration);
                    doc.AppendChild(comment);
                    doc.AppendChild(root);
                    root.AppendChild(Subroot);
                    Subroot.AppendChild(BankName);
                    Subroot.AppendChild(AccountNumber);
                    Subroot.AppendChild(BankType);
                    Subroot.AppendChild(Balance);
                    doc.Save(path);
                //Show  message
                MessageBox.Show("Records added Successfully");
                //Reset text fields for new input
                txtBalance.Text = String.Empty;
                txtAccNumber.Text = String.Empty;
                comboBox1.SelectedIndex = 0;
                                //To show added record in Gridview call LoadGrid() method which I show below
LoadGrid();
}
 

Retrieve data from XML file and bind  to DataGridview:
For  retrieve XML data  and bind to Gridview call the following method:
protected void LoadGrid()
        {
            DataSet xmlds = new DataSet();
            string path = "AccountDetails.xml";
            if (System.IO.File.Exists(path))
            {
                xmlds.ReadXml(path);
                if (xmlds.Tables.Count > 0)
                {
                    dataGridView1.DataSource = xmlds.Tables[0].DefaultView;
                   
                }
            }
       
        }
Call the above method in form page load also
private void Account_Details_Load(object sender, EventArgs e)
        {
            LoadGrid();
        }
       
Add  EDIT and DELETE columns to DataGridView:
For Editing and Deleting add two columns to DataGridView with Suitable Images. I am adding Delete Image in 1st  column and Edit in 2nd column.
For deleting and editing am taking account number as a parameter.
write the following code in dataGridView1_CellContentDoubleClick event:
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
              
//For Deleting following code
                if (e.ColumnIndex == 0)
                {
                    DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                    string acnum = row.Cells[3].Value.ToString();
                    string path = "AccountDetails.xml";
                    XmlDocument doc = new XmlDocument();
                    doc.Load(path);
                    XmlNode node = doc.SelectSingleNode("/BankAccount_Details/BankAccount[AccountNumber='" + acnum + "']");
                    node.ParentNode.RemoveChild(node);
                    doc.Save(path);
                    MessageBox.Show("Selected Record Deleted Successfully");
                }  
                  
          
          //For Editing following code
                if (e.ColumnIndex == 1)
                {
                    DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                    int acnum = Convert.ToInt32(row.Cells[3].Value);
                    string path = "AccountDetails.xml";
                    XmlDocument doc = new XmlDocument();
                    doc.Load(path);
                    XmlNode node = doc.SelectSingleNode("/BankAccount_Details/BankAccount[AccountNumber='" + acnum + "']");
                    node.ParentNode.RemoveChild(node);
                    doc.Save(path);
                  
                    
                    ////If there is no current file, then create a new one
                    if (!System.IO.File.Exists(path))
                    {
                        //Create neccessary nodes
                         XmlDeclaration declaration  = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
                     XmlComment comment = doc.CreateComment("This is an XML Generated File");
                       
                        doc.AppendChild(declaration);
                        doc.AppendChild(comment);
                    }
    //If there is already a file
                         else 
                        {
                        //    //Load the XML File
                        doc.Load(path);
                        }
                        XmlElement root = doc.CreateElement("BankAccount_Details");
                        XmlElement Subroot = doc.CreateElement("BankAccount");
                        XmlElement BankName = doc.CreateElement("BankName");
                        XmlElement AccountNumber = doc.CreateElement("AccountNumber");
                        XmlElement BankType = doc.CreateElement("BankType");
                        XmlElement Balance = doc.CreateElement("Balance");
                        //Add the values for each nodes
                        BankName.InnerText = row.Cells[2].ToString();
                        AccountNumber.InnerText = row.Cells[3].ToString();
                        BankType.InnerText = row.Cells[4].ToString();
                        Balance.InnerText = row.Cells[5].ToString();
                        //Construct the document
                        doc.AppendChild(root);
                        root.AppendChild(Subroot);
                        Subroot.AppendChild(BankName);
                        Subroot.AppendChild(AccountNumber);
                        Subroot.AppendChild(BankType);
                        Subroot.AppendChild(Balance);
                        doc.Save(path);
                        MessageBox.Show("Selected Record Edited Successfully");
                    }
                                        
                                         LoadGrid();                
                }
                   
           
                  
                }
       
Then run your application and see output :
 
 
 

Saturday, 16 June 2012

Open/Close or Show/Hide Ajax Modalpopupextender using JavaScript in asp.net


In previous posts I explained some of the samples relating to Ajax modalpopupextender. During the time whenever I worked on to prepare samples for Ajax modalpopupextender I got requirement like close the modalpopupextender whenever I click on close icon for that more check this example Ajax Confirmation box. Generally in Ajax modalpopupextender we will set two properties TargetControlID and CancelControlID like Ex: TargetControlID="btnShowPopup" CancelControlID="btnNo" Here whenever we click on btnShowPopup button control modalpopupextender will show popup and when we click on btnNo button it will close the popup. Now I want to open popup and close popup whenever click on other button controls also in that case what we can do? By using JavaScript $find() function we can show or hide modalpopupextender easily. JavaScript Functions will be like this Here 'ModalPopupExtender1' is our modalpopupextender id. Our Sample Page will be like this Untitled Page