how to check the checkbox inside the repeater at binding time accordingto value?

烂漫一生 提交于 2019-12-11 06:17:49

问题


I have a repeater and inside it i have a checkbox. Now i want to check it according to columns value(0/1). I have tried it through the itemDataBound event of the repeater. what its doing if the rows has value 1 then its checked all checkbox and if first checkbox is unchecked then its unchecked all. my code is:- `

                    <td align="center">
                        <asp:CheckBox ID="chk" runat="server" />
                    </td>
                </tr>
            </ItemTemplate>
        </asp:Repeater>`

The ItemDataBound events code is :-

 protected void rp_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    DataTable dt = new DataTable();
    dt = obj.abc(id);
    if (dt.Rows.Count > 0)
    {
        CheckBox chk = (CheckBox)(e.Item.FindControl("chk"));
        if (chk != null)
        {

            if (Convert.ToInt32(dt.Rows[0]["xyz"]) == Convert.ToInt32("0"))
            {
                chk.Checked = false;
            }
            else
            {
                chk.Checked = true;

            }
        }

    }

}

回答1:


There are many ways to do that.

  1. You can write inline ASP.NET:

    <asp:CheckBox id='isMarried' runat='server' 
    Checked='<%# Convert.ToBool(Eval("IsMarried")) ? true : false %>' />
    
  2. As you have mentioned, you can use repeater_ItemDataBound to find the check-box of each row, and set its value accordingly:

    protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        Person person = (Person)e.Item; // e.Item is the datasoruce of the row
        if (person.IsMarried) 
        {
            CheckBox isMarried = (CheckBox)(e.Item.FindControl("isMarried"));
            isMarried.Checked = true;
        }
    }
    
  3. Another way could be to inject the Boolean state (here, the marriage state) in a hidden field and send it to the client, then on client-side, using jQuery (or any other JavaScript framework), update check-boxes' checked state according to the value of those hidden fields:



来源:https://stackoverflow.com/questions/8442046/how-to-check-the-checkbox-inside-the-repeater-at-binding-time-accordingto-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!