Monday, 16 November 2009

Linq - How to check if an item exists in a DataContext

How to find an item or instance of a class in a datacontext:

if (dc.GetTable<MyBusinessObjects.Person>().Contains(personToFind)


//variables used:
//dc = MyDataContext
//personToFind = instance of the data class





tags: DataContext, Find, Contains, Search, item, c#, .net, DataContext.Contains, DataContext.Find,

Monday, 13 July 2009

Simple Lambda

Simple lambda samples:
----------------------
Syntax: Func<[type of 1st parameter], [type of return param]> [FUNCTION_NAME] = 1st parameter
=> {[function definition]}

a) //Define and call a function:
Func myFunc = x => x == 5;
int valueToCheck = Convert.ToInt32(textBox1.Text);
result = myFunc((int)valueToCheck);

b) // Define another function:
Func myFuncString = x => x.ToLower() == "five";
string strToCheck = textBox1.Text;
result = myFuncString(strToCheck);

c) Func myUntestedSample = (x, y) =>
{
return (typeof(x)==System.String && int.TryParse(y));
};

Thursday, 17 July 2008

DataGrid Paging - not working

DataGrid Paging

My datagrid's paging did not work at all: it would post back, go into the grid's PageIndexChanged event, set the new page index, fetch a new datasource (datatable from the database) and rebind the grid, and change the page number in the paging footer but the grid would still show the same set of data!

To fix it I needed to remove AllowCustomPaging="true".


<asp:DataGrid runat="server" ID="MyGrid"
CellSpacing="0"
CellPadding="6"
Width="100%"
AllowSorting="True"
OnSortCommand="MyGrid_Sorting"
OnItemDataBound="MyGrid_ItemDataBound"
OnItemCommand="MyGrid_ItemCommand"
Visible="true"
PagerStyle-Mode="NumericPages"
AutoGenerateColumns="False"
AllowPaging="True"
AllowCustomPaging="True"
AllowCustomPaging="True"
OnPageIndexChanged="MyGrid_PageIndexChanging">


There's a lot of articles about paging:
- http://www.dotnetjunkies.ddj.com/Tutorial/AAF84EAD-C412-4304-A88A-AF26F8C883E6.dcik
- http://aspnet.4guysfromrolla.com/articles/091003-1.aspx
- or search the web for more.

The catch is that paging and sorting is very customisable, so it is easy to get it wrong. Paging often does not work because of different methods being available for doing paging (built-in or paging, and custom Paging) and the implementation of these methods being confused. It depends on your implementation of your datagrid, when you load and reload the data, where you do the sorting, whether your stored procedure sorts the data (and does the paging, by retrieving only 10 recors at a time) or whether your page does sorting by using dropdownlists or clickable columns.


In my case i was trying to use custom paging, then reverted back to built-in paging, and it was a tiny left-over from custom paging (allowcustompaging=true) that caused me hours of debugging.
Hope it helps.

Thursday, 10 July 2008

DataGridLinkButton

Programming language: C#

DataGridLinkButton
is a class that is often encountered when working with the headings in a datagrid containing BoundColumns; you typically come across it when you try to edit the columns during the _ItemCreated() or _ItemDataBound() events of the datagrid.

Problem: Checking for the type DataGridLinkButton can be tricky, because of the class being protected.

Solution: find the control by ordinal reference (i.e. in the header row of a datagrid cell there will only ever be one control... the column heading - which is a DataGridLinkButton, generated from the BoundColumn of the datagrid).
foreach(TableCell cell in e.Item.Cells)
desiredControl = cell.Controls[0]; // However, this will need to be cast, see code below.

So in the header row you can easily find the cells of the datagrid, which should contain one control each: the header per cell. If a header is found and it was created from a BoundColumn that is clickable (i.e. you've enabled sorting on the grid), then the control will be a DataGridLinkButton, which you can cast to a linkbutton.

Scenario: in mydatagrid_ItemDataBound() the event called when each datagrid line is created, I try to set a tooltip on each heading in the grid. The columns are dynamically shown and hidden and configured by each user individually; the tooltips are custom phrases that the client requested, so the ItemDataBound event is ideal for finding only those columns being displayed, finding the column name (see datagridLinkButtontext below) and then modifying the column.

Code:

protected void myDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
//Check if this is the header row of the grid:
if (e.Item.ItemType == ListItemType.Header)

//Loop through the columns (cells) of the header row
foreach(TableCell cell in e.Item.Cells)
{
string datagridLinkButtontext = string.Empty;
LinkButton lb = new LinkButton();
try
{
lb = (LinkButton)cell.Controls[0];
}
catch (InvalidCastException ex)
{
// do nothing if its not a linkbutton
}
if (lb != null) datagridLinkButtontext = lb.Text;
// now you can use the above text to determine which column you're working with,
// and do something with it, i.e as in my case set the tooltip:
cell.ToolTip = getTooltipForColumn(datagridLinkButtontext);
}
...
}