Reading data from DataGridView in C#

后端 未结 5 1260
礼貌的吻别
礼貌的吻别 2020-12-01 14:40

How can I read data from DataGridView in C#? I want to read the data appear in Table. How do I navigate through lines?

相关标签:
5条回答
  • 2020-12-01 14:48

    Code Example : Reading data from DataGridView and storing it in an array

    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());
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 14:49
    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++;
    }
    

    Hope this helps....

    0 讨论(0)
  • 2020-12-01 14:51

    something like

    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();
    
        }
    } 
    

    example without using index

    foreach (DataGridViewRow row in dataGrid.Rows)
    { 
        foreach (DataGridViewCell cell in row.Cells)
        {
            string value = cell.Value.ToString();
    
        }
    }
    
    0 讨论(0)
  • 2020-12-01 14:58
     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;
             }
         }
     }
    
    0 讨论(0)
  • 2020-12-01 15:08

    If you wish, you can also use the column names instead of column numbers.

    For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.

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

    Hope it helps.

    0 讨论(0)
提交回复
热议问题