Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for July, 2008

Modal Popup Dialog Window in ASP.NET

Posted by Ramani Sandeep on July 25, 2008

This sample creates parent and child webforms. The child webform is called modally by the parent passing multiple values to the child form. The child form displays the passed values allowing them to be edited and then returns the altered values back to the parent when finished. The child form is modal to only the parent form. To make the child modal to the entire desktop, see the below final note.

1. Open a New Web project in Visual Studio
2.
Create two New WebForm pages named ParentWebForm and ChildWebForm
3.
Open the HTML surface for the ParentWebForm
4.
Locate the yellow line
5.
Delete all code EXCEPT the yellow line
6.
Insert the following HTML below the existing yellow line

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
    <HEAD>
        <title>Parent Webform</title>
        <script language="javascript">
function OpenChild()
{
    var ParmA = retvalA.value;
    var ParmB = retvalB.value;
    var ParmC = retvalC.value;
    var MyArgs = new Array(ParmA, ParmB, ParmC);
    var WinSettings = "center:yes;resizable:no;dialogHeight:300px"
    //ALTER BELOW LINE - supply correct URL for Child Form

    var MyArgs = window.showModalDialog(
   "http://localhost/ModalWin/ChildWebForm.aspx", MyArgs, WinSettings);
    if (MyArgs == null)
    {
        window.alert(
          "Nothing returned from child. No changes made to input boxes")
    }
    else
    {
        retvalA.value=MyArgs[0].toString();
        retvalB.value=MyArgs[1].toString();
        retvalC.value=MyArgs[2].toString();
    }
}
        </script>
    </HEAD>
    <body>
        <P><INPUT id="retvalA" type="text" value="AAA"></P>
        <P><INPUT id="retvalB" type="text" value="BBB"></P>
        <P><INPUT id="retvalC" type="text" value="CCC"></P>
        <P><BUTTON onclick="OpenChild()" type="button">
                Open Child Window</BUTTON>
        </P>
    </body>
</HTML>

7. In the above code, locate the line saying //ALTER BELOW LINE

8. Supply the correct URL for your Child Webform

9. Open the HTML surface for the ChildWebForm

10. Locate the yellow line

11. Delete all code EXCEPT the yellow line

12. Insert the following HTML below the existing yellow line

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
    <HEAD>
        <TITLE>Child Webform</TITLE>
        <script language="javascript">
function Done() {
    var ParmA = tbParamA.value;
    var ParmB = tbParamB.value;
    var ParmC = tbParamC.value;
    var MyArgs = new Array(ParmA, ParmB, ParmC);
    window.returnValue = MyArgs;
    window.close();
}
function doInit() {
    var ParmA = "Aparm";
    var ParmB = "Bparm";
    var ParmC = "Cparm";
    var MyArgs = new Array(ParmA, ParmB, ParmC);
    MyArgs =  window.dialogArguments;
    tbParamA.value = MyArgs[0].toString();
    tbParamB.value = MyArgs[1].toString();
    tbParamC.value = MyArgs[2].toString();
}
        </script>
    </HEAD>
    <BODY onload="doInit()">
        <P>Param A:<INPUT id="tbParamA" TYPE="text"></P>
        <P>Param B:<INPUT ID="tbParamB" TYPE="text"></P>
        <P>Param C:<INPUT ID="tbParamC" TYPE="text"></P>
        <BUTTON onclick="Done()" type="button">OK</BUTTON>
    </BODY>
</HTML>

13. Set the project StartUp page to be the Parent Webform

14. Run the project.

Final Note:

To make the child modal to the entire desktop, you’ll need add code to the child which uses

<body onblur="this.focus">


Reference : click here

Posted in ASP.NET Ajax | Tagged: , , | 5 Comments »

Selecting All CheckBoxes in GridView

Posted by Ramani Sandeep on July 19, 2008

This article will contain code that is used to Check / Uncheck checkbox in Gridview.

javascript on the page is :

<script type="text/javascript">

    var TotalChkBx;

    var Counter;

    window.onload = function()

    {

        //Get total no. of CheckBoxes in side the GridView.

        TotalChkBx = parseInt('<%= this.gvCheckboxes.Rows.Count %>');

        //Get total no. of checked CheckBoxes in side the GridView.

        Counter = 0;

    }

    function HeaderClick(CheckBox)

    {

        //Get target base & child control.

        var TargetBaseControl = document.getElementById('<%= this.gvCheckboxes.ClientID %>');

        var TargetChildControl = "chkBxSelect";

 

        //Get all the control of the type INPUT in the base control.

        var Inputs = TargetBaseControl.getElementsByTagName("input");

 

        //Checked/Unchecked all the checkBoxes in side the GridView.

        for(var n = 0; n < Inputs.length; ++n)

            if(Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl,0) >= 0)

                Inputs[n].checked = CheckBox.checked;

        //Reset Counter

        Counter = CheckBox.checked ? TotalChkBx : 0;

    }

    function ChildClick(CheckBox, HCheckBox)

    {

        //get target base & child control.

        var HeaderCheckBox = document.getElementById(HCheckBox);

 

        //Modifiy Counter;

        if(CheckBox.checked && Counter < TotalChkBx)

            Counter++;

        else if(Counter > 0)

            Counter--;

 

        //Change state of the header CheckBox.

        if(Counter < TotalChkBx)

            HeaderCheckBox.checked = false;

        else if(Counter == TotalChkBx)

            HeaderCheckBox.checked = true;

    }

</script>

Html Code on the Page is :

<asp:GridView ID="gvCheckboxes" runat="server" AutoGenerateColumns="False" OnRowCreated="gvCheckboxes_RowCreated">

    <Columns>

        <asp:BoundField HeaderText="S.N." DataField="sno">

            <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />

            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />

        </asp:BoundField>

        <asp:TemplateField HeaderText="Select">

            <ItemTemplate>

                <asp:CheckBox ID="chkBxSelect" runat="server" />

            </ItemTemplate>

            <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />

            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />

            <HeaderTemplate>

                <asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server" />

            </HeaderTemplate>

        </asp:TemplateField>

        <asp:TemplateField>

            <ItemTemplate>

                <asp:CheckBox ID="chkBx" runat="server" />

            </ItemTemplate>

            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />

        </asp:TemplateField>

    </Columns>

    <RowStyle BackColor="Moccasin" />

    <AlternatingRowStyle BackColor="NavajoWhite" />

    <HeaderStyle BackColor="DarkOrange" Font-Bold="True" ForeColor="White" />

</asp:GridView>

Code Behind code :

protected void Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

        BindGridView();

    }

}

 

protected void BindGridView()

{

    gvCheckboxes.DataSource = GetDataSource();

    gvCheckboxes.DataBind();

}

 

protected DataTable GetDataSource()

{

    DataTable dTable = new DataTable();

    DataRow dRow = null;

    Random rnd = new Random();

    dTable.Columns.Add("sno");

 

    for (int n = 0; n < 10; ++n)

    {

        dRow = dTable.NewRow();

 

        dRow["sno"] = n + ".";

 

        dTable.Rows.Add(dRow);

        dTable.AcceptChanges();

    }

 

    return dTable;

}

 

protected void gvCheckboxes_RowCreated(object sender, GridViewRowEventArgs e)

{

    if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState ==

 

    DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))

    {

        CheckBox chkBxSelect = (CheckBox)e.Row.Cells[1].FindControl("chkBxSelect");

        CheckBox chkBxHeader = (CheckBox)this.gvCheckboxes.HeaderRow.FindControl("chkBxHeader");

 

        chkBxSelect.Attributes["onclick"] = string.Format("javascript:ChildClick(this,'{0}');",

 

        chkBxHeader.ClientID);

    }

}

Posted in ASP.NET, C# 2.0, JavaScript | Tagged: , | 1 Comment »

Deleting Multiple Rows in a GridView

Posted by Ramani Sandeep on July 18, 2008

If you have used Hotmail or any other similar email client, you might have observed that  we have the option of selecting multiple rows (using the checkbox provided) and perform a set of operations on them. In this article, we will replicate this scenario for a gridview.

A gridview allows us to delete only a single row at a time. We will extend this functionality to select multiple rows and delete all of the selected rows in a single stroke. In this article, I assume that you are aware of creating asp.net web applications and have worked with gridview.

The sample makes use of the Northwind database. We will be pulling data from the Employee table. For this sample to work, drop all the Foreign Key relationships on the Employee Table. To do so, in Sql Server Management Studio, browse to the Northwind database and open the Employee table in design view. Right click in the Table designer on the right hand side and choose ‘Relationships’. Select all the relationships like FK_Orders_Employees,  FK_EmployeeTerritories_Employees etc and delete them. This step is necessary as we will get a constraint violation exception if we do not do so.

Once we are through with the task of removing the relationships in the Employee table, let us explore the steps to create a gridview with functionality to delete multiple rows at a time.

Perform the following steps :

Step 1: Create an .aspx page and add a GridView and a SqlDataSource control to it.

Step 2: Configure the connection of SqlDataSource to point to the Northwind database.  Create queries for the Select and Delete commands.

The resultant code will look similar as given below :

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"

    SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"

    DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"

    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >

 

    <DeleteParameters>

        <asp:Parameter Name="EmployeeID" />

    </DeleteParameters>

</asp:SqlDataSource>

Step 3: Once the SqlDataSource has been configured, bind the gridview with this data source.

Step 4: To create a checkbox in each row, follow these steps:

1. Create a TemplateField inside the <Columns> to add custom content to each column.

2. Inside the TemplateField, create an ItemTemplate with a CheckBox added to it.

<asp:TemplateField> 

    <ItemTemplate> 

        <asp:CheckBox ID="chkRows" runat="server"/> 

    </ItemTemplate> 

</asp:TemplateField>

This will add a checkbox to each row in the grid.

Step 5: Add a button control, and rename it to btnMultipleRowDelete.The resultant markup in the design view will look similar to the code below :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">

    <Columns> 

        <asp:TemplateField> 

            <ItemTemplate> 

                <asp:CheckBox ID="cbRows" runat="server"/> 

            </ItemTemplate> 

        </asp:TemplateField>

        <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" /> 

        <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" /> 

        <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" /> 

    </Columns> 

</asp:GridView>

 

<asp:SqlDataSource ID="SqlDataSource1" Runat="server" 

    SelectCommand="SELECT EmployeeID, LastName, City FROM Employees" 

    DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID" 

    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" > 

 

    <DeleteParameters> 

        <asp:Parameter Name="EmployeeID" /> 

    </DeleteParameters> 

</asp:SqlDataSource>

 

<asp:Button ID="btnMultipleRowDelete"  OnClick="btnMultipleRowDelete_Click" runat="server"  Text="Delete Rows" />

 

Our code will first loop through all the rows in the GridView. If a row is checked, the code retrieves the EmployeeID and passes the selected value to the Delete Command.

protected void btnMultipleRowDelete_Click(object sender, EventArgs e) 

{ 

    // Looping through all the rows in the GridView 

    foreach (GridViewRow row in GridView1.Rows) 

    { 

        CheckBox checkbox = (CheckBox)row.FindControl("cbRows");

 

        //Check if the checkbox is checked. 

        //value in the HtmlInputCheckBox's Value property is set as the

 

        //value of the delete command's parameter. 

        if (checkbox.Checked) 

        { 

            // Retreive the Employee ID 

            int employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);

    

            // Pass the value of the selected Employye ID to the Delete //command. 

            SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue = employeeID.ToString(); 

            SqlDataSource1.Delete(); 

        }

    } 

} 

Hope this will Help you !!!

Posted in ASP.NET | Tagged: , , | 13 Comments »

Data Access Layer – C#

Posted by Ramani Sandeep on July 18, 2008

This data access layer is used in turn by other program modules to access and manipulate the data within the data store without having to deal with the complexities inherent in this access.

For example, instead of using commands such as insert, delete, and update to access a specific table in a database, a class and a few stored procedures could be created in the database. The procedures would be called from a method inside the class, which would return an object containing the requested values. Or, the insert, delete and update commands could be executed within simple functions like registeruser or loginuser stored within the data access layer.

Web.config:

<connectionStrings>

    <add 

        name="ConnectionString" 

        connectionString="Data Source=server;InitialCatalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=sa"

        providerName="System.Data.SqlClient" />

</connectionStrings>

 

Step 1 :  Create WebConfiguration.cs under App_Code with the following code:

using System;

using System.Configuration;

 

/// <;summary>

/// Repository for configuration settings

/// <;/summary>

 

public static class WebConfiguration

{

    // Caches the connection string

    private readonly static string dbConnectionString;

    // Caches the data provider name

    private readonly static string dbProviderName;

    // Initialize various properties in the constructor

    static WebConfiguration()

    {

        dbConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        dbProviderName = ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName;

    }

    // Returns the connection string for the database

    public static string DbConnectionString

    {

        get

        {

            return dbConnectionString;

        }

    }

    // Returns the data provider name

    public static string DbProviderName

    {

        get

        {

            return dbProviderName;

        }

    }

}

 

Step 2 : Create Class GenericDataAccess.cs with following code:

using System;

using System.Data;

using System.Data.Common;

using System.Configuration;

 

/// <;summary>

/// Class contains generic data access functionality to be accessed from

/// the business tier

/// <;/summary>

 

public class GenericDataAccess

{

    // static constructor

    static GenericDataAccess()

    {

    }    

    // execute a command and return the results as a DataTable object

    public DataTable ExecuteSelectCommand(DbCommand command)

    {

        // The DataTable to be returned

        DataTable table;

        // Execute the command making sure the connection gets closed in the end

        try

        {

            // Open the data connection

            command.Connection.Open();

            // Execute the command and save the results in a DataTable

            DbDataReader reader = command.ExecuteReader();

            table = new DataTable();

            table.Load(reader);

            // Close the reader

            reader.Close();

        }

        catch (Exception ex)

        {

            //Utilities.LogError(ex);

            throw ex;

        }

        finally

        {

            // Close the connection

            command.Connection.Close();

        }

        return table;

    }

 

    // execute an update, delete, or insert command

    // and return the number of affected rows

    public int ExecuteNonQuery(DbCommand command)

    {

        // The number of affected rows

        int affectedRows = -1;

        // Execute the command making sure the connection gets closed in the end

        try

        {

            // Open the connection of the command

            command.Connection.Open();

    

            // Execute the command and get the number of affected rows

            affectedRows = command.ExecuteNonQuery();

        }

        catch (Exception ex)

        {

            // Log eventual errors and rethrow them

            //Utilities.LogError(ex);

            throw ex;

        }

        finally

        {

            // Close the connection

            command.Connection.Close();

        }

        // return the number of affected rows

        return affectedRows;

    }

    // execute a select command and return a single result as a string

    public string ExecuteScalar(DbCommand command)

    {

        // The value to be returned

        string value = "";

        // Execute the command making sure the connection gets closed in the end

        try

        {

            // Open the connection of the command

            command.Connection.Open();

            // Execute the command and get the number of affected rows

            value = command.ExecuteScalar().ToString();

        }

        catch (Exception ex)

        {

            //Utilities.LogError(ex);

            //throw ex;

        }

        finally

        {

            // Close the connection

            command.Connection.Close();

        }

        // return the result

        return value;

    }

 

    // creates and prepares a new DbCommand object on a new connection

    public DbCommand CreateCommand()

    {

        // Obtain the database provider name

        string dataProviderName = WebConfiguration.DbProviderName;

    

        // Obtain the database connection string

        string connectionString = WebConfiguration.DbConnectionString;

        // Create a new data provider factory

        DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName);

        // Obtain a database specific connection object

        DbConnection conn = factory.CreateConnection();

        // Set the connection string

        conn.ConnectionString = connectionString;

        // Create a database specific command object

        DbCommand comm = conn.CreateCommand();

        // Set the command type to stored procedure

        comm.CommandType = CommandType.StoredProcedure;

        // Return the initialized command object

        return comm;

    }

 

    //creates and prepares a new DbCommand object on a new connection(For QueryText)

    public DbCommand CreateCommand4QueryText()

    {

        // Obtain the database provider name

        string dataProviderName = WebConfiguration.DbProviderName;

        // Obtain the database connection string

        string connectionString = WebConfiguration.DbConnectionString;

        // Create a new data provider factory

        DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName);

        // Obtain a database specific connection object

        DbConnection conn = factory.CreateConnection();

        // Set the connection string

        conn.ConnectionString = connectionString;

        // Create a database specific command object

        DbCommand comm = conn.CreateCommand();

        // Set the command type to stored procedure

        comm.CommandType = CommandType.Text;

        // Return the initialized command object

        return comm;

    }

}

 

Step 3: Create BAL Folder under App_Code and start creating your BAL Classes & Use it on Presentation layer

using System;

using System.Data.Common;

using PropertyPortal.Common;

using System.Data;

 

public class BAL_AddAdImage

{

    public BAL_AddAdImage()

    {

    }

 

    public static DataTable getPropertyImageAll(int PropertyID)

    {

        // get a configured DbCommand object

        GenericDataAccess gda = new GenericDataAccess();

        DbCommand comm = gda.CreateCommand();

 

        // set the stored procedure name

        comm.CommandText = "PropertyDB_GetPropertyImageDetails_All";

    

        // create a new parameter

        DbParameter param = comm.CreateParameter();

        param.ParameterName = "@PropertyID";

        param.Value = PropertyID;

        param.DbType = DbType.Int32;

        comm.Parameters.Add(param);

        // return the result table

        DataTable table = gda.ExecuteSelectCommand(comm);

        return table;

    }

 

    public static string GetImagePath(int ImageID)

    {

        // get a configured DbCommand object

        GenericDataAccess gda = new GenericDataAccess();

        DbCommand comm = gda.CreateCommand();

 

        // set the stored procedure name

        comm.CommandText = "PropertyDB_GetPropertyImagePath";

        // create a new parameter

        DbParameter param = comm.CreateParameter();

        param.ParameterName = "@ImageID";

        param.Value = ImageID;

        param.DbType = DbType.Int32;

        comm.Parameters.Add(param);

        string path = gda.ExecuteScalar(comm).ToString();

        return path;

    }

    public static bool Delete(int ImageID)

    {

        // get a configured DbCommand object

        GenericDataAccess gda = new GenericDataAccess();

        DbCommand comm = gda.CreateCommand();

    

        // set the stored procedure name

        comm.CommandText = "PropertyDB_PropertyImageDetails_Delete";

        // create a new parameter

        DbParameter param = comm.CreateParameter();

        param.ParameterName = "@ImageID";

        param.Value = ImageID;

        param.DbType = DbType.Int32;

        comm.Parameters.Add(param);

        int retval = gda.ExecuteNonQuery(comm);

 

        if (retval >; 0)

            return true;

        else

            return false;

    }

}

Posted in ADO.NET, ASP.NET, C# 2.0 | Tagged: , , , , , , , | Leave a Comment »

Displaying Image in Datalist from SQL Server

Posted by Ramani Sandeep on July 14, 2008

This article describes how to display images which are stored in a database.

 

Step 1: Create page Default.aspx with following code

 

Here is the code on Default.aspx Page:

<asp:DataList ID="myList" runat="server">

       <ItemTemplate>

           <table>

                <tr>

                <td width="20%">

                    <asp:Image ID="Image1" runat="server"  Width="150" Height="125" 

                        ImageUrl='<%# DataBinder.Eval(Container.DataItem, "TestimonialID","ReadRealImage.aspx?ID={0}") %>'/>                       

                </td>

                <td>

                <asp:Label ID="mylabel" runat="Server" text='<%#Eval("Testimonial") %>' />                    

               </td>

            </tr>

        </table>

    </ItemTemplate>

</asp:DataList>

Step 2: Code Behind will contain the code shown below

Here is the code on Default.aspx.cs:

protected void Page_Load(object sender, EventArgs e)

{

    if (IsPostBack != true)

    {

        LoadTestimonials();

    }

}

private void LoadTestimonials()

{

    dlTestimonials.DataSource = BAL_Testimonial.SelectAll();

    dlTestimonials.DataBind();

}

Step 3: Create Page that will return Image as Output.

Here you also create httpHandler. Get the ID from Image that you want to return from QueryString[“ID”].

Here is the code on ReadRealImage.aspx:

protected void Page_Load(object sender, EventArgs e)

{

    int TestimonialID = 0;

    if (Request.QueryString["ID"].ToString() != null)

    {

        TestimonialID = Convert.ToInt32(Request.QueryString["ID"].ToString());

    }

    SQLHelper objSQLHelper = new SQLHelper();

    System.Data.SqlClient.SqlConnection _SqlConn = objSQLHelper.SQLConn;

    SqlCommand _SqlCommand = new SqlCommand("JobsDb_Testimonial_Select", _SqlConn);

    _SqlCommand.CommandType = System.Data.CommandType.StoredProcedure;

    _SqlCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@TestimonialID", TestimonialID));

 

    _SqlConn.Open();

    SqlDataReader reader = _SqlCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);     

    if (reader.HasRows)

    {

        while (reader.Read())

        {

            Response.ContentType = reader["PicType"].ToString();

            Response.BinaryWrite((byte[])reader["Pic"]);

        }

    }

    reader.Close();

}

Step 4: Procedure & Tables Details

 

Here i have given you the procedure that i have used in my example, you can user your table & procedure in which the Images are stored.

CREATE PROCEDURE [dbo].[Testimonial_Select]

    @TestimonialID int

AS

BEGIN

    SELECT PicType,Pic FROM [dbo].Testimonials WHERE TestimonialID = @TestimonialID

END

GO

 

CREATE PROCEDURE [dbo].[Testimonial_SelectAll]

AS

BEGIN

    SELECT * FROM [dbo].Testimonials 

END

 

Hope this will Help !!!

Posted in ASP.NET | Tagged: , , | Leave a Comment »

Change Master Page Dynamically

Posted by Ramani Sandeep on July 14, 2008

Here i the code that shows how to change master page of the page at runtime:

protected void Page_PreInit(object sender, EventArgs e) 

{ 

 if (Session["UserAccount"] == null) //check the user weather user is logged in or not

    this.Page.MasterPageFile = "~/General.master";

 else

    this.Page.MasterPageFile = "~/Member.master";

}

Hope this will help !!!

Posted in ASP.NET | Tagged: , , | Leave a Comment »