Schrader
Schrader

Reputation: 71

Reading from DataGridView

I have a DataGridViewfilled with information from my SQL: enter image description here

[Its only possible to click one complete row and not only a cell, shown in my picture]

I try some Code example from: Reading data from DataGridView in C# but it dosent work for my Problem.

I try this, because it seems good

dataGridView.Rows[MyIndex].Cells["MessageHeadline"].Value.ToString();

but i get an Error.

Now i want to take the Index (add with 1, because its start with 0) and if i press on a row, my program should take the information from my DataGridViewand give it back.

Upvotes: 1

Views: 306

Answers (3)

Sayed M. Idrees
Sayed M. Idrees

Reputation: 1408

just using the foreach loop can solve the problem.

        foreach (DataGridViewRow row in gridStore.Rows)
        {
            MessageBox.Show(row.Cells[2].Value.ToString());    //row.Cell[index Here!]
        }

Upvotes: 0

Shell
Shell

Reputation: 6849

Try to use CurrentRow instead of SelectedRow. The selected row only perform if you have selected row from RowHeader or the RowSelection property is set FullRowSelect. But, CurrentRow is actually focused row. You can get value even you have selected only single cell.

dataGridView.CurrentRow.Cells["MessageHeadline"].Value.ToString()

Upvotes: 2

Raging Bull
Raging Bull

Reputation: 18737

Try this:

Set the SelectionMode property of your datagridview to CellSelect. Now you will be able to select a cell itself.

And in CellMouseClick Event:

private void MyGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    string FullContent = "";
    for (int i = 0; i < MyGridView.Columns.Count; i++)
    {
        FullContent += MyGridView.Rows[e.RowIndex].Cells[i].Value.ToString() + "^";
    }
    FullContent = FullContent.Substring(0, Content.Length - 1);
    string[] Content=FullContent.Split('^')
}

Now you can get each column content from Content array. Like:

Content[0],Content[1],Content[2],etc.

For example, if you click the first row in your datagridview. You can access the contents like:

FullContent;  //1^Test BGW 1^Test^All^12.05.2014^.....

Splitted contents:

Content[0];   //1
Content[1];   //Test BGW 1
Content[2];   //Test
Content[3];   //All
Content[4];   //12.05.2014

Upvotes: 1

Related Questions