Archive

Archive for December, 2008

Collepse and Expand Gridview (For Details) using Javascript

December 30, 2008 3 comments

Hi

try this example:

Default.aspx

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">

<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" >
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
        function OpenTable(table, img)
        {
            object = document.getElementById(table);
            if (object.style.display=="")
            {
                object.style.display = "none";
                img.src = "plus.gif";
            }
            else

            {
                object.style.display = "";
                img.src = "minus.gif";
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID"
            AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField SortExpression="CustomerID" HeaderText="CustomerID">
                    <ItemTemplate>
                       <img src="plus.gif" onclick='OpenTable("<%# CreateID(Eval("CustomerID"))%>", this);'/>
                        <asp:Label Runat="server" Text='<%# Bind("CustomerID") %>' ID="Label1"></asp:Label>
                       <br />
                       <table width=100% style="display:none;" id='<%# CreateID(Eval("CustomerID"))%>'>
                            <tr>
                                <td>
                                    <asp:Label Runat="server" Text='<%# Bind("CompanyName") %>' ID="Label2"></asp:Label>
                                </td>
                                <td>
                                    <asp:Label Runat="server" Text='<%# Bind("ContactName") %>' ID="Label3"></asp:Label>
                                </td>
                                <td>
                                    <asp:Label Runat="server" Text='<%# Bind("ContactTitle") %>' ID="Label4"></asp:Label>
                                </td>
                                <td>
                                    <asp:Label Runat="server" Text='<%# Bind("Address") %>' ID="Label5"></asp:Label>
                                </td>
                                <td>
                                    <asp:Label Runat="server" Text='<%# Bind("City") %>' ID="Label6"></asp:Label>
                                </td>
                                <td>
                                    <asp:Label Runat="server" Text='<%# Bind("Region") %>' ID="Label7"></asp:Label>
                                </td>
                        </table>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region] FROM [Customers]"
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>">
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

in code behind:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
    public string CreateID(object value)
    {
        return "Table_" + value.ToString();
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
   
}

Hope it helps

Good Luck

Categories: ASP.Net, Javascript

Collepse and Expand Gridview Row (Master and Detail) using Javascript

December 30, 2008 12 comments

Hi

try this exanple to Collepse and Expand Gridview Row (Master and Detail) using Javascript

Default.aspx

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">

<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" >
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
        function OpenTable(table, img)
        {
            object = document.getElementById(table);
            if (object.style.display=="")
            {
                object.style.display = "none";
                img.src = "plus.gif";
            }
            else
            {
                object.style.display = "";
                img.src = "minus.gif";
            }
        }
        </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
            DataSourceID="sqlDsCustomers" AllowPaging="True" OnRowCreated="gvCustomers_RowCreated" CellPadding="4" ForeColor="#333333" ShowHeader="False">
            <Columns>
                <asp:TemplateField HeaderText="CompanyName" SortExpression="CompanyName">
                  
                    <ItemTemplate>
                    <img src="plus.gif" onclick='OpenTable("<%# CreateID(Eval("CustomerID"))%>", this);'/>
                   <asp:Label ID="Label1" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>
                        Orders (<asp:Label ID="Label2" runat="server" Text='<%# Eval("TotalOrders") %>'></asp:Label>)<table width=100% style="display:none;" id='<%# CreateID(Eval("CustomerID"))%>'>
                    <tr>
                    <td>
                     <asp:SqlDataSource ID="sqlDsOrders" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                    SelectCommand="SELECT [OrderID], [OrderDate], [RequiredDate], [Freight], [ShippedDate] FROM [Orders] WHERE ([CustomerID] = @CustomerID)">
                    <SelectParameters>
                        <asp: Parameter Name="CustomerID" Type="String" DefaultValue="" />
                    </SelectParameters>
                </asp:SqlDataSource>
                <asp:GridView AutoGenerateColumns="False" CssClass="grid" ID="gvOrders" DataSourceID="sqlDsOrders"
                        runat="server" EnableViewState="False" CellPadding="4" ForeColor="#333333">
                        <RowStyle CssClass="row" BackColor="#EFF3FB" />
                        <AlternatingRowStyle CssClass="altrow" BackColor="White" />
                        <Columns>
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <%# Container.DataItemIndex + 1 %>
                                </ItemTemplate>
                                <ItemStyle CssClass="rownum" />
                            </asp:TemplateField>
                            <asp:BoundField HeaderText="Order ID" DataField="OrderID" >
                                <ItemStyle Width="80px" />
                            </asp:BoundField>
                            <asp:BoundField HeaderText="Date Ordered" DataField="OrderDate" DataFormatString="{0:dd/MM/yyyy}" >
                                <ItemStyle Width="100px" />
                            </asp:BoundField>
                            <asp:BoundField HeaderText="Date Required" DataField="RequiredDate" DataFormatString="{0:dd/MM/yyyy}" >
                                <ItemStyle Width="110px" />
                            </asp:BoundField>
                            <asp:BoundField HeaderText="Freight" DataField="Freight" DataFormatString="{0:c}" >
                                <ItemStyle HorizontalAlign="Right" Width="50px" />
                            </asp:BoundField>
                            <asp:BoundField HeaderText="Date Shipped" DataField="ShippedDate" DataFormatString="{0:dd/MM/yyyy}" >
                                <ItemStyle Width="100px" />
                            </asp:BoundField>
                        </Columns>
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <EditRowStyle BackColor="#2461BF" />
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    </asp:GridView>
                    </td>
                    </tr>
                    </table>  
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <EditRowStyle BackColor="#2461BF" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
        <asp:SqlDataSource ID="sqlDsCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            ProviderName="<%$ ConnectionStrings:NorthwindConnectionString.ProviderName %>"
            SelectCommand="SELECT [Customers].[CustomerID], [Customers].[CompanyName], COUNT([OrderID]) TotalOrders FROM [Customers] INNER JOIN [Orders] ON [Customers].[CustomerID]=[Orders].[CustomerID] Group By [Customers].[CustomerID], [Customers].[CompanyName]">
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    public string CreateID(object value)
    {

        return "Table_" + value.ToString();

    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            SqlDataSource ctrl = e.Row.FindControl("sqlDsOrders") as SqlDataSource;
            if (ctrl != null && e.Row.DataItem != null)
            {
                ctrl.SelectParameters["CustomerID"].DefaultValue = ((DataRowView)e.Row.DataItem)["CustomerID"].ToString();
            }
        }
    }
}

Good Luck

Custom Serverside paging in GridView Vs DataGrid

December 29, 2008 1 comment

When doing serverside paging(that is paging at the database layer by returning only the paged result), one of the things I miss in the GridView control is the VirtualItemCount, which is supposedly only supported in the older control’s like the DataGrid.

This property was quite useful because while being able to supply to the DataGrid a variable number of paged result sets, i was also able to tell the DataGrid, the total number of records, that way it knew how many pager buttons to display.

Eg. If we had, say a total of a 100 records and had the pageSize set to 7, so only 7 records are shown at a time, then how does the grid know how many numbered pager buttons to display allowing us to navigate from one page to another ? That’s where the VirtualItemCount came into play and saved the day. To this property we’d pass a total records count and that was it. In the GridView today ? There is no VirtualItemCount present. The way it were planned it seems is to use the ObjectDataSource, which in my honest opinion is simply extra work, however it does abstract much of this code nicely and put it where it should be, in the data tier.

In all the example code in this post, I shall be using the MemberShip.GetAllUsers method. This method is overloaded and can retrieve a paged result of users Versus returning all the user’s in the database, which is a quite handy overload and works out nicely for the code i want to use in this post.

Let’s look at a simple example of how we couldof performed custom paging on the DataGrid control back in the old days :

int virtualItemCount = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataGridMembers.DataSource = Membership.GetAllUsers(0,
        DataGridMembers.PageSize, out virtualItemCount);
            DataGridMembers.VirtualItemCount = virtualItemCount;
            DataGridMembers.DataBind();
        }
    }

Note the VirtualItemCount ? Then on the PageIndexChanged event of the DataGrid we did :

protected void DataGridMembers_PageIndexChanged(object source,DataGridPageChangedEventArgs e)
    {
        DataGridMembers.CurrentPageIndex = e.NewPageIndex;
        DataGridMembers.DataSource = Membership.GetAllUsers(e.NewPageIndex,
        DataGridMembers.PageSize, out virtualItemCount);
        DataGridMembers.DataBind();
    }

And that was it, it was as simple as that 

Now try to do that on the GridView ? Can’t be done and this is a control that is replacing the old DataGrid control. To make things worse, the DataGrid is not a supported control anymore in 2.0 ; It’s been obsoleted and by default you wont even find this control in your toolbox. You can still use it however by manually adding it to your toolbox. Unfortunate, because there are moments like this custom paging situation and i’m getting nostalgic already.

So, how to achieve the same thing in the GridView control which happens to replace the DataGrid ? Well, it’s a long shot. Since we cannot achive this directly on the GridView, we are going to have to do it via the DataSource control, which is actually the control that is populating the data for the gridview and also the control that handles paging and sorting amoung other things. While i like this kind of data abstraction, i’m actually doing more work and making the extra effort,but this is how you would implement custom paging on  your GridView control.

The GridView alone is lacking a VirtualItemCount property, which i believe shouldn’t have been so hard to implement. To compensate for this lacking, you perform custom serverside paging by using an ObjectDataSource control, defining a SelectMethod and a SelectCountMethod method. The SelectCountMethod is your custom method that returns the Total records count.

So let’s look at some code, and there are few gotcha’s that weren’t exactly obvious to me in the begining :
First our custom SelectMethod :

public MembershipUserCollection GetAllUsers(int startRowIndex,int maximumRows)
    {
        if (startRowIndex > 0)
            startRowIndex = startRowIndex / maximumRows;
        return Membership.GetAllUsers(startRowIndex,
            maximumRows, out selectCountValue);
    }

One gotcha you want to make note of is how i have some extra code to divide startRowIndex by maximumRows ; This is because startRowIndex is actually the first row in the resultset as the variable name indicates, however what i really need is the current page index, because that is what our stored procedure is expecting, in this case that is what the internal MemberShip.GetAllUsers method is expecting.

Next we need to add a SelectCountMethod :

int selectCountValue = 0;
    public int SelectVirtualCount()
    {
        return selectCountValue;
    }

The code is minimum as you can note, but ofcourse, there is some extra effort to making the abstraction. The code above goes into the data layer.

And lastly, we need to subscribe to PageIndexChanging event of our GridView and pass the selected page index :

protected void GridViewMembers_PageIndexChanging(object sender,GridViewPageEventArgs e)
    {
        GridViewMembers.PageIndex = e.NewPageIndex;
    }

A peculiar behaviour you will notice is that the SelectCountMethod and the SelectMethod both share the same SelectParameters if SelectParameters are defined. Peculiar because i was not really expecting it, however I have no issues with it, For example if we had to rewrite our previous example to include also a search by userName, then our ObjectDataSource would be expecting some SelectParameters like this :

<asp:ObjectDataSource ID="ObjectDataSourceMembers"
        EnablePaging="True"
        SelectCountMethod="SelectVirtualCount"
        SelectMethod="GetAllUsers"
        TypeName="MembersData"
        runat="server">
<SelectParameters>
            <asp:ControlParameter ControlID="TextBoxUserName" Name="userName"
        PropertyName="Text" DefaultValue="All" />
        </SelectParameters>
</asp:ObjectDataSource>

And then modified our SelectMethod as such :

public MembershipUserCollection GetAllUsers(int startRowIndex,int maximumRows, string userName)
    {
        if (startRowIndex > 0)
            startRowIndex = startRowIndex / maximumRows;
        if (userName == "all")
        {
            return Membership.GetAllUsers(startRowIndex,
                maximumRows, out selectCountValue);
        }
        else
        {
                return (MembershipUserCollection)
                    Membership.FindUsersByName(userName + "%",
                    startRowIndex, maximumRows, out selectCountValue);
        }
    }

As you can see while our GetAllUsers(SelectMethod) has the needed userName parameter, our SelectVirtualCount method defined above does not have any parameters defined on it, since we don’t need to pass it anything. However, the ObjectDataSource is going to complain with :

ObjectDataSource ‘ObjectDataSourceMembers’ could not find a non-generic method ‘SelectVirtualCount’ that has parameters: userName

So it means both the SelectMethod and the SelectCountMethod share the same Select parameters. I resolved by adding the extra userName parameter in the SelectCountMethod as well, while i did not clearly need it, but no big deal.
Here is what the modified SelectCountMethod wouldof looked like :

int selectCountValue = 0;
    public int SelectVirtualCount(string userName)
    {
        return selectCountValue;
    }

The SelectCountMethod is treated exactly in the same way the SelectMethod is treated, so the ObjectDataSource’s Selected Event is going to fire twice for example, once when the SelectMethod is called and once when the SelectCountMethod is called. These are all gotchas i was not really prepared for.

Full code for custom serverside paging in DataGrid :


<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  
int virtualItemCount = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataGridMembers.DataSource = Membership.GetAllUsers(0,
        DataGridMembers.PageSize, out virtualItemCount);
            DataGridMembers.VirtualItemCount = virtualItemCount;
            DataGridMembers.DataBind();
        }
    }

    protected void DataGridMembers_PageIndexChanged(object source,
    DataGridPageChangedEventArgs e)
    {
        DataGridMembers.CurrentPageIndex = e.NewPageIndex;
        DataGridMembers.DataSource = Membership.GetAllUsers(e.NewPageIndex,
        DataGridMembers.PageSize, out virtualItemCount);
        DataGridMembers.DataBind();
    }
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp: DataGrid ID="DataGridMembers" AllowPaging="True"
        AllowCustomPaging="true" PageSize="2" runat="server"
        OnPageIndexChanged="DataGridMembers_PageIndexChanged">
        <PagerStyle Mode="NumericPages"
                     HorizontalAlign="Right" />
        </asp: DataGrid>
    </div>
    </form>
</body>
</html>

And the full code for custom paging in GridView :


<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">

<script runat="server">
protected void GridViewMembers_PageIndexChanging(object sender,
    GridViewPageEventArgs e)
    {
        GridViewMembers.PageIndex = e.NewPageIndex;
    }
</script>

<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridViewMembers" DataSourceID="ObjectDataSourceMembers"
    runat="server" AllowPaging="True" PageSize="2"
    OnPageIndexChanging="GridViewMembers_PageIndexChanging">
        </asp:GridView>
        <asp:ObjectDataSource ID="ObjectDataSourceMembers"
        EnablePaging="True"
        SelectCountMethod="SelectVirtualCount"
        SelectMethod="GetAllUsers"
        TypeName="MembersData"
        runat="server"></asp:ObjectDataSource>
    </div>
    </form>
</body>
</html>

and the Class

public class MembersData
{
    public MembersData()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    int selectCountValue = 0;
    public int SelectVirtualCount()
    {
        return selectCountValue;
    }
    public MembershipUserCollection GetAllUsers(int startRowIndex,int maximumRows)
    {
        if (startRowIndex > 0)
            startRowIndex = startRowIndex / maximumRows;
        return Membership.GetAllUsers(startRowIndex,
            maximumRows, out selectCountValue);
    }
}

Hope this helps

Good Luck

Categories: ASP.Net

Customizing the ChangePassword control and removing the required CurrentPassword field

December 29, 2008 2 comments

It’s very rare that what is already provided in asp.net under the Login controls fits my requirements out of the box without some tweaking. Not that any of these controls offer anything specialized, but certainly they are a big time saver if we can re-utilize their functionality.

First some background as to why i personally want to customize the ChangePassword control to suit my needs :

Password recovery is what i was after today, however i have hashed passwords, and recovery is impossible. If the user lost their password, then there is no way for me to know what their password is and send it back in clear text.

The ideal solution is to reset the password, however the autogenerated password is quite ugly and quite hard to remember. What I’ve decided to do is send the email during password recovery, but as part of the email, instead of telling the user their old password(which i can’t) , I’m instead going to ask them to click on a tokenized link that will guarantee to me that they are indeed the ones that requested the password, send them to the page where they can provide a new password, in the background i’d be autogenerating a password first ofcourse, then updating the password with their new password because the MembershipUser.ChangePassword(oldPassword, newPassword) method requires Old password as one of it’s two parameters.
This password change step, i’d like to be done using the ChangePassword control, however to my big surprise CurrentPassword Field is a required field that i cannot remove. This is also a field that I do not want asked for during the password change request(since my user has forgotten their password and are now going to provide their new pasword).

There is ofcourse no property or method in this control that removes the CurrentPassword field requirement, below is a screenshot of the ChangePassword control in designview, as you can note, the highlighted field is the CurrentPassword field i do not want.

As you can read from the posts there, the issue seems to be two things which were also my same issues :
1) Remove the current password label/TextBox
2) Pass the new resetpassword to CurrentPassword Property which by the way is a getter only and not settable (SAD SAD)

Both of these things are not supported in this control. So let’s quickly fix requirement 1 and there are a couple of ways to fix this : 
a) You have to define a custom  <ChangePasswordTemplate>. This can be easily done by taking your ChangePassword control into DesignView in Visual studio, right click on the control and select “Convert to template”. You can then switch to HtmlView and set the visibility of CurrentPasswordLabel, CurrentPassword and CurrentPasswordRequired controls.
b) If you prefer to do this in code, then you can find the Label and TextBox for CurrentPassword and set its visiblity to false. Since a is a nobrainer, i’m including a sample code of method (b) :


Label l = (Label)changePassword1.ChangePasswordTemplateContainer.
    FindControl("CurrentPasswordLabel");
if (l != null)
    l.Visible = false;

TextBox tb = (TextBox)changePassword1.ChangePasswordTemplateContainer.
FindControl("CurrentPassword");
if (tb != null)
    tb.Visible = false;

RequiredFieldValidator rfv = (RequiredFieldValidator)changePassword1.
ChangePasswordTemplateContainer.FindControl("CurrentPasswordRequired");
if (rfv != null)
    rfv.Visible = false;

Now that we have the fields we want disabled, let’s head onto fix issue 2 :
We can’t pass the Autogenerated password to the CurrentPassword Property because its a getter only, however this getter returns the value from our CurrentPassword TextBox, and this job is done immidiately after ChangingPassword event fires. This is good news for us, so we can resolve issue 2 like this :

void changePassword1_ChangingPassword(object sender,
    LoginCancelEventArgs e)
{
    changePassword1.UserName = user.UserName;
        TextBox currentPassword = (TextBox)changePassword1.
         ChangePasswordTemplateContainer.FindControl("CurrentPassword");
        if (currentPassword != null)
            currentPassword.Text = user.ResetPassword();
}

Hope it helps
Good Luck

Categories: ASP.Net Tags: ,

Display Image in Popup window with Gridview

December 29, 2008 Leave a comment

Hi

try this example to display image in popup window where i save image name in my database and upload image in folder in my website called Car_Image

First Example:

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

and in code behind :-

protected void GridView1_DataBound(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            Image img = (Image)row.FindControl("Image1");
            string strImage = img.ImageUrl;
            //strImage = strImage.Replace("~", "..");
            img.Attributes.Add("onClick", "javascript:window.open('image.aspx?PId=" + strImage + "',null,'left=45px,top=15px, width=300px, height=300px,status=no, resizable= yes, scrollbars=yes, toolbar=no, location=no,menubar=no');");
        }
    }

 and in image.aspx page add image control

and in code behind of image.aspx page we will get image as we pass image name in querystring

protected void Page_Load(object sender, EventArgs e)
    {
        string url = Request.QueryString["PId"].ToString();
        Image1.ImageUrl = url;
    }

Second Example:

<script language="javascript" type="text/javascript">
function Openpopup(popurl)
{
winpops = window.open(popurl,"car","width=340, height=300, left=45, top=15, scrollbars=yes, menubar=no,resizable=no,directories=no,location=no")
}
</script>

<asp:TemplateField HeaderText="Image">
                <ItemTemplate>
                   <a href="javascript:Openpopup('Image_Detail.aspx?PId=<%# Eval("Id") %>')">
                   <asp:Image ID="Image1" runat="server" Height="72px" ImageUrl='<%# Eval("Image", "Car_Image/{0}") %>'
                            Width="91px" /></a>
                </ItemTemplate>
                <HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>

and in Image_Detail.aspx page we will get image by Id from Query String

Hope it helps…….

Good Luck

Categories: ASP.Net

Display Image in DataList

December 29, 2008 Leave a comment

Hi

try this example to display image in DataList where i save image name in my database and upload image in folder in my website called Car_Image

<ItemTemplate>
            <asp:Image ID="Image1" runat="server" Height="95px" ImageUrl='<%#"~/Car_Image/" + DataBinder.Eval(Container.DataItem,"Image")%>'
                Width="106px" />
</ItemTemplate>

and in code behind :-

protected String GetImageSrc(Object imgSrc)
{
if (imgSrc ==null || imgSrc == DBNull.Value || imgSrc == String.Empty())
{
return “Car_Image/NoImage.jpg”;
}
else
{
return “Car_Image/” + imgSrc.ToString();
}
}

Hope this helps

Good Luck

Categories: ASP.Net

Iframe with mouse scrolling

December 28, 2008 Leave a comment

Hi

try this example:-

First. make your iframe no scroll just like the following code:

  <IFRAME id=Viewer height=400 src=”Photo.aspx?id=1″ frameBorder=no width=600 scrolling=no></IFRAME>

Second.  In your Photo.aspx, make sure it can support the drag and drop by mouse:

<SCRIPT language=JavaScript>
drag = 0
move = 0
function init() {
window.document.onmousemove = mouseMove
window.document.onmousedown = mouseDown
window.document.onmouseup = mouseUp
window.document.ondragstart = mouseStop
}
function mouseDown() {
if (drag) {
clickleft = window.event.x - parseInt(dragObj.style.left)
clicktop = window.event.y - parseInt(dragObj.style.top)
dragObj.style.zIndex += 1
move = 1
}
}
function mouseStop() {
window.event.returnValue = false
}
function mouseMove() {
if (move) {
dragObj.style.left = window.event.x - clickleft
dragObj.style.top = window.event.y - clicktop
}
}
function mouseUp() {
move = 0
}
</SCRIPT>

Good Luck

Categories: ASP.Net, Javascript