这几天我正在研究QR码。因此,我正在尝试执行QR码。 我的目的是选择Employee表并选择两个列(Id和Name), 加载员工ID时,我想让我的ID成为QR码并放入Gridview图片控件
下面是我的前端程序
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="QRcodeSample.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="QR Code">
<ItemTemplate>
<asp:Image ID="ImgQRcode" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
下面是我的后端代码:
protected void Page_Load(object sender, EventArgs e){
GetEmployeeNumber();
}
public void GetEmployeeNumber(){
SqlConnection cn = new SqlConnection();
cn.ConnectionString =
System.Configuration.ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
cn.Open();
string sql = "SELECT EmployeeID,FirstName FROM Employees";
SqlCommand cmd = new SqlCommand(sql,cn);
SqlDataReader drEmployee = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(drEmployee);
//Load DataTable
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow row = dt.NewRow();
string number = dt.Rows[i]["EmployeeID"].ToString();
GenerateQRCode(number);
}
GridView1.DataSource = drEmployee;
GridView1.DataBind();
}
private void GenerateQRCode(string number)
{
var writer = new BarcodeWriter()
{
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions()
{
Width = 100,
Height = 100,
CharacterSet = "UTF-8"
}
}
};
var result = writer.Write(number);
string path = Server.MapPath("/images/" + number + ".jpg");
var barcodeBitmap = new Bitmap(result);
using(MemoryStream memory = new MemoryStream())
{
using(FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
barcodeBitmap.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
//Here is my problem, what should I do?
//ImgQRcode.Visible = true;
//ImgQRcode.ImageUrl = "~/images/QRImage.jpg";
}