Saturday, 24 November 2012

Insert , Update and Delete without writing any code in GridView in Asp.Net.


Introduction:-

It is possible to insert , update and delete operation performed in GridView in asp.net  without writing any code in .cs page. If you use SqlDataSoucreId , then it is possible.
When you drag and drop a GridView on web page , click on gridview  , a rectangular box will appear at the top right corner . Click on this , select new  datasource. I have Already explain about sqlDatasourceid. Now go to property of gridview set true to AutoGenerateEditButton and AutoGenerateDeleteButton. Write the update and delete code inside the sqldatasourceid control . Follow the code as given Below.

GridView.aspx:-
<!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:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            AutoGenerateEditButton="True" DataSourceID="SqlDataSource1"
            AllowSorting="True" AutoGenerateDeleteButton="True">
            <Columns>
                <asp:BoundField DataField="user_name" HeaderText="user_name"
                    SortExpression="user_name" ReadOnly="true" />
                <asp:BoundField DataField="password" HeaderText="password"
                    SortExpression="password" ReadOnly="true" />
                <asp:BoundField DataField="country" HeaderText="country"
                    SortExpression="country" />
                <asp:BoundField DataField="email" HeaderText="email" SortExpression="email" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:modiConnectionString %>"
            SelectCommand="SELECT [user_name], [password], [country], [email] FROM [user_registration]"
              UpdateCommand="Update user_registration set country=@country, email=@email where user_name=@user_name"
               DeleteCommand="Delete user_registration where user_name=@user_name">
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Run the code and test the code.
If any problem regarding this post feel free to contact me or comment the post.

Friday, 23 November 2012

FormView Control in Asp.Net 4.0 using C#.


Introduction:

FormView control display only single record in a table at a time retrieved from datasource. Template are used to display and edit the data value in a FormView control. When multiple records are retieved from the datasorce then paging is usd to view all the records. It supports basic functions like select ,edit and deleting data records.
Drag and drop a FormView Control on your web page. Click on fromview control , you will see at the top right corner there is rectangular box , click on this box -> choose data source  from the drop down list -> select new data source . See the figure given below..


After this choose SqlDataSource as shown in the figure.

After it will open Configure data source window. Select your connection from the drop down list, if connection is not available then click on new connection option. To countinue ,click on the next button. In the next screen , pass the sql query to the ‘Configure the select statement ‘ screen as shown in the figure below.


Click Finish Button. This will automatically add the sqlDataSuorce control to the web page.
If you want show all data in Form View then Check the EnablePaging CheckBox as shown in the figure which is given below.


FormView.aspx:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FormView.aspx.cs" Inherits="FormView" %>

<!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:FormView ID="FormView1" runat="server" AllowPaging="True"
            DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">
            <EditItemTemplate>
                EmployeeID:
                <asp:Label ID="EmployeeIDLabel1" runat="server"
                    Text='<%# Eval("EmployeeID") %>' />
                <br />
                Name:
                <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
                <br />
                Title:
                <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>' />
                <br />
                BirthDate:
                <asp:TextBox ID="BirthDateTextBox" runat="server"
                    Text='<%# Bind("BirthDate") %>' />
                <br />
                MaritalStatus:
                <asp:TextBox ID="MaritalStatusTextBox" runat="server"
                    Text='<%# Bind("MaritalStatus") %>' />
                <br />
                Gender:
                <asp:TextBox ID="GenderTextBox" runat="server" Text='<%# Bind("Gender") %>' />
                <br />
                HireDate:
                <asp:TextBox ID="HireDateTextBox" runat="server"
                    Text='<%# Bind("HireDate") %>' />
                <br />
                <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
                    CommandName="Update" Text="Update" />
                &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server"
                    CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </EditItemTemplate>
            <InsertItemTemplate>
                Name:
                <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
                <br />
                Title:
                <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>' />
                <br />
                BirthDate:
                <asp:TextBox ID="BirthDateTextBox" runat="server"
                    Text='<%# Bind("BirthDate") %>' />
                <br />
                MaritalStatus:
                <asp:TextBox ID="MaritalStatusTextBox" runat="server"
                    Text='<%# Bind("MaritalStatus") %>' />
                <br />
                Gender:
                <asp:TextBox ID="GenderTextBox" runat="server" Text='<%# Bind("Gender") %>' />
                <br />
                HireDate:
                <asp:TextBox ID="HireDateTextBox" runat="server"
                    Text='<%# Bind("HireDate") %>' />
                <br />
                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
                    CommandName="Insert" Text="Insert" />
                &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server"
                    CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </InsertItemTemplate>
            <ItemTemplate>
                EmployeeID:
                <asp:Label ID="EmployeeIDLabel" runat="server"
                    Text='<%# Eval("EmployeeID") %>' />
                <br />
                Name:
                <asp:Label ID="NameLabel" runat="server" Text='<%# Bind("Name") %>' />
                <br />
                Title:
                <asp:Label ID="TitleLabel" runat="server" Text='<%# Bind("Title") %>' />
                <br />
                BirthDate:
                <asp:Label ID="BirthDateLabel" runat="server" Text='<%# Bind("BirthDate") %>' />
                <br />
                MaritalStatus:
                <asp:Label ID="MaritalStatusLabel" runat="server"
                    Text='<%# Bind("MaritalStatus") %>' />
                <br />
                Gender:
                <asp:Label ID="GenderLabel" runat="server" Text='<%# Bind("Gender") %>' />
                <br />
                HireDate:
                <asp:Label ID="HireDateLabel" runat="server" Text='<%# Bind("HireDate") %>' />
                <br />

            </ItemTemplate>
        </asp:FormView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:modiConnectionString %>"
            SelectCommand="SELECT [EmployeeID], [Name], [Title], [BirthDate], [MaritalStatus], [Gender], [HireDate] FROM [Employee]">
        </asp:SqlDataSource>
   
    </div>
    </form>
</body>
</html>

Press F5 button and see the output. 

AdRotator Example in Asp.Net using Xml file.


Introduction:

AdRotator is used to display different advertisement randomly in page. You can store the advertisement  either in the XML file or stored in the DataBase. Here I have used XML file to display the advertisement.

AdRotator.aspx:-  

<!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:Label ID="Label1" runat="server" Text="AspMaterials Blog"></asp:Label><br />
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
        <asp:AdRotator ID="AdRotator1" runat="server" DataSourceID="XmlDataSource1" />
        <asp:XmlDataSource ID="XmlDataSource1" runat="server"
            DataFile="~/AdRotatorXMLFile.xml"></asp:XmlDataSource>
    </div>
    </form>
</body>
</html>

AdRotatorXMlFile.xml:-

<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
  <Ad>
    <ImageUrl>image/google.jpg</ImageUrl>
    <NavigatorUrl>http://wwww.google.com</NavigatorUrl>
    <AlternateText>Google</AlternateText>
    <Impressions>90</Impressions>
    <Keyword>Search</Keyword>
  </Ad>
  <Ad>
  <ImageUrl>image/msn.jpg</ImageUrl>
  <NavigatorUrl>http://www.msn.com</NavigatorUrl>
  <AlternateText>MSN</AlternateText>
  <Impressions>80</Impressions>
  <Keyword>MSN</Keyword>
 </Ad>
  <Ad>
    <ImageUrl>image/Microsoft.jpg</ImageUrl>
    <NavigatorUrl>http://www.microsoft.com</NavigatorUrl>
    <AlternateText>Microsoft</AlternateText>
    <Impressions>70</Impressions>
    <Keyword>Read</Keyword>
  </Ad>
  <Ad>
    <ImageUrl>image/AspMaterials.jpg</ImageUrl>
    <NavigatorUrl>http://www.aspmaterials.blogspot.com</NavigatorUrl>
    <AlternateText>Asp Materials</AlternateText>
    <Impressions>90</Impressions>
    <Keyword>Read</Keyword>
  </Ad>
  <Ad>
    <ImageUrl>image/yahoo.jpg</ImageUrl>
    <NavigatorUrl>http://www.yahoo.com</NavigatorUrl>
    <AlternateText>Yahoo</AlternateText>
    <Impressions>80</Impressions>
    <Keyword>Search</Keyword>
  </Ad>
</Advertisements>

Here image is folder name in which image has put. If you want to put in main directory then just remove folder name with  forward slash means write only image name with extension.
Run the code and observe the output. Here advertisement will not  raotate  or display continuously because  time is not used . If you want to check that advertisement is randomly coming or not just click on refresh button , it will automatically display other advertisement.
In next post   I will come back with AdRotator in asp.net using DataBase file.

Thursday, 22 November 2012

How to retrieve image from database in asp.net using c#.


In the previous  I had explained ‘How to save image in database in Asp.Net using c#’. In this post I have explained how to retrieve image from database in asp.net. I suggest you to follow my previous post ‘How to save image in database in Asp.Net using c#’.
Follow step by step as given below.(First review the previous post ’how to save image in database in asp.net’).

Step1:  Bal code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for bal
/// </summary>
public class bal
{
    dal d1 = new dal();
      public bal()
      {
            //
            // TODO: Add constructor logic here
            //
      }
    public DataSet find(string UserName)
    {
        return d1.find(UserName);
    }
}

Step2: Dal code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for dal
/// </summary>
public class dal
{
    SqlConnection con = new SqlConnection(@"Data Source=SUSHIL-PC;Initial Catalog=modi;Integrated Security=True");
      public dal()
      {
            //
            // TODO: Add constructor logic here
            //
      }
public DataSet find(string UserName)
    {
        SqlCommand com = new SqlCommand("sp_search", con);// here sp_insert is stored procedure
        con.Open();
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.AddWithValue("@username", UserName);
        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
        con.Close();
    }
}

Step3: Util class

Util.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Util
/// </summary>
public class Util
{
      public Util()
      {
            //
            // TODO: Add constructor logic here
            //
      }
    public static string IMAGE = "image\\";
    public static string TILED_ROOT = "~/";
    public static string ROOT_PATH = System.Web.HttpContext.Current.Server.MapPath("~/");
    public static string makePictureName( String orignalFileName)
    {
        return getName(orignalFileName) + "." + getExtension(orignalFileName);
    }
    public static string getName(String fileName)
    {
        if (fileName.Contains("."))
        {
            return fileName.Split('.')[0].ToString();
        }
        else
        {
            //throw Exception;
            return fileName;

        }
    }
    public static string getExtension(String fileName)
    {
        if (fileName.Contains("."))
        {
            return fileName.Split('.')[1].ToString();
        }
        else
        {
            //throw Exception;
            return fileName;

        }
    }
    public static string makePhysicalPath(String virtualPath)
    {
        return virtualPath.Replace('\\', '/');
    }
    public static string makeVirtulPath(String virtualPath)
    {
        return virtualPath.Replace('/', '\\');
    }
}


Step4:  Design page
<!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>
    UserName:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
    Password:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
    Email Id:<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
    Photo:<asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Image ID="Image1" runat="server" Height="85px" Width="156px" /><br />
        <asp:Button ID="Button2" runat="server" Text="Search" onclick="Button2_Click" />
    </div>
    </form>
</body>
</html>

Step5:  .cs page code
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;

public partial class SaveImageInDatabase : System.Web.UI.Page
{
    bal b1 = new bal();
    protected void Page_Load(object sender, EventArgs e)
    {

    }

   
    protected void Button2_Click(object sender, EventArgs e)
    {
        // code for displaying image
        string userName = TextBox1.Text;
        DataSet _ds = b1.find(userName);
        if (_ds != null && _ds.Tables[0].Rows.Count > 0)
        {
            TextBox2.Text=_ds.Tables[0].Rows[0].ItemArray[1].ToString();
            TextBox3.Text=_ds.Tables[0].Rows[0].ItemArray[2].ToString();
            String s = _ds.Tables[0].Rows[0].ItemArray[3].ToString();
            Image1.ImageUrl = Util.TILED_ROOT + Util.makePhysicalPath(s);
        }
    }
}

Step6: Run the code and check the output.
If any problem regarding this post you can contact me at sushilct86@gmail.com.