2012-07-31

How to change label text of a particular row in GridView on click of a button next to it

Following example code demonstrates how to access another control in the same row as the clicked button, and change it’s behavior.

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" OnRowCommand="List_RowCommand">
        <Columns>
            <asp:TemplateField HeaderText="Status">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Action">
                <ItemTemplate>
                    <asp:LinkButton CommandName="Activate" ID="lnkActivate"
                        runat="server" Text="testlink"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

Here, I’m going to change the text of Label1 when the testlink button Clicked. Following is the code behind (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Data;

namespace WebApplication1
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("column1");

            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void List_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            GridViewRow clickedRow = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;
            Label lblID = (Label)clickedRow.FindControl("Label1");
            lblID.Text = "Some text here";
        }
    }
}

Now when the user press the link button, text of the Label which is associated in the same row will change to “Some text here”. In this example, I’m having only a one row.

2012-07-30

How to retain values of dynamically created controls in asp.net

Dynamically generated controls are getting lost whenever a post back happens. There is actually no way to keep them persistent across post backs. What we can do is, store the dynamically created controls in session and restore them back from the session when a post back happens. Following example demonstrate how to store the dynamically generated controls in session and restore them back when a post back happens.

ASPX code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="HowManyToGenerateTextBox" runat="server" Text="0"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Generate" OnClick="GenerateButton_Click" />
    <asp:Button ID="Button2" runat="server" Text="Calculate" OnClick="CalculateButton_Click" />
    <asp:Label ID="ResultLabel" runat="server" Text="Result"></asp:Label>
    <asp:Panel ID="Panel1" runat="server">
    </asp:Panel>
    </form>
</body>
</html>

In this example, you can enter value in the textbox so it will dynamically generate that number of textboxes when the Generate button clicks. And when the Calculate button clicks, it will sum up all the values entered in the dynamically created textboxes and display the result in Result Label. Following is the C# code behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

        }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Generate initial textboxes
                GenerateButton_Click(sender, e);
            }
        }

        protected void GenerateButton_Click(object sender, EventArgs e)
        {
            //Generate textboxes
            int z = int.Parse(HowManyToGenerateTextBox.Text);

            Panel1.Controls.Clear();

            for (int i = 0; i < z; i++)
            {
                TextBox s = new TextBox();
                s.Text = i.ToString();
                s.ID = "tb" + i.ToString();
                Session[s.ID] = s;
                Panel1.Controls.Add(s);
            }
        }

        protected void CalculateButton_Click(object sender, EventArgs e)
        {
            //Calculate sum
            int sum = 0;

            for (int i = 0; i < Session.Count; i++)
            {
                string textboxID = "tb"+i.ToString();
                TextBox checkIfTextBox = (TextBox)Session[textboxID];

                if (checkIfTextBox != null)
                    sum += int.Parse(checkIfTextBox.Text);
            }

            ResultLabel.Text = sum.ToString();
        }

    }
}

At the page load method, I’m calling to the Generate button click event to initialize the textboxes. In this case, since I’ve hardcoded value 0 to the HowManyToGenerateTextBox, it will not create any textboxes dynamically when the page loads. After that, you can enter any value to the textbox and click Generate button so it will create that number of textboxes. Now you can enter numbers to the dynamically created textboxes and click on the Calculate button. Now a post back happens. But I have stored the dynamically created textboxes in session so I can get them back from the session. I’m getting them back from session, sum it up and display the result in the Result label.

2012-07-27

Set a placeholder image when the image is not available

When you are using img tags, sometimes you need to set a default image for the img tag if the source image is not found or corrupted. There is an event for the img tag called onerror. By using that event, we can easily set a default placeholder image for the img tag, if the image failed to load. Following is an example for the onerror method.

<script>
    function test(e)
    {
       e.src="images/placeholder.jpg";
    }
<script>

<img onerror="test(this);" src="......." />

Now the test() method will get called whenever there is a problem loading the image to the src and will set the placeholder.jpg as the image src.

How to create a simple countdown using javascripts

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClientDisplayForserver.aspx.cs" Inherits="ClientDisplayForserver" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script>
       function GetCount(amount) {
           document.getElementById('test').innerHTML = amount;
           if (amount == 0)
               clearTimeout();
           else
               setTimeout(function () { GetCount(amount - 1) }, 1000);
       }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <span id="test">Test<br />
        <br />
    </span>&nbsp;<asp:Button ID="Button1" runat="server" OnClientClick="GetCount(30); return false" Text="Button" /></div>
    </form>
</body>
</html>

The above sample code is for a countdown when the user press the button. Here it will go from 30. You can change the parameter pass to the GetCount() method,

2012-07-26

Auto-scroll to the bottom of a multiline textbox when page loads

Using the below javascript code snippet, you can auto scroll to the bottom of an asp:TextBox, which’s TextMode property is set to Multiline.

Let’s say the textbox is like below

<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"></asp:TextBox>

Then the javascript code should look like below

window.onload=function myScroll() {
   var x = document.getElementById("<%=textboxid.ClientID%>");
   var h = x.clientHeight;
   x.scrollTop = h;
}

Now, when the page loads, the scroll of the Multiline textbox would go to the bottom.

2012-07-25

How to get the current position when paused, in the embedded windows media player

The below sample code will alert the user, time elapsed, when the user press the pause button. Since it’s Windows Media player, it will only work in IE. To get it work in other browsers, you may need to install plugins/add-ons.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
    <title></title>
</head>
<body>
    <form id="Form1">
    <object id="Player" height="0" width="0" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
    </object>
    <input type="button" name="BtnPlay" value="Play" onclick="StartMeUp()" />
    <input type="button" name="BtnStop" value="Stop" onclick="ShutMeDown()" />
    <input type="button" name="BtnPause" value="Pause" onclick="Pause()" />
    <script type="text/javascript">
<!--

        function StartMeUp() {
            document.getElementById('Player').URL = "Danza kuduro.mp3";
        }

        function ShutMeDown() {
            document.getElementById('Player').Controls.stop();
        }

        function Pause() {
            document.getElementById('Player').Controls.Pause();
            alert(document.getElementById('Player').Controls.currentPosition);
        }

-->
    </script>
    </form>
</body>
</html>

Process an image pixel by pixel to check color on each pixel in C#

By using the below kind of code, we can read an image pixel by pixel and get the color on each.

Bitmap img = new Bitmap("image name here"); 
Color c;

for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
c = img.GetPixel(i, j);
if (c == Color.Black)
{
//Code here
}
else
{
//Code here
}
}
}


On that sample code, I’m checking the pixel color against Black color.

2012-07-23

Specify the Maximum length for JSON response

By adding the following part to the web.config file, you can specify the maximum length for a JSON response

<configuration>
    <system.web.extensions>
        <scripting>
            <webServices>
               <jsonSerialization maxJsonLength="1000" />
            </webServices>
        </scripting>
    </system.web.extensions>
</configuration>

Addition of two short type numbers causing a negative result

I will try to explain this using a simple example. Following code adds two short type numbers and assign the result to another short type variable.

short num1 = 30000, num2 = 30000;
short answer = (short)num1+num2;

But if you see the result, you will get a negative number.

The value range of short data type is -32,768 to 32,767. So the first line is correct because we are storing 30000 (which is less than 32,767) in the variables.

But in the second line, we are adding those two variables which results in 60000 which is bigger than the maximum value which can be stored for a short variable.

Binary representation of the 60000 is 1110101001100000

Binary representation of the 32,767 is 0111111111111111

The first bit is the sign bit. 0 represent positive number and 1 represent negative number. That's why the Binary representation value of the 32,767 is 0111111111111111 (Notice the leading 0). short data type can store only 15 bits (Except the sign bit). As I said, the first bit is used to indicate the sign (negative or positive) of the number. But the binary value of 60000 (1110101001100000) requires 16 bits. So when we store the 60000 in a short variable the leading 1 will assigned to the sign bit and as a result of it, we are getting a negative number. The leading sign bit has the value of 2^15. When it's positive, it's 0 (Because the value of the bit is 0). But when it's negative, it has the value of -2^15 (-32768).

So let's go back to the result 60000. When we assign the value to a short variable, the binary representation of it 1110101001100000 will assign the leading 1 to the sign bit. So now it has value of -32768. Except the sign bit, the left over is 110101001100000 (Notice that I've left out the leading 1) which's value is 27232. So altogether, when we take that value with the sign bit, the final value is  -32768+27232 =-5536.

How to display a popup window in full screen mode

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">
        function openPopup() {
            window.open("yourpagename.html", null, "fullscreen=yes, channelmode=no, scrollbars=yes, resizable=no, status=no, toolbar=no, directories=no")
        }
    </script>
</head>
<body>
    <form>
    <input type="button" name="btnFullscreen" value="Open in fullscreen" onclick="openPopup();" />
    </form>
</body>
</html>

When you press the button, the popup will open in full screen. Note that this can be vary depend on the browser settings and this is not a good user experience too.

2012-07-09

How to vertically center align a text within a dynamically created asp:Label

The following code example shows how to center a text within a asp:Label using a bit of mathematics and help of CSS styles. For the horizontal align, we can simply set the CSS style, text-align to center. For vertically center align the text, we have to use some calculations and position the text accordingly.

Label lblproof = new Label();

lblproof.ID = "label2";

int width = 60;

int height = 30;

int fontSize = 12;

lblproof.Width = width;

lblproof.Height = height-(((height - fontSize) / 2)/2);

lblproof.Text = "Pueba2";

lblproof.Style["position"] = "absolute";

lblproof.Style["font-size"] = "12px";

lblproof.Style["border-bottom"] = "2px";

lblproof.Style["border-left"] = "2px";

lblproof.Style["border-top"] = "2px";

lblproof.Style["border-right"] = "2px";

lblproof.Style["border-style"] = "solid";

lblproof.Style["text-align"]= "center";

lblproof.Style["padding-top"] = (((height - fontSize) / 2) / 2).ToString()+"px";

lblproof.Style["margin-left"] = "auto";

lblproof.Style["margin-right"] = "auto";

this.Controls.Add(lblproof);

You can change the variable values for height, width and fontSize. The mathematical calculation will take the respective values and center the text inside the label both vertically and horizontally.

2012-07-05

The difference between float and display:inline-block

When you use float, the elements will follow you (i.e. if you float:left an element, the elements after it will follow you to the right. If you float:right an element, the elements after it will follow you to the left.). As the name suggests, the element will float in your web page as much as it can (either to left or to right, as you define). If you use float property, it can overlap with other elements on your webpage. But when you set the display:inline-block, it would not make an element overlap with others.

Since the floating elements float either to left or right, it's bit hard to deal with aligning a floated element to the center.

2012-07-04

Simple example for parseJSON function

Following is a simple sample app which parse a JSON string to a jQuery object and access a value in the JSON string.

<html>
<head>
    <title></title>
    <script src="
http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var str = "[{\"CityName\":\"Colombo\",\"CityID\":1,\"ZipCodeID\":1,\"ZipCode\":1098},
                       {\"CityName\":\"Kandy\",\"CityID\":2,\"ZipCodeID\":2,\"ZipCode\":1675}]";
        var test = jQuery.parseJSON(str);
        for (var i = 0; i < test.length; i++)
            alert(test[i].CityName); //Here, this will alert the City name in the JSON string
    </script>
</head>
<body>
</body>
</html>

2012-07-02

SQL injections

I'll try to explain it with a simple example.

Let's take a table named 'Users' which has two columns, 'Username' and 'Password'. In the 'Username' field, they store the username and in the 'Password' field they store passwords. For the simplicity, let's assume they are storing the password in plain text (Facebook surely don't store their password in plain text). Now let's look what it looks like the SQL query for a legal user. They will provide the username along with the correct password. So their query will looks like below.

SELECT * FROM Users WHERE Username = 'Ruchira' AND Password = '123'

Here I'm login to that site using my username 'Ruchira' and my password '123' which is the correct one. So now, the select query will return a one row. Now the system know I'm a legal user because it returns a record which matches both my password and username.

Now, let's see how SQL query for a hacker looks like. Hacker knows my Username but don't know my password. So he is TRYING to make a query like below.

SELECT * FROM Users WHERE Username = 'Ruchira' AND Password = 'none' OR 'x'='x'

Now the question is how can a hacker makes such a query.

He can pass the username as I do but problems occurs when he provide the password because he don't know it. Now what he is doing is he provides something which makes the second condition (i.e. Password='none'…. part) always evaluates to true no matter what he provides for the password. In the backend, the website have something likes this

SELECT * FROM Users WHERE Username = '+txtUserName.Text+' AND Password = '+txtPassword.Text+'

Where they are getting the username from txtUserName TextBox and password from txtPassword TextBox. So now, the hacker provides the following value for the txtPassword field

none' OR 'x'='x

So the final query he is sending looks like below

SELECT * FROM Users WHERE Username = '+txtUserName.Text+' AND Password = 'none' OR 'x'='x'

So what basically SQL injection preventions do is, they prevent/ignore users from inserting words such as OR in to the password fields or prevent users inserting special characters such as " ' or distinguish data from the SQL query so the data will not be used to build the query.