C# 循环遍历 DataGridView 单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13788156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:48:08  来源:igfitidea点击:

Looping through DataGridView Cells

c#visual-studio-2010excelloopsdatagridview

提问by Mr Bagder

I am creating a program that generates a bar code and then prints the shipping labels.

我正在创建一个生成条形码然后打印运输标签的程序。

I have a function that allows the user to upload a spreadsheet into the datagrid view. One of the column names is "Tracking Number".

我有一个功能,允许用户将电子表格上传到数据网格视图中。列名称之一是“跟踪编号”。

I would like to be able to loop through each cell that has a tracking number and then generate a barcode into a a new cell in a column called "barcode".

我希望能够遍历具有跟踪号的每个单元格,然后将条形码生成到名为“条形码”的列中的新单元格中。

I understand there is a loop function for this but I have never used it before.

我知道有一个循环函数,但我以前从未使用过它。

The code that generates the barcode is the following , it calls two classes:

生成条码的代码如下,调用了两个类:

 Image barc = Rendering.MakeBarcodeImage(txtTrack.Text, int.Parse(txtWidth.Text), true);
 pictBarcode.Image = barc;

Any Help would be much appreciated. I will happily answer any other questions.

任何帮助将非常感激。我很乐意回答任何其他问题。

回答by Sid Holland

You can loop through a DataGridViewusing the following:

您可以DataGridView使用以下方法循环遍历 a :

foreach (DataGridViewRow row in dgvNameOfYourGrid.Rows)
{
    if (row["Tracking Number"].ToString != "")
    {
        string trackingNumber = row.Cells["Tracking Number"].ToString();

        // do stuff with the tracking number
    }
}

But to display the barcode in another cell you will need to convert it to a DataGridViewImageCell(or preferable the whole column into a DataGridViewImageColumn).

但是要在另一个单元格中显示条形码,您需要将其转换为 a DataGridViewImageCell(或者最好将整个列转换为 a DataGridViewImageColumn)。

回答by Chris

To iterate through every cell, you can use foreach loops

要遍历每个单元格,您可以使用 foreach 循环

foreach(DataGridViewRow row in yourDataGridView.Rows)
{
    foreach(DataGridViewCell cell in row.Cells)
    {
        //do operations with cell
    }
}