Event Handlers for Dynamically added ASP.NET controls
August 28, 2006 6:18 AM   Subscribe

How to write and execute event handlers between dynamically added asp.net controls

I have code which loops through an IDataReader adding a tablecell to a table and a checkbox to the tablecell for each record. I need to have the containing tablecell change color when the checkboxe is checked and unchecked and I cant figure out how. Preferrable this would be achieved without a roundtrip to the server.

while (data.Read())
{
.......

for (cellCtr = 1; cellCtr <= cellCnt; cellCtr++)
{
TableCell tCell = new TableCell();
tCell.RowSpan = 1;
tRow.Cells.Add(tCell);

CheckBox cb = new CheckBox ();
cb.Checked = false;
cb.Text = Field1.ToString();
cb.ID = Field1.ToString();
cb.ToolTip = Field2.ToString();


tCell.Controls.Add (cb);
}
}
posted by kenaman to Computers & Internet (2 answers total)
 
How about adding a JavaScript (or VB if you want) client-side event handler to each cell? (I'm not sure if this is the way things are normally done in ASP.NET, but it'll still work).

I don't have an ASP.Net system to hand to test this, but something like this should work:

// Server-side:
cb.SetAttribute("onclick","changeColor(this.parent)")

// Then put this in the <head> of your page:
<script type="text/javascript">
function changeColor(cell)
{
oldBgColour = '#000000'; // default colour
newBgColour = '#FFFFFF'; // highlight colour
if (cell.style.backgroundColor == oldBgColour)
{
cell.style.backgroundColor = newBgColour;
}
else
{
cell.style.backgroundColor = oldBgColour;
}
</script>


This assumes the parent of the checkbox is the cell.
posted by matthewr at 7:24 AM on August 28, 2006


Thanks a million for that matthewr. It worked. I am just giving the JavaScript a tweak and the cb.SetAttribute is cb.Attributes.Add ("onclick","clicked(this.parent)");

But basically it is adding and calling the JavaScript function which is exactly what I wanted. I will post the 'tweaked' JS when I get a chance. Have tried to mark as best answer but not working at the moment. Will try later also.

Thanks Ken
posted by kenaman at 8:24 AM on August 28, 2006


« Older Simple data transfer question   |   Japanese PHP/Mysql development tips? Newer »
This thread is closed to new comments.