简体   繁体   中英

using Databinder.Eval in onclick of checkbox in datagrid

<asp:DataGrid ID="dg" runat="server">
    <Columns>
        <asp:TemplateColumn>
            <ItemTemplate>
                <asp:CheckBox ID="cb" runat="server" onclick='myCheckChanged("<%#DataBinder.Eval(Container, "DataItem.myid")%>")' />
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>

This runs but when I click the checkbox in the browser I get a js error. I tried all the combinations of single and double quotes and escaping but i either get a js error or a .net "The server tag is not well formed" error. how can I do this?

If you run your code it will show you undefined or nothing so there are some ways to do this approach, the firs one and easiest you should change you cb as following:

<asp:CheckBox ID="cb" runat="server" onclick='<%# string.Format("myCheckChanged(\"{0}\")", Eval("myid")) %>' />

and the second way you can do it in code-behind on ItemDataBound like this:

1- change your `DataGrid' as:

<asp:DataGrid ID="dg" runat="server" OnItemDataBound="dg_ItemDataBound">
        <Columns>
            <asp:TemplateColumn>
                <ItemTemplate>
                    <asp:CheckBox ID="cb" runat="server" />
                </ItemTemplate>
            </asp:TemplateColumn>
        </Columns>
    </asp:DataGrid>

2- in code-behind implement dg_ItemDataBound like :

 protected void dg_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            CheckBox ch = (CheckBox)e.Item.FindControl("cb");
            ch.Attributes.Add("OnClick", string.Format("myCheckChanged({0});", e.Item.Cells[1].Text));
        }
    }

note: in this snippet e.Item.Cells[1].Text you must know myid is in which Cells

these two ways are working properly.

找出一种方法,这是我所做的:

<asp:CheckBox ID="cb" runat="server" onclick=<%# "myCheckChanged('" + DataBinder.Eval(Container, "myid") + "') "%> />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM