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);
}
}
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);
}
}
Response by poster: 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
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
This thread is closed to new comments.
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