Sunday 30 December 2007

Clickable row in ASP .NET Table

Easy three steps to create click able row in ASP .NET table. This is accomplished using JavaScript.

Step one: Create an ASP Table
Adding a table in an .aspx file is easy. Just drag and drop the table icon from toolbox. Add header row. Or simply copy paste following code.

< asp:table id="employeeTable" runat="server" cellpadding="0" cellspacing="0">
< asp:tableheaderrow>
< asp:tableheadercell>First Name < /asp:tableheadercell>
< asp:tableheadercell>Last Name < /asp:tableheadercell>

< /asp:tableheaderrow>
< /asp:table>

Step two: Write a JavaScript function to invoke from onClick event of table row.
< script type="text/javascript">
function SayHello( )
{
alert( "Hello there." );
}
< / script>


Step three: put them together
Now you just one inch away to get your result. What you need to do is to add appropriate attribute the table row.
Lets add a row in the table and associate the click event handler with the row. We are going to do that in page load event handler.

protected void Page_Load(object sender, EventArgs e)
{
TableCell name = CreateCell( "John" );
TableCell lastName = CreateCell( "Smith" );

TableRow row = CreateRow( new TableRow[]{ name, lastName});

this.employeeTable.Rows.Add( row );

//this is the glue between your JavaScript and TableRow

row.Attributes.Add("onClick", "javascript:SayHello();");


}


public static TableRow CreateRow( TableCell []cells)
{
TableRow row = new TableRow();
foreach (TableCell cell in cells)
row.Cells.Add(cell);
return row;
}

public static TableCell CreateCell(String text)
{
Label label = new Label();
label.Text = text;

TableCell cell = new TableCell();

cell.Controls.Add( label);

return cell;
}



Now simply run your program. Click on the row. It should display a alert box.

Part II

No comments:

Post a Comment