Share Blog

Tuesday, January 27, 2015

How to Bind,save,edit,update,delete records from DataList in asp.net(C#)



Create Table
create table news_info(imageid int primary key identity(1,1)
                        ,Title varchar(100),
                        name varchar(100),
                        discription varchar(max),
                         ImagePath varchar(max))

 

Create Store Procedure
-----create procedure for Insert image-----------
CREATE PROCEDURE Savenews_Sp
                (
                                @Title varchar(100),
                                @name varchar(100),
                                @discription varchar(max),
                                @ImagePath varchar(500)
                )            
AS
BEGIN
    insert into news_info(Title,name,discription,ImagePath)
    values (@Title,@name,@discription,@ImagePath)
END
    ------create procedure for show image-----------
    create PROCEDURE shownews_Sp
AS
BEGIN
                select * from news_info
END
 ------create procedure for update image-----------
Alter PROCEDURE updatenews_Sp
                (               @imageid int,
                                @Title varchar(100),
                                @name varchar(100),
                                @discription varchar(max)
                           
                )            
AS
BEGIN
   update news_info set Title=@Title,name=@name,discription=@discription where imageid=@imageid
  
END
------create procedure for delete image--------------
CREATE PROCEDURE Deletenews_Sp
                (
                                @imageid int
                )            
AS
BEGIN
                delete from news_info where imageid=@imageid

END





edit_update_delete_show_image.aspx

<% Page Language="C#"AutoEventWireup="true" CodeFile="edit_update_delete_show_image.aspx.cs" Inherits="edit_update_delete_show_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></title>
</head>
<body>
    <form id="form1" runat="server">
   <fieldset style="width:550px">
    <legend>Bind,Save,Edit,Update,Delete in DataList</legend>
    <table style="width:100%">
    <tr><td width="25%">Title</td><td>
        <asp:TextBox ID="txtTitle" runat="server"></asp:TextBox></td></tr>
    <tr><td>Name</td><td>
        <asp:TextBox ID="txtname" runat="server"></asp:TextBox></td></tr>
    <tr><td>Discription</td><td>
        <asp:TextBox ID="txtdiscription" runat="server"></asp:TextBox></td></tr>
  
        <tr><td>Upload Image</td><td>
            <asp:FileUpload ID="FileUpload1" runat="server" /></td></tr>
    <tr><td></td>
       <td> <asp:Button ID="btnSubmit" runat="server" Text="Save"
            onclick="btnSubmit_Click" /></td></tr>
    </table>
   
     <asp:DataList ID="Datalist_news" runat="server" RepeatColumns="2"
            oncancelcommand="dtlNews_CancelCommand" oneditcommand="dtlNews_EditCommand"
            onupdatecommand="dtlNews_UpdateCommand"  
           ondeletecommand="dtlNews_DeleteCommand" DataKeyField="imageid"
            BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px"
            CellPadding="4" GridLines="Both"
           onselectedindexchanged="btnSubmit_Click">
            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
            <ItemStyle BackColor="White" ForeColor="#003399" />
        <ItemTemplate>
        <table>
        <tr>
        <td><img src='<%#Eval("ImagePath") %>' width="90px" height="90px" alt="Book Image" /></td><td><b>Title : </b><%#Eval("Title")%><br />
        <b>Name : </b><%#Eval("name")%><br />
        <b>Discription : </b><%#Eval("discription")%><br />
       
        </tr>
        </table>
        <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit"></asp:LinkButton>
        <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete selected records')"></asp:LinkButton>
        </ItemTemplate>
        <EditItemTemplate>      
        <b>Title : </b><asp:TextBox id="txtEditTitle" runat="server" Text='<%#Eval("Title") %>'></asp:TextBox><br />
        <b>Name : </b><asp:TextBox id="txtEditname" runat="server" Text='<%#Eval("name") %>'></asp:TextBox><br />
        <b>Discription : </b><asp:TextBox id="txtEditdiscription" runat="server" Text='<%#Eval("discription") %>'></asp:TextBox><br />
      
         <asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update"></asp:LinkButton>
        <asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel"></asp:LinkButton>    
        </EditItemTemplate>
            <SelectedItemStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        </asp:DataList>  
         </fieldset>
    </form>
</body>
</html>


edit_update_delete_show_image.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 edit_update_delete_show_image : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindDataList();
        }
    }
    protected void BindDataList()
    {
        SqlDataAdapter adp = new SqlDataAdapter();
        DataTable dt = new DataTable();
        try
        {
            adp = new SqlDataAdapter("shownews_Sp", con);
            adp.SelectCommand.CommandType = CommandType.StoredProcedure;
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
               Datalist_news.DataSource = dt;
               Datalist_news.DataBind();
            }
            else
            {
                Datalist_news.DataSource = dt;
                Datalist_news.DataBind();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! Error occured : " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            con.Close();
            dt.Clear();
            dt.Dispose();
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string filePath = string.Empty;
        SqlCommand cmd = new SqlCommand();
        string ImgPath = string.Empty;
        string DbImgPath = string.Empty;
        try
        {
            cmd = new SqlCommand("SaveNews_Sp", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Title", txtTitle.Text.Trim());
            cmd.Parameters.AddWithValue("@name", txtname.Text.Trim());
            cmd.Parameters.AddWithValue("@discription", txtdiscription.Text.Trim());
         
            if (FileUpload1.HasFile)
            {
                ImgPath = (Server.MapPath("~/BookImages/") + Guid.NewGuid() + FileUpload1.FileName);
                FileUpload1.SaveAs(ImgPath);

                DbImgPath = ImgPath.Substring(ImgPath.LastIndexOf("\\"));
                DbImgPath = DbImgPath.Insert(0, "BookImages");
                cmd.Parameters.AddWithValue("@ImagePath", DbImgPath);
            }
            else
            {
                cmd.Parameters.AddWithValue("@ImagePath", string.Empty);
            }

            con.Open();
            cmd.ExecuteNonQuery();
            BindDataList();
            ClearControls();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Book record has been saved successfully');", true);

        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! Error occured : " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            con.Close();
            cmd.Dispose();
        }
    }


    protected void dtlNews_CancelCommand(object source, DataListCommandEventArgs e)
    {
        Datalist_news.EditItemIndex = -1;
        BindDataList();
    }
    protected void dtlNews_DeleteCommand(object source, DataListCommandEventArgs e)
    {
        Int32 bookId;
        SqlCommand cmd = new SqlCommand();
        try
        {
            bookId = Convert.ToInt32(Datalist_news.DataKeys[e.Item.ItemIndex]);
            cmd = new SqlCommand("Deletenews_Sp", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@imageid", bookId);
            con.Open();
            cmd.ExecuteNonQuery();
            BindDataList();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Book record has been deleted successfully');", true);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! Error occured : " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            con.Close();
            cmd.Dispose();
        }
    }
    protected void dtlNews_EditCommand(object source, DataListCommandEventArgs e)
    {
        Datalist_news.EditItemIndex = e.Item.ItemIndex;
        BindDataList();
    }
    protected void dtlNews_UpdateCommand(object source, DataListCommandEventArgs e)
    {
        Int32 imageid;
        string tit = string.Empty;
        string name = string.Empty;
        string dis = string.Empty;
        SqlCommand cmd = new SqlCommand();
        try
        {
            tit = ((TextBox)(e.Item.FindControl("txtEditTitle"))).Text;
            name = ((TextBox)(e.Item.FindControl("txtEditname"))).Text;
            dis = ((TextBox)(e.Item.FindControl("txtEditdiscription"))).Text;
          
            imageid = Convert.ToInt32(Datalist_news.DataKeys[e.Item.ItemIndex]);
            con.Open();
            cmd = new SqlCommand("updatenews_Sp", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@imageid", imageid);
            cmd.Parameters.AddWithValue("@Title", tit);
            cmd.Parameters.AddWithValue("@name", name);
            cmd.Parameters.AddWithValue("@discription",dis);
            cmd.ExecuteNonQuery();
            Datalist_news.EditItemIndex = -1;
            BindDataList();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Book record has been updated successfully');", true);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! Error occured : " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            cmd.Dispose();
            con.Close();
            tit = string.Empty;
           name = string.Empty;
            dis = string.Empty;
        }
    }
    private void ClearControls()
    {
        txtTitle.Text = string.Empty;
        txtname.Text = string.Empty;
        txtdiscription.Text = string.Empty;
     
        txtTitle.Focus();
    }
}




Friday, January 23, 2015

How to Upload Video file,Audio file,Image in database Using Asp.net

First Create Table

Create table Videos
(
 ID Int identity,
Video varbinary(MAX),
Video_Name nvarchar(50),
Video_Size bigint
)

1.      Open Vs 2010 –> File –> New –> Website.
2.      select –> C#
3.      Select ‘Asp.Net Empty Website’ –> name – ‘Video’.

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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
       
     
   
    </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.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    byte[] buffer;
    SqlConnection con;
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile && FileUpload1.PostedFile != null
            && FileUpload1.PostedFile.FileName != "")
        {
            HttpPostedFile file = FileUpload1.PostedFile;
            //retrieve the HttpPostedFile object

            buffer = new byte[file.ContentLength];
            int bytesReaded = file.InputStream.Read(buffer, 0,
                              FileUpload1.PostedFile.ContentLength);
             if (bytesReaded > 0)
            {
                try
                {
                  SqlConnection con = new SqlConnection("Data Source=ABC;Initial Catalog=db;Integrated Security=True");
                    SqlCommand cmd = new SqlCommand
                    ("INSERT INTO Videos (Video, Video_Name, Video_Size)" +
                     " VALUES (@video, @videoName, @videoSize)", con);
                    cmd.Parameters.Add("@video",
                        SqlDbType.VarBinary, buffer.Length).Value = buffer;
                    cmd.Parameters.Add("@videoName",
                        SqlDbType.NVarChar).Value = FileUpload1.FileName;
                    cmd.Parameters.Add("@videoSize",
                        SqlDbType.BigInt).Value = file.ContentLength;
                    using (con)
                    {
                        con.Open();
                        int i = cmd.ExecuteNonQuery();
                        Label1.Text = "uploaded, " + i.ToString();
                    }
                }
                catch (Exception ex)
                {
                    Label1.Text = ex.Message.ToString();
                }
            }

        }
        else
        {
            Label1.Text = "Choose a valid video file";
        }
    }

 
}

Wednesday, January 21, 2015

Facebook Like Box in HTML




Write Code In <Body><Body> Tag

Include the JavaScript on your page once, ideally right after the opening <body> tag.

<div id="fb-root"></div>
<script>    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";
        fjs.parentNode.insertBefore(js, fjs);
    } (document, 'script', 'facebook-jssdk'));</script>


Place the code for your plugin wherever you want the plugin to appear on your page.

<div class="fb-like-box" data-href="https://www.facebook.com/FacebookDevelopers" data-colorscheme="light" data-show-faces="true" data-header="true" data-stream="false" data-show-border="true"></div>












Monday, October 27, 2014

How to make Contact Page 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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table border = "0" style="width: 409px">
    <tr>
        <td>
            <asp:Label ID="Label1" runat="server" Text="Name*"></asp:Label><br />
        </td>
        <td>
            <asp:TextBox ID="txtName" runat="server" ValidationGroup = "contact"></asp:TextBox><br />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
             ControlToValidate = "txtName"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="Label2" runat="server" Text="Subject*"></asp:Label><br />
        </td>
        <td>
            <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox><br />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*"
             ControlToValidate = "txtSubject"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="Label3" runat="server" Text="Email*"></asp:Label><br />
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
            <asp:RegularExpressionValidator id="valRegEx" runat="server"
            ControlToValidate="txtEmail"
            ValidationExpression=".*@.*\..*"
            ErrorMessage="*Invalid Email address."
            display="dynamic">
            </asp:RegularExpressionValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*"
            ControlToValidate = "txtEmail"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td valign = "top" >
            <asp:Label ID="Label4" runat="server" Text="Body*"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtBody" runat="server" TextMode = "MultiLine" ></asp:TextBox><br />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*"
            ControlToValidate = "txtBody"></asp:RequiredFieldValidator>
        </td>
    </tr>
     <tr>
        <td></td>
        <td>
            <asp:FileUpload ID="FileUpload1" runat="server" />
       </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
       </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <asp:Label ID="lblMessage" runat="server" Text="" ForeColor = "Green"></asp:Label>
       </td>
    </tr>
</table>
    </div>
    </form>
</body>
</html>

default.aspx.cs Code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        MailMessage mm = new MailMessage(txtEmail.Text,"tajpg2013@gmail.com");
        mm.Subject = txtSubject.Text;
        mm.Body = "Name: " + txtName.Text + "<br /><br />Email: " + txtEmail.Text + "<br />" + txtBody.Text;
        if (FileUpload1.HasFile)
        {
            string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
            mm.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileName));
        }
        mm.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
        NetworkCred.UserName = "tajpg2013@gmail.com";
        NetworkCred.Password = "*******";
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
        lblMessage.Text = "Meassage Sent SucessFully.";
    }
}