Yasserzaid’s Weblog

December 24, 2008

Move items form ListBox to another

Filed under: Javascript — yasserzaid @ 7:47 pm

Try this example:

   <title>Untitled Page</title>
  
    <script type=”text/javascript”>
        /*
            – Function MoveItems()
            – Direction: Specifies direction i.e. L = Left, R = Right
            – All: Move All items 1 = All, 0 = Selected
        */
        function MoveItems(Direction, All)
        {
            var LstLeft;
            var LstRight;
            var Removed = ”;
            var i;
           
            if (Direction == ‘R’)
            {
                var LstLeft = document.getElementById(“<%=LstLeft.ClientID %>”);
                var LstRight = document.getElementById(“<%=LstRight.ClientID %>”);               
            }
            else
            {
                var LstLeft = document.getElementById(“<%=LstRight.ClientID %>”);
                var LstRight = document.getElementById(“<%=LstLeft.ClientID %>”);               
            }  
           
            for (i=0; i<LstLeft.length; i++)
            {
                if (LstLeft.options[i].selected || All == 1)
                    if(ItemExists(LstRight, LstLeft.options[i].value) == 0)
                    {
                        LstRight[LstRight.length] = new Option(LstLeft.options[i].text, LstLeft.options[i].value, true);
                        Removed = Removed + LstLeft.options[i].value + ‘,’;
                    }
            }
            RemoveFromList(LstLeft, Removed);
            return false;           
        }
   
        function RemoveFromList (Lst, Items)
        {
            var Removed = Items.split(‘,’);
            var j;
            var x;
            for (j=0; j<Removed.length; j++)
            {
                for (x=0; x<Lst.length; x++)
                {
                    if (Lst.options[x] != null && Lst.options[x].value == Removed[j])
                    {
                        Lst.options[x] = null;
                    }
                }
            }
        }
       
        function ItemExists(Lst, value)
        {
            var Flag = 0;
            var i = 0;
            for (i=0; i<Lst.length; i++)
            {
                if (Lst.options[i].value == value)
                {
                    Flag = 1;
                    break;
                }
            }
            return Flag;
        }
    </script>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:ListBox ID=”LstLeft” runat=”server” SelectionMode=”multiple” Width=”200px” Rows=”5″ >
            <asp:ListItem Value=”0″ Text=”Farhan”></asp:ListItem>
            <asp:ListItem Value=”1″ Text=”Moin”></asp:ListItem>
            <asp:ListItem Value=”2″ Text=”Haroon”></asp:ListItem>
            <asp:ListItem Value=”3″ Text=”Khurram”></asp:ListItem>
            <asp:ListItem Value=”4″ Text=”Mansur”></asp:ListItem>
        </asp:ListBox>
        &nbsp;&nbsp;
        <asp:ListBox ID=”LstRight” runat=”server” SelectionMode=”multiple” Width=”200px” Rows=”5″>
        </asp:ListBox>
        <br />
        <asp:Button ID=”BtnRight” runat=”server” Text=”>” OnClientClick=”return MoveItems(‘R’, 0);” />
        &nbsp;
        <asp:Button ID=”BtnLeft” runat=”server” Text=”<”  OnClientClick=”return MoveItems(‘L’, 0);”/>
        <asp:Button ID=”BtnRightAll” runat=”server” Text=”>>”  OnClientClick=”return MoveItems(‘R’, 1);” />
        &nbsp;
        <asp:Button ID=”BtnLeftAll” runat=”server” Text=”<<”  OnClientClick=”return MoveItems(‘L’, 1);” />
    </div>
    </form>
</body>
</html>

Good Luck

JavaScript to Maximize image

Filed under: ASP.Net, Javascript — yasserzaid @ 7:42 pm

Hi

try this example:

<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" >
<head runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
        .image {width:187px; height:224px; border: 1px solid #000000}
    </style>
    <script type="text/javascript">
        var restored = true        
        function MaximizeRestore()
        {
            if (restored == true)
            {  
                document.getElementById('<%= Image2.ClientID %>').style.width="200";
                document.getElementById('<%= Image2.ClientID %>').style.height="200";               
                restored = false;
            }
            else
            {
                document.getElementById('<%= Image2.ClientID %>').style.width="119";
                document.getElementById('<%= Image2.ClientID %>').style.height="142";               
                restored = true;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <img id="Image2" src="images/image.jpg" alt="testimage" class="image" onclick="MaximizeRestore()" />   
    </div>
    </form>
</body>
</html>

Good Luck

insert multiple records at a time with Gridview

Filed under: ASP.Net — Tags: — yasserzaid @ 7:40 pm

Hi

try this example:

<%@ Page Language=”C#” MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”insertusinggridview.aspx.cs” Inherits=”GRidviews_insertusinggridview” Title=”Untitled Page” %>
<asp:Content ID=”Content1″ ContentPlaceHolderID=”ContentPlaceHolder1″ Runat=”Server”>
    No Of Records : <asp:TextBox ID=”txtNo” runat=”server”></asp:TextBox> <asp:Button ID=”btnSubmit” runat=”server”  Text=”Submit” OnClick=”btnSubmit_Click”/>
    <br />
    <asp:GridView ID=”GridView1″ runat=”server”>
        <Columns>
            <asp:TemplateField HeaderText=”Name”>
                <ItemTemplate>
                      <asp:TextBox ID=”txtName” runat=”server”></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText=”No”>     
                <ItemTemplate>
                      <asp:TextBox ID=”txtNo” runat=”server”></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:Button ID=”btnInsert” runat=”server” Text=”Insert” OnClick=”btnInsert_Click” />
   
</asp:Content>

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 GRidviews_insertusinggridview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int[] nos = new int[Convert.ToInt32(txtNo.Text)];
        for (int i = 0; i < nos.Length; i++)
            nos[i] = i+1;
        GridView1.DataSource = nos;
        GridView1.DataBind();
       
    }
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvRow in GridView1.Rows)
        {
            TextBox txtName = (TextBox)gvRow.FindControl(“txtName”);
            TextBox txtNo = (TextBox)gvRow.FindControl(“txtNo”);
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["masterconnectionstring2"].ConnectionString);
            SqlCommand cmd = new SqlCommand(“insert into Names values (@Name,@No)” ,con);
            cmd.Parameters.Clear();
            cmd.Parameters.Add(“Name”, txtName.Text);
            cmd.Parameters.Add(“No”, txtNo.Text);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}
 

Good Luck

How to open popup windows in IE and Firefox and return values using ASP.NET and Javascript

Filed under: ASP.Net, Javascript — yasserzaid @ 7:38 pm

Try this example to know How to open popup windows in IE and Firefox and return values using ASP.NET and Javascript

Part 1 – Passing value to Popup window

Step 1: Open Visual Studio. Create a new website (File > New > Website). Set the location, filename and language of the project.

Step 2: In your Default.aspx, add a label (lblFName), textbox (txtFName) and a button (btnPopup). Set the ‘Text’ property of the label to ‘FirstName’. Similarly set the ‘Text’ property of the button control to ‘Show Popup’.

Step 3: Now add the popup form. Right click your project > Add New Item > Web Form > Rename form as ‘PopupWin.aspx’ and click on Add.

Step 4: In the PopupWin.aspx, add a textbox (txtReverse) and a button (btnReverse).
Well now we have two pages, Default.aspx which is the parent page and PopupWin.aspx which will be the popup page. Let us now pass a value from Default.aspx to the popup window.

Step 5: We will invoke the popup window on the button (btnPopup) click of Default.aspx. To do so, we will use Button.Attribute.Add and call a javascript function that will open the popup window. The javascript function will be contained in a seperate pop.js file which we will create shortly. Add this code in the code behind file of your Default.aspx.
C#
protected void Page_Load(object sender, EventArgs e)
    {
        btnPopup.Attributes.Add(“onClick”, “javascript:InvokePop(‘” + txtFName.ClientID + “‘);”);
    }
Over here we are passing the ClientID of the textbox. ClientID is the identifier of the server control, generated by ASP.NET. You must be wondering why I am not passing the value of the textbox directly. Well passing the control has an advantage where there is more than one control that is passed to the popup page. While returning back the values from the popup to the parent page; it helps you to decide and determine which control receives which value. Even though we will be using only one textbox for simplicity, I thought of creating a sample which can be extended later by you to suit your needs. If the use of ClientID is not clear to you, wait till we get to part 2 of this article, and I will again touch upon the subject.

Step 6: Let us now create the javascript functionality which will open the Popup. Right click your project > Add New Item > Jscript file > Rename the file to pop.js. Add the following function to the pop.js file
function InvokePop(fname)
{
        val = document.getElementById(fname).value;
        // to handle in IE 7.0          
        if (window.showModalDialog)
        {      
            retVal = window.showModalDialog(“PopupWin.aspx?Control1=” + fname + “&ControlVal=” + val ,’Show Popup Window’,”dialogHeight:90px,dialogWidth:250px,resizable:yes,center:yes,”);
            document.getElementById(fname).value = retVal;
        }
        // to handle in Firefox
        else
        {     
            retVal = window.open(“PopupWin.aspx?Control1=”+fname + “&ControlVal=” + val,’Show Popup Window’,'height=90,width=250,resizable=yes,modal=yes’);
            retVal.focus();           
        }         
}
This function accepts the textbox control, retrieve’s the value of the textbox that needs to be reversed and passes the textbox control and its value to PopupWin.aspx through query string. This is the function which will be called on the btnPopup click.

Step 7: To wire up the .js with your asp.net pages, add a link to the javascript file in both the pages as shown below:

Default.aspx
<head runat=”server”>
    <title>Parent Page</title>
    <script type=”text/javascript” src=”pop.js”></script>
</head>
PopupWin.aspx
<head runat=”server”>
    <title>Popup Page</title>
    <script type=”text/javascript” src=”pop.js”></script>
</head>

Step 8: In the code behind file of PopupWin.aspx, add the following code at the Page_Load() to retrieve the value from the querystring and display the value in the TextBox ‘txtReverse’, placed in the popup window.
C#
protected void Page_Load(object sender, EventArgs e)
    {
        txtReverse.Text = Request.QueryString["ControlVal"].ToString();
    }
If you are eager to test the value going from Parent page to the popup window, you can do so now. Make Default.aspx as ‘Set as Start page’ and run the sample. Enter your name in txtFName TextBox and click on Show Popup button. A popup window opens with the value entered in the Parent page.

Part 2 - Passing value from Popup window to the Parent page
In this second part, we will reverse the string and pass the reversed string back to the parent page. To do so, follow these steps:

Step 1: Add additional functions to the pop.js file which will reverse the string and return the string back to the parent page.
// pop.js
function ReverseString()
{
         var originalString = document.getElementById(‘txtReverse’).value;
         var reversedString = Reverse(originalString);
         RetrieveControl();
         // to handle in IE 7.0
         if (window.showModalDialog)
         {             
              window.returnValue = reversedString;
              window.close();
         }
         // to handle in Firefox
         else
         {
              if ((window.opener != null) && (!window.opener.closed))
              {              
                // Access the control.       
                window.opener.document.getElementById(ctr[1]).value = reversedString;
              }
              window.close();
         }
}
 
function Reverse(str)
{
   var revStr = “”;
   for (i=str.length – 1 ; i > – 1 ; i–)
   {
      revStr += str.substr(i,1);
   }
   return revStr;
}
 
function RetrieveControl()
{
        //Retrieve the query string
        queryStr = window.location.search.substring(1);
        // Seperate the control and its value
        ctrlArray = queryStr.split(“&”);
        ctrl1 = ctrlArray[0];
        //Retrieve the control passed via querystring
        ctr = ctrl1.split(“=”);
}

As you saw in part 1, the value was passed from the parent window to the popup window and was kept in the txtReverse TextBox. The function ReverseString() retrieves the value from this textbox and passes the string to the Reverse() function which reverses the string. The reversed string is then kept in the ‘reversedString’ variable. The ‘RetrieveControl’ splits the query string and identifies the control in the parent page to which the reversed string value is to be sent.
Note: If you observe, in the IE implementation, I am not really making use of the RetrieveControl(), however in Firefox I am. If you remember, in the beginning of part1 , I had mentioned the use of ClientID, using which both controls and their values can be passed to determine which control recieves which value. This is especially needed when there are multiple controls. Well the RetrieveControl seperates the different controls and you can use the variables in this method to return values to the respective contro.l
The value is then returned to the parent window and the popup window is closed.

Step 2: Now in order to use these newly added javacript functions, just call the ReverseString() function on the btnReverse click. To do so, add the onclick attribute to the btnReverse.
<input class=”button” type=”button” id=”btnReverse” value=”Reverse value back” onclick=”ReverseString();”/>

Good Luck

Getting FCKEditor to work

Filed under: ASP.Net — Tags: — yasserzaid @ 7:29 pm

To install the control I did the following:

1) Downloaded FCK Editor, uncompressed the zip, and copied the FCKEditor folder to my website.

2) Downloaded FCKEditor.net, uncompressed the zip, copied FredCK.FCKEditorV2.dll to a bin sbfolder

3) Added the FredCK.FCKEditorV2.dll to form editor.

4) Dragged the editor to the page.  The resulting file is below.

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Register Assembly="FredCK.FCKeditorV2" Namespace="FredCK.FCKeditorV2" TagPrefix="FCKeditorV2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "<a href="http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">http://www.w3.org/TR/xhtml11/DTD/xhtml11.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>
</head>
<body>
<form id="form1" runat="server">
<div>
<FCKeditorV2:FCKeditor ID="FCKeditor1" runat="server" BasePath ="~/FCKEditor/" ImageBrowserURL="~/FCKEditor/" LinkBrowserURL="~/FCKEditor/" >
</FCKeditorV2:FCKeditor>
</div>
</form>
</body>
</html>

Hope this helps

Good Luck

Getting all Users from Membership by Role

Filed under: ASP.Net — Tags: — yasserzaid @ 7:27 pm

Hi

try this example to Getting all Users from Membership by a specific Role

string[] users = Roles.GetUsersInRole(rolename);

foreach (string user in users)
{

//Response.Write(user.ToString());

//do your emailing here

}

Good Luck

Get last inserted Record ID

Filed under: ASP.Net — yasserzaid @ 7:26 pm

Hi

try this example:

ASPX

<%@ page autoeventwireup=”true” codefile=”RetrieveLastIdentityWithSqlDataSource.aspx.cs”
 inherits=”DetailsView_RetrieveLastIdentityWithSqlDataSource” language=”C#” masterpagefile=”~/MasterPages/Default.master”
 title=”DetailsView: Retrieve Last Identity With SqlDataSource” %>

<asp:content id=”Content1″ runat=”Server” contentplaceholderid=”ContentPlaceHolder1″>
 <asp:detailsview id=”dvSuppliers” runat=”server” autogenerateinsertbutton=”true”
  autogeneraterows=”False” datakeynames=”ShipperID” datasourceid=”sdsSuppliers”
  defaultmode=”Insert”>
  <headertemplate>
   Add Shipper
  </headertemplate>
  <fields>
   <asp:boundfield datafield=”ShipperID” headertext=”ShipperID” insertvisible=”False”
    readonly=”True” />
   <asp:boundfield datafield=”CompanyName” headertext=”CompanyName” />
   <asp:boundfield datafield=”Phone” headertext=”Phone” />
  </fields>
 </asp:detailsview>
 <asp:sqldatasource id=”sdsSuppliers” runat=”server” connectionstring=”<%$ ConnectionStrings:NorthwindConnectionString %>”
  insertcommand=”INSERT INTO Shippers(CompanyName, Phone) VALUES (@CompanyName, @Phone); SELECT @ShipperID = SCOPE_IDENTITY();”
  oninserted=”sdsSuppliers_Inserted” selectcommand=”SELECT * FROM Shippers”>
  <insertparameters>
   <asp:parameter name=”CompanyName” />
   <asp:parameter name=”Phone” />
   <asp:parameter direction=”Output” name=”ShipperID” type=”Int32″ />
  </insertparameters>
 </asp:sqldatasource>
 <asp:label id=”lblShipperId” runat=”server” />
</asp:content>

CODE-BEHIND

using System;
using System.Web.UI.WebControls;

public partial class DetailsView_RetrieveLastIdentityWithSqlDataSource : System.Web.UI.Page
{
   protected void sdsSuppliers_Inserted(object sender, SqlDataSourceStatusEventArgs e)
 {
  if (e.Exception == null)
  {
   lblShipperId.Text = String.Concat(“New ShipperID: “,  e.Command.Parameters["@ShipperID"].Value);
  }
 }
}
Good Luck

Get Current Page URL

Filed under: ASP.Net — yasserzaid @ 7:16 pm

Hi

try this:

System.IO.Path.GetFileName(System.Web.HttpContext. Current.Request.Url.AbsolutePath)
or
System.IO.FileInfo(System.Web.HttpContext.Current. Request.Url.AbsolutePath).Name

Good Luck

Filling Dropdown List from XMLHTTP response

Filed under: ASP.Net — yasserzaid @ 7:13 pm

Hi

Following function is to fill dropdownlist (TEXT and VALUE) from the response we get from handler file. Just pass dropdown ID and the string in this function. 
function FN_fillList(ddl,str){
        var arr = str.split(”;”);
        //To Remove All Items of Drop Down
        document.getElementById(ddl).length = 0;
        document.getElementById(ddl).options[0] = new Option(’Select’,0);
        //To Add Items In Drop Down
        for(var i=1,j=1; i < arr.length;i=i+2,j++){
            document.getEle mentById(ddl).options[j] = new Option(arr[i],arr[i+1]);
        }
    }
Good Luck
Older Posts »

Blog at WordPress.com.