This blog will demonstrate how to generate QR code using ASP.NET.
Step 1
Create an empty web project in the Visual Studio version of your choice.
Step 2
Add Web Form, right-click on the project, select Add New Item, choose web form, give it a name and click on Add.
Step 3
Add script and styles in web form head section.
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
Step 4
Design web form by dragging and dropping textbox control, button control, and placeholder control. Apply bootstrap 4 class to textbox and button.
- <!DOCTYPE html>
- <html>
- <head runat="server">
- <title>QR Generate</title>
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div class="container">
- <h2>How to Generate QR Code in ASP.NET</h2>
- <div class="row">
- <div class="col-md-4">
- <div class="form-group">
- <label>Enter Something</label>
- <div class="input-group">
- <asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
- <div class="input-group-prepend">
- <asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
- </div>
- </div>
- </div>
- </div>
- </div>
- <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
- </div>
- </form>
- </body>
- </html>
Step 5
Double-click on the Generate button control and write the following C# code.
- using System;
- using System.Drawing;
- using System.IO;
- using QRCoder;
- namespace QRCode_Demo
- {
- public partial class QRCode : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void btnGenerate_Click(object sender, EventArgs e)
- {
- string code =txtQRCode.Text;
- QRCodeGenerator qrGenerator = new QRCodeGenerator();
- QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
- System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
- imgBarCode.Height = 150;
- imgBarCode.Width = 150;
- using (Bitmap bitMap = qrCode.GetGraphic(20))
- {
- using (MemoryStream ms = new MemoryStream())
- {
- bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
- byte[] byteImage = ms.ToArray();
- imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
- }
- PlaceHolder1.Controls.Add(imgBarCode);
- }
- }
- }
- }
Step 6
Run the project by pressing Ctrl + F5.
Final output