Monday, February 21, 2011

how to setup bindable checkbox value automatically changed to male/female

I'm using detailsview in asp.net. I have gender field. when this field checked, checkbox text automatically changed to 'male', otherwise 'female'. How can i do? How to setup checkbox to this feature?

From stackoverflow
  • While I hope you aren't actually doing this, the following will accomplish it:

    protected void chkSex_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkSex = (CheckBox)sender;
        chkSex.Text = SexString(chkSex.Checked);
    }
    protected string SexString(bool sex)
    {
        return sex ? "Male" : "Female";
    }
    

    And the markup:

    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:CheckBox runat="server" 
                Checked='<%# Eval("Sex") %>'
                OnCheckedChanged="chkSex_CheckedChanged" 
                AutoPostBack="true" 
                Text='<%# SexString((bool)Eval("Sex")) %>'/>
        </ContentTemplate>
    </asp:UpdatePanel>
    
  • You can do this with some simple javascript.

    Mark Up

    <label id="sexLabel" for="sexCheckBox">Male</label>
    <input id="sexCheckBox" type="checkbox" onclick="sexClick(this);" />
    

    Code

    function sexClick(checkbox) {
        document.getElementById('sexLabel').innerHTML = (checkbox.checked) ? 'Female' : 'Male';     
    }
    

    jQuery

    Mark Up

    <label id="sexLabel" for="sexCheckBox">Male</label>
    <input id="sexCheckBox" type="checkbox" />
    

    Code

    $(function() {
        $('#sexCheckBox').click(function() {
            $('#sexLabel').text((checkbox.checked) ? 'Female' : 'Male');
        });
    });
    
    Yuriy Faktorovich : Ha, I went overboard.
  • Suppose the column or property name is Sex and is true if sex is male. Use this in markup:

    <asp:CheckBox runat="server" ID="chkSex" Text='<%# GetText((bool)Eval("Sex"))%>' 
             Checked='<%# Eval("Sex")%>' />
    

    write this method in code-behind:

    protected static object GetText(bool b)
    {
        return b ? "Male" : "Female";
    }
    

0 comments:

Post a Comment