Home > Mobile >  Get Highest number in DataGridView Column without clicking a row, to generate ID field on another fo
Get Highest number in DataGridView Column without clicking a row, to generate ID field on another fo

Time:12-21

I am trying get the value of the highest number in a DataGridView column, so that I can populate a text field on a separate form with that value 1, I can't seem to find a working method for .Max, or a solution that matches this specific need.

In my limited experience with Python, I seem to remember being able to get the last value in an array by using [-1] or something similar, does c# have anything like this?

Here is my code to populate the Text field on the 2nd form, with the Column value of the DataGridView on the first:

public AddPart()
    {
        InitializeComponent();

        MainScreen frm1 = new MainScreen();
        AddPartIDBox.Text = frm1.PartDGV.Rows[0].Cells[0].Value.ToString();

enter image description here

enter image description here

Here's what I'm needing it to do, if I have ID 0, 1, I need that text field to populate with 2, so that it saves the new part with the next available number.

Note: The 2 parts (ID 0 and ID 1) are manually coded into Program.cs to add, the part constructor uses an integer IncrementID to set the ID field with PartID = IncremementID ;

CodePudding user response:

Thanks to Ryan Wilson, I was able to get it working. Here is the code snippet:

int dgvIndex = (int)frm1.PartDGV.Rows[frm1.PartDGV.Rows.Count - 1].Cells[0].Value; 
        int dgvIndex2 = dgvIndex   1;
        AddPartIDBox.Text = dgvIndex2.ToString();

CodePudding user response:

In case your DataGridView can be manipulated to re-order the rows, it may be better to find the MAX PartID. You can achieve this in multiple ways, but for sake of doing it with few lines of code, I am going to use Linq:

int maxpartid = frm1.PartDGV.Rows.Cast<DataGridViewRow>()
                  .Max(x => Convert.ToInt32(x.Cells[0].Value));
  • Related