views:

316

answers:

1

I'm a beginner with C# so I made a little app, to figure out how to work with Linq and databased in C#.

What I'm trying to do is in a DataGridView when someone clicks a row containing some data I want to go from e.RowIndex to a Linq object of the data in that row, my attempt involved using the DataBoundItem.

But for whatever reason the currentAd variable in this code always gives me a null value.

    private void clickRow(object sender, DataGridViewCellEventArgs e)
    {
        richTextBox1.Text = "There is a clickRow event with row index " + e.RowIndex;
        Ad currentAd = adsDataGridView.Rows[e.RowIndex].DataBoundItem as Ad;
        if (currentAd != null) // The problem is it is always null
        {
            MessageBox.Show( currentAd.ToString() );
        }
    }

Thanks for your help.

A: 

In the examples given on the MSDN site, they cast the row to a DataGridViewRow object first, before taking the DataBoundItem, so you might want to try it this way:

    private void clickRow(object sender, DataGridViewCellEventArgs e)
    {
        richTextBox1.Text = "There is a clickRow event with row index " + e.RowIndex;
        DataGridViewRow row = adsDataGridView.Rows[e.RowIndex] as DataGridViewRow;
        Ad currentAd = row.DataBoundItem as Ad;
        if (currentAd != null) 
        {
            MessageBox.Show( currentAd.ToString() );
        }
    }
Robert Harvey
Yeah, I looked over there and I was trying to play around with that and it still wasn't working. I tried it and it was still giving null.
Emil
It would seem then that your cast to `Ad` is failing.
Robert Harvey