Link to home
Start Free TrialLog in
Avatar of Charles Baldo
Charles BaldoFlag for United States of America

asked on

Need to use Windows Forms datagridview as a variable in control

Using Windows Forms

I have a tabcontrol , each page has a datagridview.  I know the  tab page name

tabData.SelectedTab.Name

let's say I have tabPage1  the datagridview on that tab is dgvPage1.   Now I want to get the selected row

int row = dgvPage1.CurrentCell.RowIndex;  


How can I do this if all I know about is the grid I want is   -- String  VariableName  =  "dgvPage1"  stored in a variable.

int row = (VariableName).CurrentCell.RowIndex;  
String Person = (VariableName).Rows[row].Cells[0].Value.ToString();
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

I'm not sure I fully understand your question, since you seem to have the expected code in your question:

int row = dgvPage1.CurrentCell.RowIndex;  
String Person = dgvPage1.Rows[row].Cells[0].Value.ToString();

Maybe you're asking WHEN you should call this code, but the answer to that is up to you (do you want to call it when a button is clicked or when some kind of event happens, and if so, what is that event) ?

If you're asking how the above works, the "dgvPage1.CurrentCell" part is a special, automatically-updating property that points to the datagrid cell that is currently selected at the time when the code runs. So if you run your program and click on the second column in the second row of your grid, and then you click a button that runs those 2 lines of code, then dgvPage1.CurrentCell will point to that cell you clicked on.

From there, the RowIndex tells you which row the cell is on.

Then,  dgvPage1.Rows[row] points to that specific row, and  dgvPage1.Rows[row].Cells[0] points to the 1st column in that row.

Then  dgvPage1.Rows[row].Cells[0].Value points to the contents that are inside that cell. The contents aren't necessarily a string (a datagrid cell could have other things, like checkboxes), so  dgvPage1.Rows[row].Cells[0].Value.ToString() tries to force it to a string.

All that said, I'd strongly recommend you learn WPF and models/databinding. Once you learn how to do that stuff, it makes life SO much easier, and WPF datagrids are a lot more flexible and capable than Winforms datagrids.
ASKER CERTIFIED SOLUTION
Avatar of Kelvin McDaniel
Kelvin McDaniel
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Charles Baldo

ASKER

Thanks Kevin,

You understood.  I do not know which tab or grid I have, but in a variable from a selected item list by the user

gr8Gonzo, thanks but WPF is not an option on this project.   I have been given very strict requirements, it must be in Windows  Forms.