Getting a primary key from a datagrid. C#

Posted on 2004-08-26
Last Modified: 2010-04-17
Right now I have a program where a user needs to highlight a row and click a button.   The function of that button depends on the row selection.   Is there a way to sync the CurrentRowIndex with a cell in that row like the primary key cell for example, or is there a completely different way to do this?  I'm open to suggestions!
Question by:sean-keys
  • 4
  • 2

Expert Comment

ID: 11910517
CurrentRowIndex tells you a position in your dataset, which is connected with grid.
m_Grid.DataSource - which is typically DataSet or DataTable - .DataSet.Tables(0).Rows(m_Grid.DataSource.CurrentRowIndex)
where m_Grid is your grid.

Expert Comment

ID: 11910665
supose you know the position of the primary key column

int rowIndex = dataGrid1.CurrentRowIndex;
dataGrid1[rowIndex][PKcolumn]  will return the value of the desired column, from the current row;

Author Comment

ID: 11960282

      It sounds like you hit the nail on the head, is there anyway you can give a brief example with a little more detail.  Please forgive my ignorance, sorry for the delay.

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.


Accepted Solution

IceColdas earned 125 total points
ID: 11961146
ok, lets say you have this command string : commandString = "SELECT primaryKey, column2, column3, column4 FROM table1"
In this case, the primary Key column will be on the first position (means position 0).
else, if commandString = "SELECT column1, column2, primaryKey,  column4 FROM table1" (in this case, PKcolumn = 2)
Therefor, the program will be :

int PKcolumn = 0; //first position is 0, second position = 1, and so on
int rowIndex = dataGrid1.CurrentRowIndex;
//now, depending on the type of primaryKey field, either
int primaryKeyValue = (int)dataGrid1[rowIndex][PKcolumn];
string primaryKeyValue = dataGrid1[rowIndex][PKcolumn].ToString();

Expert Comment

ID: 11961370
second, you can find any column position from the datagrid tablestyles, if you know the name of that column;
this way, if the column position change in the database, then your program will still work
i.e. :
private int GetColumnPosition(string myColumnName)
//myColumnName the name of the column you want to get the position
int columnPosition = -1;
int i=0;
/* either use TableStyles[0] if you have only one table in the dataset, or TableStyles[tableName] to specify the table name */
foreach (System.Windows.Forms.DataGridColumnStyle cs in dataGrid1.TableStyles[0].GridColumnStyles)
      /*for case insensitive comparision:
                                                 if  (cs.MappingName.ToUpper() == myColumnName.ToUpper() ) */
                if (cs.MappingName == myColumnName)
                 { columnPosition = i; break; }
return columnPosition;

Author Comment

ID: 11986602
I get the following errors when I build the code.   Maybe someone can shed some light on what I over looked.  Thanks

private void test_Click(object sender, System.EventArgs e)
                  int PKcolumn= 0;
                  int rowIndex = grdcustomers.CurrentRowIndex;
                  int primaryKeyValue= (int) grdcustomers[rowIndex][PKcolumn];
                  testval.Text =primaryKeyValue.ToString() ;

(1606): The best overloaded method match for 'System.Windows.Forms.DataGrid.this[System.Windows.Forms.DataGridCell]' has some invalid arguments
(1606): Argument '1': cannot convert from 'int' to 'System.Windows.Forms.DataGridCell'


Expert Comment

ID: 11988085
sorry, my mistake
it is
 int primaryKeyValue= (int) grdcustomers[rowIndex, PKcolumn];

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Sql how to exclude from a table 3 73
scoreUp challenge 14 48
factorial example challenge 10 62
word0 challenge 3 58
Purpose To explain how to place a textual stamp on a PDF document.  This is commonly referred to as an annotation, or possibly a watermark, but a watermark is generally different in that it is somewhat translucent.  Watermark’s may be text or graph…
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now