Search code examples
javascriptc#jqueryasp.netrepeater

Generate Barcode in every Repeater ItemTemplate


I plan to generate barcode with jquery barcode library in an asp repeater.

The repeater work well, all data retreived is diplayed.

The problem is wuth the barcode generation.

Please help on this.

<script src="Scripts/jquery-3.1.1.min.js"></script>
<script src="Scripts/jquery-barcode.js"></script>
<script type="text/javascript">
    function GetBarcode(_refEnvoi) {
        $("#bcTarget").barcode(_refEnvoi, "code128", { barWidth: 2, 
     barHeight: 50, output: 'css' });
    };

</script>

<form id="form1" runat="server">
<asp:Repeater runat="server" ID="repAllEnvois" ClientIDMode="Static" 
 OnItemDataBound="repAllEnvois_ItemDataBound">
        <ItemTemplate>
 <asp:Label ID="txtrefEnvoi" runat="server" Text='<%# Eval("refEnvoi") %>' 
 />
<div id="bcTarget" runat="server" class="pull-right" style="height: 70px"> 
</div>
</ItemTemplate>
        <SeparatorTemplate>
            <h2 style="page-break-before: always;"></h2>
            <br />
        </SeparatorTemplate>

    </asp:Repeater>

 </form>

Code Behind

    protected void repAllEnvois_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            RepeaterItem item = e.Item;

            string refBarcode = (item.FindControl("txtrefEnvoi") as Label).Text;

            ClientScript.RegisterClientScriptBlock( this.GetType(), "GetBarcode", "GetBarcode(+'refBarcode'+)", true);l;
        }
    }

Solution

  • Try this

    <img class="barcode" data-id='<%# Eval("refEnvoi") %>' />
    

    inside repeater where you want barcode to appear

    then at botton use this script to generate barcodes

    <script>
    $(function(){
        var $barcode = $(".barcode");
        $barcode.each(function () {
            var bc = $(this).data('id').toString();
            $(this).JsBarcode(bc, { "format": "code128", "backgroundColor": "#fff", "fontSize": 16, "height": 40, "width": 1, "displayValue": true }, function (valid) {
    
            });
        });
    });
    </script>
    

    requires JSBarcode library