Getting DataRow information off a DataGrid (Database)

G

Guest

In Visual Studio 2005, I am developing a Windows Mobile application, using
Mobile SQL 2005.
I need Data from a Database to be shown in a DataGrid, this works.
But now I want to be able to get the Data of the selected DataRow, for
instance, I want to display the value of the "Klant" column of the selected
Row using:

DataRow currentRow = table.Rows[routeDataGrid.CurrentCell.RowNumber];
MessageBox.Show(currentRow["klant"].ToString());

I want to do this by making a DataTable which gets the information from
routeDataGrid.DataSource. To get the information from
routeDataGrid.DataSource to a DataTable, routeDataGrid.DataSource needs to be
cast to a DataTable, the way I do this is show in the next line:

DataTable table = (DataTable)routeDataGrid.DataSource;

When I do this, during runtime I get a: “InvalidCastException was unhandledâ€
I know the reason I get this Exception is, my routeDataGrid.DataSource is a
BindingSource and not a DataTable.

The only code I implement for button1 is:
DataTable table = (DataTable)routeDataGrid.DataSource;
The rest of my code is generated code that I got for placing the DataGrid
and the Details textboxes of the DataSources tab.

The third textbox shown on the UI is the Status textbox.
Now I don’t know how I should get to the DataRow Data of a Database. I
wanted to do this by using:
DataRow currentRow = table.Rows[routeDataGrid.CurrentCell.RowNumber];
but because the cast doesn’t work I don’t get the information I want to get.

The entire Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace PPCTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
if (RouteDBDataSetUtil.DesignerUtil.IsRunTime())
{
// TODO: Delete this line of code to remove the default
AutoFill for 'routeDBDataSet.Route'.
this.routeTableAdapter.Fill(this.routeDBDataSet.Route);
}

}

private void button1_Click(object sender, EventArgs e)
{
DataTable table = (DataTable)routeDataGrid.DataSource;
DataRow currentRow =
table.Rows[routeDataGrid.CurrentCell.RowNumber];
MessageBox.Show(currentRow["Klant"].ToString());
}
}
}
 
C

ClayB

The error message suggests your DataGridView.DataSource is a
BindingSource object and not a DataTable.

Try this code:

BindingSource bsrc = dataGridView1.DataSource as BindingSource;
if (bsrc != null)
{
DataRowView drv = bsrc[dataGridView1.CurrentCell.RowIndex] as
DataRowView;
if (drv != null)
{
MessageBox.Show(drv["Klant"].ToString());
}
}

===============
Clay Burch
Syncfusion, Inc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top