Friday, May 29, 2009

Using onclick with ListItem within RadioButtonList Control

Below is a way to add an onclick event into the ListItems of a RadioButtonList Control:


Static RadioButtonList and ListItems within HTML
<asp:RadioButtonList id="citizenRbl" runat="server" RepeatDirection="Horizontal">
<asp:ListItem value="uscitizen" text="US Citizen"></asp:ListItem>
<asp:ListItem value="residentalien" text="Resident Alien"></asp:ListItem>
<asp:ListItem value="nonresidentalien" text="Non-Resident Alien"></asp:ListItem>
</asp:RadioButtonList>

Code Behind - add the onclick event to the parent control of the ListItems
citizenRbl.Attributes.Add("onclick", "CheckCitizenSelection('"+citizenRbl.ClientID+"')");

Javascript
<script language="Javascript">
function CheckCitizenSelection(rblID){
var rbl = document.getElementById(rblID);
var options = rbl.getElementsByTagName('input');
for(jj=0; jj<options.length; jj++)
{
  var cbox = options[jj];
  if(cbox.checked && cbox.value == "nonresidentalien"){
    alert('You choice was non-resident alien');
  }
}
}
</script>

Friday, May 8, 2009

Add client on click to asp repeater

To add a client side onclick event to buttons in a repeater, use the scenario below as a reference.


Within the web form:
<asp:Repeater ID="ItemsRpt" Runat="server">
  <ItemTemplate>
    <tr>
      <td><%#DataBinder.Eval(Container.DataItem, "ItemName")%></td>
      <td>
        <asp:Button ID="DeleteBtn" Runat="server" Visible=<%#System.Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "canDelete"))%> Text="Delete" CommandArgument=<%#DataBinder.Eval(Container.DataItem, "ItemId")%> CommandName="DeleteItem" CssClass="Btn" CausesValidation="False"></asp:Button>
      </td>
    </tr>
  </ItemTemplate>
</asp:Repeater>

Within the code behind "InitializeComponent"
this.ItemsRpt.ItemCreated += new RepeaterItemEventHandler(ItemsRpt_ItemCreated);

and then...
private void PositionsRpt_ItemCreated(object sender, RepeaterItemEventArgs e)
{
  if (e.Item.DataItem != null)
  {
    Button btn = e.Item.FindControl("DeleteBtn") as Button;
    if (btn != null) {
      btn.Attributes.Add("onclick", "return confirm('Confirm the deletion of this item');");
    }
  }
}