正在从C#中的DataGridView读取数据

本文关键字:DataGridView 读取 数据 中的 | 更新日期: 2023-09-27 18:00:38

如何在C#中从DataGridView读取数据?我想读取表中显示的数据。如何在行中导航?

正在从C#中的DataGridView读取数据

类似的东西

for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
     for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
    {
        string value = dataGrid.Rows[rows].Cells[col].Value.ToString();
    }
} 

不使用索引的示例

foreach (DataGridViewRow row in dataGrid.Rows)
{ 
    foreach (DataGridViewCell cell in row.Cells)
    {
        string value = cell.Value.ToString();
    }
}

如果您愿意,也可以使用列名而不是列号。

例如,如果您想从4上的DataGridView读取数据。行和"名称"列。它让我更好地理解我正在处理的变量。

dataGridView.Rows[4].Cells["Name"].Value.ToString();

希望能有所帮助。

string[,] myGridData = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach(DataRow row in dataGridView1.Rows)
{
    myGridData[i][0] = row.Cells[0].Value.ToString();
    myGridData[i][1] = row.Cells[1].Value.ToString();
    myGridData[i][2] = row.Cells[2].Value.ToString();
    i++;
}

希望这能有所帮助。。。。

代码示例:从DataGridView读取数据并将其存储在数组中

int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
    for (int j = 0; j < StartDataView.Columns.Count; j++)
    {
        if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
        {
            try
            {
                n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
            }
            catch (Exception Ee)
            { //get exception of "null"
                MessageBox.Show(Ee.ToString());
            }
        }
    }
}
 private void HighLightGridRows()
 {            
     Debugger.Launch();
     for (int i = 0; i < dtgvAppSettings.Rows.Count; i++)
     {
         String key = dtgvAppSettings.Rows[i].Cells["Key"].Value.ToString();
         if (key.ToLower().Contains("applicationpath") == true)
         {
             dtgvAppSettings.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
         }
     }
 }