Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 123, comments - 361, trackbacks - 0

My Links

News

Archives

Image Galleries

Sunday, October 18, 2009

Hide Panel When Clicking Anywhere in the Page

This example shows how to hide a Div when clicking anywhere the page:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

      <script type="text/javascript" language="javascript">

        function HideDiv()

        {

             document.getElementById("ContainerDiv").style.display = 'none';

             return false;

        }

        function ShowDiv(e)

        {

            document.getElementById("ContainerDiv").style.display = 'block';

            if(!e)

            e=window.event;

            e.cancelBubble=true;

            return false;

        }

    </script>

</head>

<body onclick="return HideDiv();">

    <form id="form1" runat="server">

    <asp:Button ID="Button1" runat="server" Text="Show Div" OnClientClick="return ShowDiv(event);" />

      <div id="ContainerDiv"

       style="width:521px;

              height:200px;

              background-color:Gray;

              left:150px;

              position:absolute;

              top: 201px;

              display:block"

              align="center"

              onclick ="return ShowDiv(event);">

       HELLO ASP.NET

       <br />

       <asp:TextBox ID="TextBox1" runat="server" onclick = "return ShowDiv(event);"></asp:TextBox>

      </div>

    </form>

</body>

</html>


That's it!

posted @ Sunday, October 18, 2009 2:22 PM | Feedback (0) |

Thursday, October 08, 2009

Move Multiple Rows Between GridViews

This example shows how to move multiple rows between GridViews. The main idea here is to use a CheckBox control for selecting the rows to be removed from one GridView to another and vise versa.

 

Take a look at sample screen shots below:

 

On initial load:



 Selecting rows from the left GridView:


 

After Moving the selected rows to the right GridView:

As you notice the selected rows are automatically sorted by its ID upon moving.

Selecting rows from the Right GridView:

After Moving the selected rows to the Left GridView:



Here are the code blocks below for the implementation:


ASPX SOURCE:

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    </div>

    <table>

        <tr>

            <td valign="top">

                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

                <Columns>

                    <asp:TemplateField>

                        <ItemTemplate>

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

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:BoundField DataField="EmployeeID" HeaderText="ID" />

                    <asp:BoundField DataField="LastName" HeaderText="Last Name" />

                    <asp:BoundField DataField="FirstName" HeaderText="First Name" />

                </Columns>

                </asp:GridView>

            </td>

            <td>

                <asp:Button ID="Button1" runat="server" Text=">>>" onclick="Button1_Click" />

                <br />

                <asp:Button ID="Button2" runat="server" Text="<<<" onclick="Button2_Click" />

            </td>

            <td valign="top">

               <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">

                <Columns>

                    <asp:TemplateField>

                        <ItemTemplate>

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

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:BoundField DataField="EmployeeID" HeaderText="ID" />

                    <asp:BoundField DataField="LastName" HeaderText="Last Name" />

                    <asp:BoundField DataField="FirstName" HeaderText="First Name" />

                </Columns>

              </asp:GridView>

            </td>

        </tr>

    </table>

    </form>

</body>

</html>

 

 

RELEVANT CODES:

 

public partial class AddMultipleRowsGridView : System.Web.UI.Page

{

    private DataTable _clonedTable;

 

    private string GetConnectionString()

    {

        return @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Northwind.mdf;Integrated Security=True;User Instance=True";

    }

 

    private DataTable QueryData()

    {

        DataTable dt = new DataTable();

        SqlConnection connection = new SqlConnection(GetConnectionString());

        try

        {

            connection.Open();

            string sqlStatement = "SELECT TOP(10)EmployeeID, LastName, FirstName FROM Employees";

            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);

            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            sqlDa.Fill(dt);

        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            string msg = "Fetch Error:";

            msg += ex.Message;

            throw new Exception(msg);

        }

        finally

        {

            connection.Close();

        }

 

        return dt;

    }

 

    private void BindGrid(DataTable dt, GridView gv)

    {

        if (dt.Rows.Count > 0)

        {

            dt = TrimEmptyRow(dt);

            gv.DataSource = SortData(dt);

            gv.DataBind();

        }

        else

        {

            ShowNoResultFound(dt, gv);

        }

        if (gv.ID == "GridView1")

            ViewState["OrigData"] = dt;

        else

        {

            ViewState["MovedData"] = dt;

        }

    }

    private DataTable SortData(DataTable dt)

    {

        DataView dv = dt.DefaultView;

        dv.Sort = "EmployeeID ASC";

        dt = dv.ToTable();

 

        return dt;

    }

       

    private void MoveRows(DataTable dt, GridView gv)

    {

            for (int i = gv.Rows.Count - 1; i >= 0; i--)

            {

                CheckBox cb = (CheckBox)gv.Rows[i].Cells[0].FindControl("CheckBox1");

                if (cb != null)

                {

                    if (cb.Checked)

                    {

                        AddRow(dt.Rows[i], gv);

                        dt.Rows.Remove(dt.Rows[i]);

                    }

                }

            }

            BindGrid(dt, gv);

    }

 

    private void AddRow(DataRow row,GridView gv)

    {

        DataTable dt = null;

        if (ViewState["MovedData"] == null)

        {

            dt = (DataTable)ViewState["ClonedTable"];

            dt.ImportRow(row);

            dt.Rows.Remove(dt.Rows[0]);

            ViewState["MovedData"] = dt;

            BindGrid(dt, GridView2);

        }

        else

        {

            if (gv.ID == "GridView1")

            {

                dt = (DataTable)ViewState["MovedData"];

                dt.ImportRow(row);

                ViewState["MovedData"] = dt;

                BindGrid(dt, GridView2);

            }

            else

            {

                dt = (DataTable)ViewState["OrigData"];

                dt.ImportRow(row);

                ViewState["OrigData"] = dt;

                BindGrid(dt, GridView1);

            }

        }

    }

 

    private DataTable TrimEmptyRow(DataTable dt)

    {

        if (dt.Rows[0][0].ToString() == string.Empty)

        {

            dt.Rows.Remove(dt.Rows[0]);

        }

        return dt;

    }

 

    private void ShowNoResultFound(DataTable source, GridView gv)

    {

 

        source.Rows.Add(source.NewRow()); // create a new blank row to the DataTable

        // Bind the DataTable which contain a blank row to the GridView

        gv.DataSource = source;

        gv.DataBind();

        // Get the total number of columns in the GridView to know what the Column Span should be

        int columnsCount = gv.Columns.Count;

        gv.Rows[0].Cells.Clear();// clear all the cells in the row

        gv.Rows[0].Cells.Add(new TableCell()); //add a new blank cell

        gv.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell

        //You can set the styles here

        gv.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;

        gv.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;

        gv.Rows[0].Cells[0].Font.Bold = true;

        //set No Results found to the new added cell

        gv.Rows[0].Cells[0].Text = "NO ITEMS FOUND!";

 

    }

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            BindGrid(QueryData(), GridView1);

            _clonedTable = QueryData().Clone();

            ViewState["ClonedTable"] = _clonedTable;

 

            ShowNoResultFound(_clonedTable, GridView2);

        }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        DataTable dtOrigData = (DataTable)ViewState["OrigData"];

        MoveRows(SortData(dtOrigData), GridView1);

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        DataTable dtMovedData = (DataTable)ViewState["MovedData"];

        MoveRows(SortData(dtMovedData), GridView2);

    }

}

 


As you can see the code above was very self explanatory and straight forward. Hope you will find this example useful!


posted @ Thursday, October 08, 2009 11:19 PM | Feedback (0) |

Thursday, September 10, 2009

How To: Reset Identity Column Value in SQL Table

Recently, one of the members at forums.asp.net is asking if how to reset identity count in sql table. So I thought of sharing the possible solution that we have discussed in this thread as a reference to others.

HTH!

posted @ Thursday, September 10, 2009 2:17 PM | Feedback (0) |

Monday, September 07, 2009

Good News!: SEA MVPs Blog-A-Holic has Officially Launched Today

Check this out:

Microsoft SEA MVP Blog

posted @ Monday, September 07, 2009 1:49 PM | Feedback (0) |

Tuesday, September 01, 2009

BASIC: Binding ListBox and DropDownList using LINQ

This example shows the basic way on how to populate a data from database to a ListBox/DropDownList control using LINQ to SQL.

 

Note that I used Northwind database here just for the simplicity of this example.

 

To get started then let’s go ahead and add a new item in your website application in Visual Studio 2008 or VWD Express 2008. To do this, just right click on the web site -> select Add New Item -> and on the Templates select LINQ to SQL Classes as shown below and click ok:

 

 

Now open up Server Exporer in Visual Studio and do the follwing:

 

* Under Data Connections, expand the northwind database

* Expand the Table folder and select the Table that you want to use and drag it on the Data Context. Note that I used the product table in this example as shown below:

 

 

Now add a new webform then grab a ListBox and a DropDownList control from the Visual Studio ToolBox and place it on the ASPX source. The mark up would look something like this:

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>LINQ Basics Demo</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>

        <asp:DropDownList ID="DropDownList1" runat="server">

        </asp:DropDownList>

    </div>

    </form>

</body>

</html>

 

And here are the code blocks below for binding the ListBox and DropDownList control using LINQ:

 

using System;

using System.Collections;

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;

 

public partial class LINQDemo : System.Web.UI.Page

{

    private void ShowProducts()

    {

        //create new instance of the the DataContext class that we have just created

        DataClassesDataContext db = new DataClassesDataContext();

        FillListBox(db);

    }

    private void FillListBox(DataClassesDataContext db)

    {

        //LINQ syntax

        //Select the ProductID and ProductName from Products

        var products = from c in db.Products

        select new

        {

            ProductID = c.ProductID,

            ProductName = c.ProductName,

        };

 

        //Bind the ListBox

        ListBox1.DataSource = products;

        ListBox1.DataTextField = "ProductName";

        ListBox1.DataValueField = "ProductID";

        ListBox1.DataBind();

 

       //Bind the DropDownList

        DropDownList1.DataSource = products;

        DropDownList1.DataTextField = "ProductName";

        DropDownList1.DataValueField = "ProductID";

        DropDownList1.DataBind();

 

    }

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            ShowProducts();

        }

    }

}

 

 

As you can see the code above is straight forward and self explanatory. That's it!

posted @ Tuesday, September 01, 2009 6:33 PM | Feedback (3) |

Wednesday, August 26, 2009

Passing Information from .HTM to ASPX page in ASP.NET

Just recently, one of the members at forums.asp.net is asking if how to pass data from .htm page to aspx page. So I decided to share with you of what we have discussed in this thread for a possible solution.

posted @ Wednesday, August 26, 2009 7:17 PM | Feedback (0) |

How To: Prevent SQL Injection in ASP.NET

Mike Brind has written a very good example about "Preventing SQL Injection in ASP.NET". If you are new to Data Access manipulations in ASP.NET then I would strongly suggest you to read the article mentioned above.

posted @ Wednesday, August 26, 2009 7:16 PM | Feedback (0) |

Tuesday, August 18, 2009

Accessing Controls from ASPX to External JavaScript file

This example shows the basic way on how to access control from external javascript file (.js). Normally, we use the following line below when accessing control within our JavaScript method in the page.

document.getElementById('<%= TextBox1.ClientID %>');

AFAIK, Using  Inline expression like <% %> will not work within external  js files. As a workaround we can pass the id of the control (eg. TextBox) to the funciton as a parameter instead like:

External JS file:

 

function GetControlValue(obj)

{

   var box =  document.getElementById(obj);

   alert(box.value); // returns the value "Hello ASPNET"

}

ASPX:

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<title>Untitled Page</title>

<script src="JScript.js" type="text/javascript"></script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:TextBox ID="TextBox1" Text="Hello ASPNET" runat="server" />

        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="GetControlValue('TextBox1');" />

    </div>

    </form>

</body>

</html>

 

As you notice, we passed the ID of TextBox control which is "TextBox1" to the Javascript function and get the value to perform certain actions or conditions based on the value.

posted @ Tuesday, August 18, 2009 10:10 PM | Feedback (1) |

Thursday, August 13, 2009

Bind DataTable to DataList Control

This example shows how to bind a DataTable in a DataList control. Just for the simplicity of this demo I’m going to create a dummy data in the DataTable. See the code blocks below:

 

private DataTable GetData()

{

        DataTable dt = new DataTable();

        DataRow dr;

        dt.Columns.Add(new System.Data.DataColumn("Column1", typeof(String)));

        dt.Columns.Add(new System.Data.DataColumn("Column2", typeof(String)));

        dt.Columns.Add(new System.Data.DataColumn("Column3", typeof(String)));

 

        dr = dt.NewRow();

        dr[0] = "Column1 Item A";

        dr[1] = "Column2 Item B";

        dr[2] = "Column3 Item C";

        dt.Rows.Add(dr);

 

        dr = dt.NewRow();

        dr[0] = "Column1 Item AA";

        dr[1] = "Column2 Item BB";

        dr[2] = "Column3 Item CC";

        dt.Rows.Add(dr);

 

        dr = dt.NewRow();

        dr[0] = "Column1 Item AAA";

        dr[1] = "Column2 Item BBB";

        dr[2] = "Column3 Item CCC";

        dt.Rows.Add(dr);

 

        dr = dt.NewRow();

        dr[0] = "Column1 Item AAAA";

        dr[1] = "Column2 Item BBBB";

        dr[2] = "Column3 Item CCCC";

        dt.Rows.Add(dr);

 

        return dt;

}

 

Now let’s set up the DataList in the ASPX source like below.

 

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

        <HeaderTemplate>

               <table>

                    <tr>

                    <th style="width:150px" align="left">HEADER 1</th>

                    <th style="width:150px" align="left">HEADER 2</th>

                    <th style="width:150px" align="left">HEADER 3</th>

                    </tr>

                </table>

        </HeaderTemplate>

        <ItemTemplate>

                <table>

                    <tr>

                     <td style="width:150px" align="left"> <asp:Label ID="LabelTest1" Text='<%# DataBinder.Eval(Container.DataItem, "Column1") %>' runat="server" /></td>

                     <td style="width:150px" align="left"> <asp:Label ID="LabelTest2" Text='<%# DataBinder.Eval(Container.DataItem, "Column2") %>' runat="server" /></td>

                     <td style="width:150px" align="left"> <asp:Label ID="LabelTest3" Text='<%# DataBinder.Eval(Container.DataItem, "Column3") %>' runat="server" /></td>

                    </tr>

                </table>

        </ItemTemplate>

</asp:DataList>

 

As you can see, the set up above was very simple. Now let’s go switch back to the code behind part of the page and bind the DataList with the data from the DataTable. Here’s the code block below:

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            DataTable dt = GetData();

            DataList1.DataSource = dt;

            DataList1.DataBind();

        }

    }

 

That’s Simple!

posted @ Thursday, August 13, 2009 10:41 PM | Feedback (0) |

Wednesday, August 12, 2009

Retain Leading Zeros when Converting from Int to String

Many members in the forums are asking if why is it that an integer value with a leading zero is being trimmed off when converting it to a string?

 

Consider this example:

 

        int num = 0123456; // a 7 numbers

        string sNum = num.ToString();

 

        //The result will give you 123456

 

 

What happened to the leading zero?

 

Well basically, leading zero has no significance to an integer because by nature an integer with a value of 01 is simply the same as 1. So based on the example above we have an integer value of 0123456 and basically it outputs 123456 (without the leading zero).

 

How can we retain them when we need to display them?

 

That’s the main reason why I decided to write this post. Here’s one way on how to retain them when converting it to string.

 

        int num = 0123456; // a 7 numbers

        string sNum = num.ToString("0000000");

 

        Response.Write(sNum);

        //The result will give you 0123456

 

The trick there is we used ToString() with the format "0000000" where the number of zero is equal to number of digits your integer has. So since we have a 7 digit integer value then we used 7 zeros in the format.

 

That’s it! Hope you will find this post useful!

posted @ Wednesday, August 12, 2009 8:56 PM | Feedback (0) |

Powered by: