Search code examples
c#asp.netbarcode

Barcode ASP.NET C# Issue


I have this code for generating barcode when page is loaded.(code below) txtBarcodeBlack.Text content is pulled from SQL Server Database as varchar. I have a button submit that will do another process like saving the txtBarcodeBlack.text to database. My problem is when I press the button, it gives me this Problem please help. I'm stuck for 2 days.

 private void loadBlackBarcode() {
    //barcode black
    //txtBarcodeBlack.Text = vBarcodeBlack;
    string barCodeBlack = txtBarcodeBlack.Text;
    System.Web.UI.WebControls.Image imgBarCodeBlack = new System.Web.UI.WebControls.Image();
    using (Bitmap bitMap = new Bitmap(barCodeBlack.Length * 40, 80))
    {
        using (Graphics graphics = Graphics.FromImage(bitMap))
        {
            Font oFont = new Font("IDAutomationHC39M", 16);
            PointF point = new PointF(2f, 2f);
            SolidBrush blackBrush = new SolidBrush(Color.Black);
            SolidBrush whiteBrush = new SolidBrush(Color.White);
            graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
            graphics.DrawString("*" + barCodeBlack + "*", oFont, blackBrush, point);
        }
        using (MemoryStream ms = new MemoryStream(100000))
        {
            bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            byte[] byteImage = ms.ToArray();

            Convert.ToBase64String(byteImage);
            imgBarCodeBlack.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
        }
        PlaceHolder1.Controls.Add(imgBarCodeBlack);
    }

}


<div class="col-xs-12 col-sm-12 col-lg-12" style="margin-bottom:20px;">
      <h3>Digital Black</h3>

      <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>

Solution

  • UPDATE Okay I tried searching for other solution, and I found the answer.

    I changed this line:

    using (Bitmap bitMap = new Bitmap(barCodeBlack.Length * 40, 80))
    

    to this line:

    using (Bitmap bitMap = new Bitmap(800, 80))
    

    for some reason the new Bitmap does not accept variable inside the parameter, so I guess I need to hard code my measurement of the barcode.