Archive

Archive for May, 2010

Accesse DropDownLists inside the GridView Control

Hi

try this example to Accesse DropDownLists inside the GridView Control

Step1 :- Create new website using VS2005 and add new web page

Step2 :- From Toolbox drag  two Gridview controls and Button control so the first Gridview to Bind with DropdownList and the second one is to Display selected value from DropdownList inside the first Gridview and display it so your web page will be like that

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
            <Columns>
                <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
                <asp:TemplateField HeaderText="Category Name">
                    <ItemTemplate>
                        <asp:DropDownList DataSource='<%# GetCategoryNames() %>' DataTextField="CategoryName" DataValueField="CategoryName" ID="ddlCategoryName" runat="server">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description">
                    <ItemTemplate>
                        <asp:DropDownList DataSource='<%# GetCategoryDescriptions() %>' DataTextField="Description" DataValueField="Description" ID="ddlDescription" runat="server">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField HeaderText="Select" ShowSelectButton="True" />
            </Columns>
            <FooterStyle BackColor="White" ForeColor="#000066" />
            <RowStyle ForeColor="#000066" />
            <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
            <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
        </asp:GridView>
        &nbsp;&nbsp;<br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Get Selected Items" /><br />
        <br />
        <asp:GridView ID="GridView2" runat="server">
        </asp:GridView>

Step3 :- in code behind add the following code


protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindData();
        }      
    }

    private void BindData()
    {
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds, "Categories");
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }

    public DataSet GetCategoryNames()
    {
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT CategoryName FROM Categories", myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds, "Categories");
        return ds;
    }

    public DataSet GetCategoryDescriptions()
    {
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT Description FROM Categories", myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds, "Categories");
        return ds;
    }

    private string ConnectionString
    {
        get { return @"Server=localhost;Database=Northwind;Trusted_Connection=true"; }
    }
  
    // Gets the selected items in the GridView Control
    protected void Button1_Click(object sender, EventArgs e)
    {
        string categoryName = String.Empty;
        string description = String.Empty;
        DataTable dt = new DataTable();
        dt.Columns.Add("CategoryName");
        dt.Columns.Add("Description");

        foreach (GridViewRow row in GridView1.Rows)
        {
            categoryName = ((DropDownList)row.FindControl("ddlCategoryName")).SelectedItem.Value;
            description = ((DropDownList)row.FindControl("ddlDescription")).SelectedItem.Value;
            DataRow dr = dt.NewRow();
            dr["CategoryName"] = categoryName;
            dr["Description"] = description;
            dt.Rows.Add(dr);
        }     
        GridView2.DataSource = dt;
        GridView2.DataBind();

    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string categoryName = ((DropDownList)GridView1.SelectedRow.FindControl("ddlCategoryName")).SelectedItem.Value;
        Response.Write(categoryName);
    }

Hope this helps

Good Luck.

Advertisements
Categories: ASP.Net

Get Text and Value Pair with AJAX AutoComplete Extender

May 14, 2010 5 comments

Hi all,

try this example to get Text and Value Pair with AutoComplete Extender

in this example i will use Northwind Database

Step1 :- Open MS VS2008 and create new website and add new web page

Step2 :- From Toolbox drag ScriptManager , TextBox , AJAX AutoComplete Extender and GridView Control in your web page sp your web page will be like this :-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register TagPrefix="cc1" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" %>
<!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>Text and Value Pair with AutoComplete Extender</title>
    <script type="text/javascript">
    function ace1_itemSelected(sender, e)
    {
        var hdCustID = $get('<%= hdEmpID.ClientID %>');
        hdCustID.value = e.get_value();
    }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="sm1" runat="server" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Label ID="lblEmpName" Text="Employee Name:" AssociatedControlID="txtEmpName" runat="server" />
                <asp:TextBox ID="txtEmpName" AutoPostBack="true" AutoComplete="off" runat="server"
                    OnTextChanged="txtEmpName_TextChanged" />
                <cc1:AutoCompleteExtender ID="ace1" TargetControlID="txtEmpName" ServiceMethod="GetSuggestions"
                    MinimumPrefixLength="1" OnClientItemSelected="ace1_itemSelected" FirstRowSelected="true"
                    runat="server" />
                <asp:HiddenField ID="hdEmpID" runat="server" />
                <br /><br /><br />
                <asp:GridView ID="gvEmployee" runat="server" AutoGenerateColumns="False" CellPadding="4"
                    ForeColor="#333333" GridLines="None" PageSize="4" BorderStyle="Groove">
                    <RowStyle BackColor="#EFF3FB" />
                    <Columns>
                        <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID"  />
                        <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
                        <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
                        <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                        <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                        <asp:BoundField DataField="Region" HeaderText="Region"  />
                    </Columns>
                    <FooterStyle BackColor="#507CD1" ForeColor="White" Font-Bold="True" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <EditRowStyle BackColor="#2461BF" />
                    <AlternatingRowStyle BackColor="White" />
                </asp:GridView>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

Step3 :- In code behind of your page add the following code :


using System;
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.Web.Configuration;
using System.Collections.Generic;
using System.Collections;
using AjaxControlToolkit;

public partial class _Default : System.Web.UI.Page
{
 
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string[] GetSuggestions(string prefixText, int count)
    {
        try
        {

            string conStr;
            conStr = WebConfigurationManager.ConnectionStrings["ctionString"].ConnectionString;
            string sqlQuery = "SELECT [FirstName],[EmployeeID] FROM [Employees] WHERE FirstName like @FirstName";
            SqlConnection conn = new SqlConnection(conStr);
            SqlCommand cmd=new SqlCommand(sqlQuery,conn);
            cmd.Parameters.AddWithValue("@FirstName", prefixText + "%");
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            List<string> custList = new List<string>();
            string custItem = string.Empty;
            while (dr.Read())
            {
                custItem=AutoCompleteExtender.CreateAutoCompleteItem(dr[0].ToString(),dr[1].ToString());
                custList.Add(custItem);

            }
            conn.Close();
            dr.Close();
            return custList.ToArray();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void txtEmpName_TextChanged(object sender, EventArgs e)
    {
        try
        {
         gvEmployee.DataSource= GetCustomerDetail(Convert.ToInt32(hdEmpID.Value));
         gvEmployee.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public SqlDataReader GetCustomerDetail(int EmpID)
    {
        try
        {

            string conStr;
            conStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            string sqlQuery = "SELECT EmployeeID,FirstName,LastName,Title,Address,City,Region ";
            sqlQuery = sqlQuery + " FROM [Employees] WHERE EmployeeID = @EmployeeID";
            SqlConnection conn = new SqlConnection(conStr);
            SqlCommand cmd = new SqlCommand(sqlQuery, conn);
            cmd.Parameters.AddWithValue("@EmployeeID", EmpID);
            conn.Open();
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Step4 :- In Web.Config add the ConnectionStrng

<connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Hope this helps

Good Luck.

Categories: AJAX, ASP.Net

Use Mouseover on image in Gridview to Zoom Image

May 9, 2010 2 comments

Hi

try this example

Step1 :- Open MS SQL Server and create new database and add new Table called “Album” with the following fields

– Id —> int (Auto Increment) and Primary Key

– Name —> nvarchar(50)

– Pic —> nvarchar(50)

where i will save image name in database and upload it in folder in my website called “Picture”

Step2 :- Open VS2005 and create a new website and add new web page and from ToolBox drag Gridview Control and Bind it using SQLDatasource control

Step3 :- Add this CSS Style

    <style type="text/css">
        body
        {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow-y: auto;
        }
        .modal
        {
            display: none;
            position: absolute;
            top: 0px;
            left: 0px;
            background-color: black;
            z-index: 100;
            opacity: 0.8;
            filter: alpha(opacity=60);
            -moz-opacity: 0.8;
            min-height: 100%;
        }
        #divImage
        {
            display: none;
            z-index: 1000;
            position: fixed;
            top: 0;
            left: 0;
            background-color: White;
            height: 300px;
            width: 600px;
            padding: 3px;
            border: solid 1px black;
        }
        * html #divImage
        {
            position: absolute;
        }
    </style>

Step4 :- Add this Javascript Script in your page


    <script type="text/javascript">
        function LoadDiv(url) {
            var img = new Image();
            var bcgDiv = document.getElementById("divBackground");
            var imgDiv = document.getElementById("divImage");
            var imgFull = document.getElementById("imgFull");
            var imgLoader = document.getElementById("imgLoader");

            imgLoader.style.display = "block";
            img.onload = function() {
                imgFull.src = img.src;
                imgFull.style.display = "block";
                imgLoader.style.display = "none";
            };
            img.src = url;
            var width = document.body.clientWidth;
            if (document.body.clientHeight > document.body.scrollHeight) {
                bcgDiv.style.height = document.body.clientHeight + "px";
            }
            else {
                bcgDiv.style.height = document.body.scrollHeight + "px";
            }

            imgDiv.style.left = (width - 650) / 2 + "px";
            imgDiv.style.top = "20px";
            bcgDiv.style.width = "100%";

            bcgDiv.style.display = "block";
            imgDiv.style.display = "block";
            return false;
        }
        function HideDiv() {
            var bcgDiv = document.getElementById("divBackground");
            var imgDiv = document.getElementById("divImage");
            var imgFull = document.getElementById("imgFull");
            if (bcgDiv != null) {
                bcgDiv.style.display = "none";
                imgDiv.style.display = "none";
                imgFull.style.display = "none";
            }
        }
    </script>

and Your web page will be


        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"   OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="Image" SortExpression="Image">

                    <ItemTemplate>
                        <asp:Image ID="Image1" runat="server" Height="85px" ImageUrl='<%# Eval("Image", "~/Car_Image/{0}") %>' Width="122px" />

                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Car_DBConnectionString %>"
            SelectCommand="SELECT [Image] FROM [Car]"></asp:SqlDataSource>

    </div>
   
<div id="divBackground">
        <div id="divImage">
            <table style="height: 100%; width: 100%">
                <tr>
                    <td valign="middle" align="center">
                        <img id="imgLoader" alt="" src="5.gif" />
                        <img id="imgFull" runat="server" alt="" src=""  />
                    </td>
                </tr>
                <%--<tr>
                <td align="center" valign="bottom">
                    <%--<input id="btnClose" type="button" value="close" onclick="HideDiv()" />
                </td> </tr>--%>
    </table>
    </div>
 </div>

Step5 :- In code behind add the following code:-

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            Image imgProdImage = (Image)row.FindControl("Image1");
            if (imgProdImage != null)
            {
                imgProdImage.Attributes.Add("onmouseover", "LoadDiv(this.src)");
                imgProdImage.Attributes.Add("onmouseout", " HideDiv()");
            }
        }
    }

Hope this helps

Good Luck

Categories: ASP.Net, Javascript

AJAX HoverMenu Control to Display Details for Gridview Row

Hi

try this example to use AJAX HoverMenu Control to Display Details for Gridview Row

Step1 :- Open MS SQL Server and create new database and add new Table called “Album” with the following fields

– Id —> int (Auto Increment) and Primary Key

– Name —> nvarchar(50)

– Pic —> nvarchar(50)

where i will save image name in database and upload it in folder in my website called “Picture”

Step2 :- Open VS2005 and create a new website and add new web page

Step3 :- From ToolBox drag ScriptManager , GridView and AJAX HoverMenuExtender and bind your Gridview using SqlDataSource control so your page will be like this



        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        CellPadding="4" ForeColor="#333333" BorderColor="#628BD7"
        BorderStyle="Solid" BorderWidth="2px" DataSourceID="SqlDataSource1" >
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:TemplateField HeaderText="Pic" SortExpression="Pic">
                    <ItemTemplate>
                        <asp:Image ID="thumbnailImage" runat="server" Height="71px"
                            ImageUrl='<%# Eval("Pic", "~/Pic/{0}") %>' Width="115px" />
                        <cc1:HoverMenuExtender ID="HoverMenuExtender1" runat="server"
                             PopupControlID="popupImage"
                             TargetControlID="thumbnailImage"
                             OffsetX="10" OffsetY="5"
                             PopupPosition="Right"
                             PopDelay="100" HoverDelay="100">
                      </cc1:HoverMenuExtender>
                      <asp:Panel runat="server" ID="popupImage" BorderColor="#628BD7"
                         BorderStyle="Solid" BorderWidth="7px">                
                         <asp:Image runat="server" ID="mainImage"
                            ImageUrl='<%# Eval("Pic", "~/Picture/{0}") %>'  />              
                      </asp:Panel>   
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Album]"></asp:SqlDataSource>

after that rum your website

Hope this helps

Good Luck.

Categories: AJAX, ASP.Net