DataGridView为何生成额外的Barcode列?
解决DataGridView生成额外Barcode列的问题
问题原因
你的代码出现多余列的核心问题有两点:
- 绑定
DataTable时,DataGridView会自动为查询返回的每个字段生成对应列——你的SQL查询包含Barcode和BarcodeImage,所以控件会自动创建这两个列(其中BarcodeImage默认以字节数组形式显示,不是图片)。 - 你又手动创建并添加了一个新的
DataGridViewImageColumn,导致条码相关列重复;同时后续赋值操作错误指向自动生成的BarcodeImage列,手动添加的列并未被使用。
解决方案
方案1:改造自动生成的列(简单高效)
不需要手动新增列,直接修改自动生成的BarcodeImage列为图片格式,同时如果不需要Barcode文本列,直接从SQL查询中移除该字段:
private void LoadInventoryData() { // 移除不需要的Barcode字段,避免生成多余列 string query = "SELECT ItemName, Description, Quantity, BarcodeImage FROM InventoryItems"; dataAdapter = new SQLiteDataAdapter(query, connection); dataTable = new DataTable(); dataAdapter.Fill(dataTable); dataGridViewInventory.DataSource = dataTable; // 将自动生成的BarcodeImage列转为图片列 if (dataGridViewInventory.Columns["BarcodeImage"] != null) { dataGridViewInventory.Columns["BarcodeImage"].HeaderText = "Barcode Image"; ((DataGridViewImageColumn)dataGridViewInventory.Columns["BarcodeImage"]).ImageLayout = DataGridViewImageCellLayout.Stretch; } }
方案2:完全自定义列(精准控制)
关闭DataGridView的自动列生成功能,手动添加所有需要的列并绑定到DataTable字段:
private void ViewInventoryForm_Load(object sender, EventArgs e) { InitializeComponent(); // 关闭自动列生成,避免控件自动创建列 dataGridViewInventory.AutoGenerateColumns = false; string connectionString = "Data Source=C:\\Users\\denin\\Desktop\\PCEVINV\\Database_pcevinv\\pcevinv.db;Version=3;"; connection = new SQLiteConnection(connectionString); connection.Open(); LoadInventoryData(); } private void LoadInventoryData() { string query = "SELECT ItemName, Description, Quantity, BarcodeImage FROM InventoryItems"; dataAdapter = new SQLiteDataAdapter(query, connection); dataTable = new DataTable(); dataAdapter.Fill(dataTable); dataGridViewInventory.DataSource = dataTable; // 手动添加文本列 dataGridViewInventory.Columns.Add(new DataGridViewTextBoxColumn { Name = "ItemName", HeaderText = "Item Name", DataPropertyName = "ItemName" }); dataGridViewInventory.Columns.Add(new DataGridViewTextBoxColumn { Name = "Description", HeaderText = "Description", DataPropertyName = "Description" }); dataGridViewInventory.Columns.Add(new DataGridViewTextBoxColumn { Name = "Quantity", HeaderText = "Quantity", DataPropertyName = "Quantity" }); // 手动添加图片列并绑定到BarcodeImage字段 DataGridViewImageColumn imageColumn = new DataGridViewImageColumn(); imageColumn.Name = "BarcodeImage"; imageColumn.HeaderText = "Barcode Image"; imageColumn.DataPropertyName = "BarcodeImage"; imageColumn.ImageLayout = DataGridViewImageCellLayout.Stretch; dataGridViewInventory.Columns.Add(imageColumn); }
额外提示
- 如果之前在设计器中给
DataGridView添加过列,记得删除这些设计器中的列,防止和代码生成的列重复。 - 设置
ImageLayout = DataGridViewImageCellLayout.Stretch可以让条码图片自适应单元格大小,提升显示效果。
内容的提问来源于stack exchange,提问作者PotatoCast
相关产品推荐
相关产品推荐

