Monday, April 16, 2007

VS2003: How do I retrieve the current row from a DataTable to which a DataGrid is bound after the grid has been sorted?


In an unsorted DataGrid bound to a DataTable, you can get a reference to a row in the DataTable through the DataGrid.CurrentRowIndex. DataTable dataTable = (DataTable)

dataGrid1.DataSource;
DataRow dataRow = dataTable.Rows[ dataGrid1.CurrentRowIndex ];

But if the grid has been sorted, you can no longer get at the current row in the table through the grid's CurrentRowIndex. But for both unsorted and sorted grids, you can get at the current row through the BindingContext and the Current property of the BindingManagerBase.

BindingManagerBase bm =
dataGrid1.BindingContextr[ dataGrid1.DataSource, dataGrid1.DataMember ];
DataRow dataRow = ( (DataRowView) bm.Current ).Row;

Wednesday, March 21, 2007

SQL: Creating search Stored Procedures

Below you'll find a good way to create a search stored procedure. This way you avoid creating different stored procedures to search or filtering the data in-memory.

DECLARE
@ProductName VARCHAR(50),
@CompanyName VARCHAR(50),
@CategoryName VARCHAR(50)
DECLARE
@UnitPrice MONEY,
@UnitsInStock SmallInt

--SET @ProductName = '%Cha%'
SET @CompanyName = '%exotic%'
SET @CategoryName = '%condi%'

SELECT
[Products].[ProductName],
[Suppliers].[CompanyName],
[Categories].[CategoryName],
[Products].[UnitPrice],
[Products].[UnitsInStock]
FROM
[Products]
INNER JOIN [Suppliers] ON [Products].[SupplierId] = [Suppliers].[SupplierId]
INNER JOIN [Categories] ON [Products].[CategoryId] = [Categories].[CategoryId]
WHERE
(@ProductName IS NULL OR [Products].[ProductName] LIKE @ProductName)
AND
(@CompanyName IS NULL OR [Suppliers].[CompanyName] LIKE @CompanyName )
AND
(@CategoryName IS NULL OR [Categories].[CategoryName] LIKE @CategoryName )