Solved

Get value of ID Column in dataGridView ForEach?

Posted on 2008-06-25
2
11,915 Views
Last Modified: 2013-12-16
I have some code that I would like to execute for each row in a dataGridView that I am populating from a database.  Does anyone know how I can get the value of the ID Column for each row for this foreach?  Any help is greatly appreciated.

Here is my code if you need it:

(You may notice that the Select Statement and columns in the dataGridView don't add up...  I accidentally deleted part of the Select Statement, so I'll be fixing that today...  In the meantime what is there is correct...

Thanks Again,
try

{

//Populate the Collection DataGridView

string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Environment.CurrentDirectory + @"\DB.accdb;Jet OLEDB:Database Password=xxxx;";
 

// create an open the connection

OleDbConnection conn = new OleDbConnection(conString);

OleDbCommand command = new OleDbCommand();

command = conn.CreateCommand();
 

// create the DataSet

DataSet ds = new DataSet();
 

// run the query

command.CommandText = "SELECT ID AS [#], CTitle AS [Title], CType AS [Type], CValue AS [Value] FROM Table1 WHERE Tab = 'Tab1';";

OleDbDataAdapter adapter = new OleDbDataAdapter();

adapter = new OleDbDataAdapter(command);

adapter.Fill(ds);
 

// close the connection

conn.Close();
 

bindingSource.DataSource = ds.Tables[0];
 

dataGridView1.DataSource = bindingSource;
 

//Set Value Column Format to Currency

dataGridView1.Columns["Value"].DefaultCellStyle.Format = "c";
 

//Count the number of rows

try

{

int CountString;

CountString = bindingSource.Count;

Label1.Text = CountString + "";

}

catch

{

}
 

//Total the value of results

try

{

String valueString = ds.Tables[0].Compute("Sum(Value)", String.Empty).ToString();

decimal valueString2 = Convert.ToDecimal(valueString);

String valueString3 = String.Format("{0:C}", valueString2);

if (valueString != "")

{

Label2.Text = valueString3;

}

}

catch

{

}
 

// set the size of the dataGridView Columns

this.dataGridView1.Columns[0].Width = 50;

this.dataGridView1.Columns[1].Visible = false;

this.dataGridView1.Columns[2].Width = 311;

this.dataGridView1.Columns[3].Width = 50;

this.dataGridView1.Columns[4].Width = 50;

this.dataGridView1.Columns[5].Width = 100;

this.dataGridView1.Columns[6].Width = 100;

this.dataGridView1.Columns[7].Width = 100;

this.dataGridView1.Columns[8].Width = 100;

this.dataGridView1.Columns[9].Width = 100;
 

//Sort on the Title Column

DataGridViewColumn sortColumn = dataGridView1.Columns[2];

ListSortDirection direction;

direction = ListSortDirection.Ascending;

dataGridView1.Sort(sortColumn, direction);
 

//Set the Selected Property of the First Row to False

dataGridView1.Rows[0].Selected = false;
 

//Clear selection in dataGridView

dataGridView1.ClearSelection();

dataGridView1.CurrentCell = null;

}

catch

{

}

Open in new window

0
Comment
Question by:M_Lyons
2 Comments
 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 500 total points
ID: 21871008
Not 100% sure what do you need. Do you need to get a value for row's column if column name, say, is "ID"? Or, in other words, you have a row, and want to get "ID" value from it but does not know what's the column number? Do I understand properly?

If yes, you probably need two nested loops. I have written some sample code, but it's in VB, hope you can understand (it's very straightforward. In button_Click1 we iterate through rows, and through cells in each row, and if cell's owning column is "ID" - we print content.

In Form_Load I just populate the grid.

If you can'r read vb6 code let me know.
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
 

        For Each r As DataGridViewRow In Me.dgv.Rows

            For i As Integer = 0 To r.Cells.Count - 1

                If r.Cells.Item(i).OwningColumn.Name = "ID" Then

                    Debug.WriteLine("ID = " & r.Cells.Item(i).Value)

                End If

            Next
 

        Next
 

    End Sub
 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' create datatable

        Dim dt As New DataTable

        ' create 3 datacolumns

        Dim dc0 As New DataColumn("ID")

        Dim dc1 As New DataColumn("Name")

        Dim dc2 As New DataColumn("Rank")

        ' add columns to datatable

        dt.Columns.Add(dc0)

        dt.Columns.Add(dc1)

        dt.Columns.Add(dc2)

        ' create, fill datarows and add them to table

        Dim dr0 As DataRow = dt.NewRow

        dr0.Item(0) = "22"

        dr0.Item(1) = "Bob"

        dr0.Item(2) = "H"

        Dim dr1 As DataRow = dt.NewRow

        dr1.Item(0) = "44"

        dr1.Item(1) = "Rod"

        dr1.Item(2) = "L"

        Dim dr2 As DataRow = dt.NewRow

        dr2.Item(0) = "66"

        dr2.Item(1) = "Ken"

        dr2.Item(2) = "M"

        dt.Rows.Add(dr0)

        dt.Rows.Add(dr1)

        dt.Rows.Add(dr2)
 

        ' set table as datasourse for datagridview

        Me.dgv.DataSource = dt
 

    End Sub

Open in new window

0
 

Author Closing Comment

by:M_Lyons
ID: 31470509
Thank you very much, that did work well.  I used a VB to C# converter online.  I love those things...  lol  Thanks Again.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

706 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

22 Experts available now in Live!

Get 1:1 Help Now