Gridview not showing data for a particular field in linq - linq

I want to data in gridview for a particular mail_id. but wheneven i add this where condition its not showing anything. please help
if (!IsPostBack)
{
var mail = lblmail.Text;
var result = from test in je.jobposting orderby test.post_date where test.c_j_email==mail select test;
foreach (var items in result)
{
gvjob.DataSource = result;
gvjob.DataBind();
}
}

Is this better?
{
var mail = lblmail.Text;
// here, I assume jobposting is a DataTable
if (0 < je.jobposting.Rows.Count) {
var result = from test in je.jobposting orderby test.post_date where test.c_j_email==mail select test;
if (result.Any()) {
gvjob.DataSource = result;
gvjob.DataBind();
} else {
Response.WriteLine("No Match for c_j_email=" + mail + ".");
}
} else {
Response.WriteLine("<b>No Data in jobposting DataTable!</b>");
}
}

Related

How to check if the user doesn't select any item in the list?

I have a list view that list the activities. I have a way to get the selected values. What I don't know is how can I check if the user doesn't select any items from the list. How can I do this?
This is how I populate my list this will return at least 5-20 activities:
public void Get_Activities()
{
try
{
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var getActivity = conn.QueryAsync<ActivityTable>("SELECT * FROM tblActivity WHERE Deleted != '1' ORDER BY ActivityDescription");
var resultCount = getActivity.Result.Count;
if (resultCount > 0)
{
var result = getActivity.Result;
lstActivity.ItemsSource = result;
lstActivity.IsVisible = true;
}
else
{
lstActivity.IsVisible = false;
}
}
catch (Exception ex)
{
//Crashes.TrackError(ex);
}
}
And this is how I get the values of the selected items on my list:
foreach(var x in result)
{
if (x.Selected)
{
// do something with the selected items
}
}
My question is like this
if(list.selecteditemcount == 0){
DisplayAlert("Error","Please select atleast 1 item","Ok");
}
In xamarin projects you can use Linq (using System.Linq). With Linq it's really easy to filter your list like that:
if(!list.Any(x => x.Selected == true))
{
// DisplayAlert...
}
This basically checks if any of your items has the value Selected='true'
Or without Linq you can do something like this:
if(list.FindAll(x => x.Selected).Count() == 0)
{
//DisplayAlert...
}
Use this
if (result.Any(x => x.Selected))
{
}
else
{
await DisplayAlert("Application Error", "Please choose at least one(1) activity", "Ok");
}

Dynamically Set Column Name In LINQ Query

Im trying to write a method which will allow me to search different DataTables, over different columns.
So far i have the following:
string selectedValue;
string searchColumn;
string targetColumn;
var results = (from a in dt.AsEnumerable()
where a.Field<string>(searchColumn) == selectedValue
select new
{
targetColumn = a.Field<string>(targetColumn)
}).Distinct();
Which kind of gets the job done, but I'm left with the column name as targetColumn rather than the actual column name I want.
Is there any way to resolve this?
Thanks in advance
CM
I make a LINQ to Datatables
public List<DataRow> Where(this DataTable dt, Func<DataRow, bool> pred)
{
List<DataRow> res = new List<DataRow>();
try {
if (dt != null && dt.Rows.Count > 0) {
for (i = 0; i <= dt.Rows.Count - 1; i++) {
if (pred(dt(i))) {
res.Add(dt(i));
}
}
}
} catch (Exception ex) {
PromptMsg(ex);
}
return res;
}
Usage :
var RowsList = dt.Where(f => f("SomeField").toString() == "SomeValue" ||
f("OtherField") > 5);

Column sort reset of ascending/descending on 3rd click

Suppose we've a grid with sortable columns.
If a user clicks on a column, it gets sorted by 'asc', then if a user clicks the column header again, it gets sorted by 'desc', now I want similar functionality when a user clicks the column third time, the sorting is removed, i.e. returned to previous style, the css is changed back to normal/non-italic etc?
Today I was trying to achieve same thing. I've skimmed through SlickGrid code but didn't find any 'Reset' function. So, I've tweaked the slick.grid.js v2.2 a little bit.
Basically you just need to add a new array - 'latestSortColumns' which will store sort columns state (deep copy of internal SlickGrid sortColumns array).
var latestSortColumns = [];
Optionally add new setting to opt-in for sort reset.
var defaults = {
(...),
autoResetColumnSort: false
};
Change setupColumnSort to reset sort after third click on column's header.
function setupColumnSort() {
$headers.click(function (e) {
// temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328)
e.metaKey = e.metaKey || e.ctrlKey;
if ($(e.target).hasClass("slick-resizable-handle")) {
return;
}
var $col = $(e.target).closest(".slick-header-column");
if (!$col.length) {
return;
}
var column = $col.data("column");
if (column.sortable) {
if (!getEditorLock().commitCurrentEdit()) {
return;
}
var sortOpts = null;
var i = 0;
for (; i < sortColumns.length; i++) {
if (sortColumns[i].columnId == column.id) {
sortOpts = sortColumns[i];
sortOpts.sortAsc = !sortOpts.sortAsc;
break;
}
}
**if ((e.metaKey || (options.autoResetColumnSort && latestSortColumns[i] != null && latestSortColumns[i].sortAsc === !column.defaultSortAsc)) && options.multiColumnSort) {**
if (sortOpts) {
sortColumns.splice(i, 1);
**latestSortColumns.splice(i, 1);**
}
}
else {
if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) {
sortColumns = [];
}
if (!sortOpts) {
sortOpts = { columnId: column.id, sortAsc: column.defaultSortAsc };
sortColumns.push(sortOpts);
} else if (sortColumns.length == 0) {
sortColumns.push(sortOpts);
}
}
setSortColumns(sortColumns);
if (!options.multiColumnSort) {
trigger(self.onSort, {
multiColumnSort: false,
sortCol: column,
sortAsc: sortOpts.sortAsc}, e);
} else {
trigger(self.onSort, {
multiColumnSort: true,
sortCols: $.map(sortColumns, function(col) {
return {sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc };
})}, e);
}
}
});
}
Store new state after every sort change in latestSortColumns:
function setSortColumns(cols) {
sortColumns = cols;
var headerColumnEls = $headers.children();
headerColumnEls
.removeClass("slick-header-column-sorted")
.find(".slick-sort-indicator")
.removeClass("slick-sort-indicator-asc slick-sort-indicator-desc");
$.each(sortColumns, function(i, col) {
if (col.sortAsc == null) {
col.sortAsc = true;
}
var columnIndex = getColumnIndex(col.columnId);
if (columnIndex != null) {
headerColumnEls.eq(columnIndex)
.addClass("slick-header-column-sorted")
.find(".slick-sort-indicator")
.addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc");
}
});
**for (var i = 0; i < sortColumns.length; i++)
latestSortColumns[i] = { columnId: sortColumns[i].columnId, sortAsc: sortColumns[i].sortAsc };**
}
That's all, should work now.
This is a function I call to reset all columns back to their original order.
It requires one of columns to be set up as not sortable.
In the example below I use the first column of the table, columns[0], which has the field id "locus".
function removeSorting() {
columns[0].sortable = true;
$('.slick-header-columns').children().eq(0).trigger('click');
columns[0].sortable = false;
// clear other sort columns
grid.setSortColumns( new Array() );
}
Then in the typical dataView.sort() function you make an exception for this column:
grid.onSort.subscribe(function(e,args) {
var cols = args.sortCols;
dataView.sort(function (dataRow1, dataRow2) {
for( var i = 0; i < cols.length; i++ ) {
var field = cols[i].sortCol.field;
// reset sorting to original indexing
if( field === 'locus' ) {
return (dataRow1.id > dataRow2.id) ? 1 : -1;
}
var value1 = dataRow1[field];
var value2 = dataRow2[field];
if( value1 == value2 ) continue;
var sign = cols[i].sortAsc ? 1 : -1;
return (value1 > value2) ? sign : -sign;
}
return 0;
});
});
Will the table always be sorted in some order on some column?
If not then you'll have to store a lot of state the first time a column is clicked just in case you want to restore it after a third click.

LINQ in Business Layer paging / sorting gridview in User layer

I have a gridview in my user layer that uses a business layer method as its datasource, and I want the gridview to support paging and sorting. When I returned an Ienumerable from the method, it will bring back all of the data. If I use Take/Skip to bring back only a page's worth, the gridview doesn't realize that there are many pages of data.
When I change the Ienumerable to an IQueryable, the DataBind() fails because the data has already been disposed of. I think this problem has something to do with when the query actually executes and it may have to do with the filters I am applying to the query (see below).
User Layer Code:
grdSelectedQuestionaires.DataSource = assessment.FilteredAssessmentList(filter);
grdSelectedQuestionaires.DataBind(); <-- Fails - "Cannot access a disposed object"
Business Layer Code:
public IQueryable<Assessment> FilteredAssessmentList(AssessmentSearchFilter filter)
{
using (PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext())
{
var rows = (
from a in dc.vPAQSummaries
select new Assessment()
{
PAQNumber = a.PAQNumber.Trim(),
CustomerID = (int)a.CustomerID,
Department = a.Department.Trim(),
CustomerName = a.CustomerName.Trim(),
DOTNumber = a.DOTNumber.Trim(),
OrgName = a.OrgName.Trim(),
DateEntered = a.DateEntered,
GroupNumber = a.GroupNumber.Trim(),
JobTitle = a.JobTitle.Trim(),
FileNames = a.FileNames.Trim(),
AnalystType = a.AnalystType.ToString(),
Incumbents = a.Incumbents,
});
// Filter by Customer ID
if (filter.CustomerID > 0)
{
rows = rows.Where(r => r.CustomerID == filter.CustomerID);
}
else
{
rows = rows.Where(r => r.CustomerID != null);
}
// Filter by DOT Number
if (!string.IsNullOrEmpty(filter.DOTNumberFrom))
{
if (string.IsNullOrEmpty(filter.DOTNumberTo))
{
rows = rows.Where(r => r.DOTNumber == filter.DOTNumberFrom);
}
else
{
rows = rows.Where(r => r.DOTNumber.CompareTo(filter.DOTNumberFrom) >= 0
&& r.DOTNumber.CompareTo(filter.DOTNumberTo) <= 0);
}
}
// Filter by OrgName
if (!string.IsNullOrEmpty(filter.OrgName))
{
rows = rows.Where(r => r.OrgName.StartsWith(filter.OrgName));
}
// Filter by Group
if (!string.IsNullOrEmpty(filter.GroupNumberFrom))
{
if (!string.IsNullOrEmpty(filter.GroupNumberTo))
{
rows = rows.Where(r => r.GroupNumber == filter.GroupNumberFrom);
}
else
{
rows = rows.Where(r => r.GroupNumber.CompareTo(filter.GroupNumberFrom) >= 0
&& r.GroupNumber.CompareTo(filter.GroupNumberTo) <= 0);
}
}
if (filter.Skip > 0)
{
rows = rows.Skip(filter.Skip);
}
if (filter.Take > 0)
{
rows = rows.Take(filter.Take);
}
else
{
rows = rows.Take(100);
}
return rows.Distinct();
}
}
}
The paging problem was caused by the Using statement. Changing this:
using (PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext())
{
...
}
to this:
PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext();
Made paging work. Now I have to figure out how sorting works.

Expand all items in RadGrid Hierarchy

I am using a RadGrid (2009 Q2) with a hierarchy. Is there a way in the client api to expand all rows and vice-versa?
thanks!
Update:
I have written a javascript function based off the api documentation suggested by Dick Lampard below to expand/collapse all rows in a radgrid with three levels. It expands all the mastertableview rows and all the nested detailtableview rows in both sub levels of the first mastertableview row, but it breaks when it goes the to detailtableview rows for the second mastertableview row (whew!). The error I am getting is "_350 is undefined". This is coming from a Telerik.Web.UI.WebResource file.
function ExpandCollapseAll(expand) {
var grid = $find("<%= rgHistory.ClientID %>");
master = grid.get_masterTableView();
var masterRowCount = master.get_dataItems().length;
for (masterIndex = 0; masterIndex < masterRowCount; masterIndex++) {
if (expand) {
master.expandItem(masterIndex);
}
else {
master.collapseItem(masterIndex);
}
}
var detailTables = grid.get_detailTables();
var detailTableCount = detailTables.length;
for (detailTableIndex = 0; detailTableIndex < detailTableCount; detailTableIndex++) {
var detailTable = detailTables[detailTableIndex];
var rowCount = detailTable.get_dataItems().length;
for (rowIndex = 0; rowIndex < rowCount; rowIndex++) {
if (expand) {
//expandItem is failing! detailTableIndex and rowIndex are correct
detailTables[detailTableIndex].expandItem(rowIndex);
}
else {
detailTables[detailTableIndex].collapseItem(rowIndex);
}
}
}
}
ANY IDEAS?!?!
There is client API for hierarchy expansion as well as ExpandHierarchyToTop() server method. Check out this demo.
Dick
If you would like to see all the hierarchy levels, Set HierarchyDefaultExpanded to the MasterTableView and all the GridTableViews. See this link for more details.
Try This
protected void Page_PreRenderComplete() {
if (!Page.IsPostBack) {
foreach (GridItem item in MyGrid.MasterTableView.Controls[0].Controls) {
if (item is GridGroupHeaderItem)
if (item.GroupIndex.ToString() != "0")
item.Expanded = !item.Expanded;
}
}
}
after radGrid.DataBind()
use this Mehtod
private void ExpanadAllRadGridNodes()
{
foreach (GridDataItem item_L1 in radgridQuestionGroups.MasterTableView.Items)
{
foreach (GridTableView item_L2 in (item_L1 as GridDataItem).ChildItem.NestedTableViews)
{
foreach (GridDataItem item_L3 in item_L2.Items)
{
item_L3.Expanded = true;
}
}
}
}

Resources