I am trying to set the width of a DevExpress grid in percentage but the property is not available for me like it is in every example I see. I am using a MasterDetail grid Devexpress version 12.1
settings.Width = Unit.Percentage(100);
How can I set the width property for the whole grid to 100% and then also how would I set the same property for the colums. Here is my grid
#Html.DevExpress().GridView(
settings => {
settings.Name = "masterGrid";
settings.CallbackRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterPartial" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterAddNewPartial" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterUpdatePartial" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterDeletePartial" };
settings.KeyFieldName = "InwardsGoodsID";
settings.Columns.Add(column =>
{
column.FieldName = "CustomerID";
column.Caption = "Customer";
column.ColumnType = MVCxGridViewColumnType.ComboBox;
var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
comboBoxProperties.DataSource = Model.CustomersList;
comboBoxProperties.TextField = "CustomerName";
comboBoxProperties.ValueField = "CustomerID";
comboBoxProperties.ValueType = typeof(int);
});
settings.Columns.Add(column =>
{
column.FieldName = "CustomerReference";
column.Caption = "Customer Reference";
});
settings.Columns.Add(column =>
{
column.FieldName = "TimberShadeReference";
column.Caption = "TimberShade Reference";
});
settings.Columns.Add(column =>
{
column.FieldName = "DateReceived";
column.Caption = "Date Received";
column.PropertiesEdit.DisplayFormatString = "d";
});
settings.Columns.Add(column =>
{
column.FieldName = "Comment";
column.Caption = "Comment";
});
settings.SettingsDetail.AllowOnlyOneMasterRowExpanded = true;
settings.SettingsDetail.ShowDetailRow = true;
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.SetDetailRowTemplateContent(c =>
{
Html.RenderAction("GridViewDetailPartial", new { inwardsgoodsID = DataBinder.Eval(c.DataItem, "InwardsGoodsID") });
});
//TO OPEN THE FIRST EDITABLE ROW
//settings.PreRender = (sender, e) =>
//{
// ((MVCxGridView)sender).DetailRows.ExpandRow(0);
//};
}).Bind(Model.InwardsGoods).GetHtml()
Ok so I found the answer. What I did to solve this was at the top of the cshtml page I added this using statement.
#using System.Web.UI.WebControls;
Related
I have a problem with the system for ordering products.
Scenario:
Two separate browsers
Two separate accounts (after logging in a separate session id)
when clicked, grouped, and enabled in the connect string MultipleActiveResultSets = true.
Users click at the same time (each has different filters set, grouping), but when the second user clicks on, the user gets the result of the first user query (different parameters)
Update
[C#]
PartialViewResult AdvancedCustomBindingCore(GridViewModel viewModel)
{
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
GridViewCustomBindingHandlers.SetModel(iMagoDataProvider.Get_f_MgKar(_Session));///////////////////-------------------ustawiamy do modelu zrodlo danych .....
if (Session["fulltextsearch"] == null)
{
GridViewCustomBindingHandlers.SetModel(iMagoDataProvider.Get_f_MgKar(_Session));
Session["fulltextsearch"] = null;
}
else
{
GridViewCustomBindingHandlers.SetModel(iMagoDataProvider.Get_f_MgKarFullTextSearch(_Session));
}
viewModel.ProcessCustomBinding(
GridViewCustomBindingHandlers.GetDataRowCountAdvanced,
GridViewCustomBindingHandlers.GetDataAdvanced,
GridViewCustomBindingHandlers.GetSummaryValuesAdvanced,
GridViewCustomBindingHandlers.GetGroupingInfoAdvanced,
GridViewCustomBindingHandlers.GetUniqueHeaderFilterValuesAdvanced
);
return PartialView("GridViewMgKarPartial", viewModel);
}
static GridViewModel CreateGridViewModelWithSummary()
{
var viewModel = new GridViewModel();///////////////////-------------------ustawiamy kolumny ze zrodla danych.....
viewModel.KeyFieldName = "SymKar;LogoP;JM;SymWL";
viewModel.Columns.Add("SymKar");
viewModel.Columns.Add("SymKarObcy");
viewModel.Columns.Add("OpiKar");
viewModel.Columns.Add("L_OpiKar_EN");
viewModel.Columns.Add("JM");
//////////////Jezeli ma byc niewidoczna to w cshtml tez sie musi zgadzac....czyli nie dodajemy
viewModel.Columns.Add("CenaNetto");
//////////////Jezeli ma byc niewidoczna to w cshtml tez sie musi zgadzac....czyli nie dodajemy
viewModel.Columns.Add("IloscPAL");
viewModel.Columns.Add("StanDys");
viewModel.Columns.Add("GruKar");
viewModel.Columns.Add("Waga");
viewModel.Columns.Add("LogoP");
viewModel.Columns.Add("RodzajHandlowy");
viewModel.Pager.PageSize = 20;
//viewModel.TotalSummary.Add(new GridViewSummaryItemState() { FieldName = "Size", SummaryType = SummaryItemType.Sum });
//viewModel.TotalSummary.Add(new GridViewSummaryItemState() { FieldName = "Subject", SummaryType = SummaryItemType.Count });
//viewModel.GroupSummary.Add(new GridViewSummaryItemState() { FieldName = string.Empty, SummaryType = SummaryItemType.Count });
return viewModel;
}
#endregion CustomBindingRoute_Settings
#region CustomBindingRoute_General
public ActionResult GridViewMgKarPartial(string selectedValues)//------------------------------------------------Ustawiamy nazwe dla View ktory powstal...........
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
Session[_SessionSelected] = selectedValues;
GridViewModel viewModel = GridViewExtension.GetViewModel(str_GridViewName);
if (viewModel == null)
viewModel = CreateGridViewModelWithSummary();
string _FilterExpression = "";
int FILTER_UserID = usr.users_ID;
if (Session["myGridStatefiltrKM"] != null)
{
var userFiltersList = iMagoDataProvider.wusr_f_GetUserFiters(FILTER_UserID, "GridView_mpid_" + menu_pozycje_ID).Where(x => x.wusr_GrdFiltMenForSessionidId == Convert.ToInt32(Session["myGridStatefiltrKM"])).ToList().OrderByDescending(m => m.DomyslnyFiltr).ThenByDescending(m => m.DateCreated);
foreach (var item in userFiltersList)
{
_FilterExpression = item.FilterExpression.ToString();
}
}
if (_FilterExpression != "")
viewModel.FilterExpression = _FilterExpression;//"StartsWith([SymKar], 'aa')";
return AdvancedCustomBindingCore(viewModel);
}
// Paging
public ActionResult AdvancedCustomBindingPagingAction(GridViewPagerState pager)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplyPagingState(pager);
string _FilterExpression = "";
try
{
db.wusr_p_GetGridFilterMenuForUsers(_Session, menu_pozycje_ID, str_GridViewName, ref _FilterExpression);//Pamietaj o wpisaniu prawidlowej nazwy dla grida(unikatowego w obrebie menu)
}
catch (Exception e)
{
return ExceptionHandle(e);
}
if (_FilterExpression != "")
{
viewModel.FilterExpression = _FilterExpression;//"StartsWith([SymKar], 'aa')";
}
if (Session["fulltextsearch"] == null)
{
//var model = iMagoDataProvider.Get_f_ListaZgloszen(userSessionid, 1);
Session["fulltextsearch"] = null;
return AdvancedCustomBindingCore(viewModel);
// return PartialView("Lista", model);
}
else
{
if (Session["filtr"] != null)
{
viewModel.FilterExpression = Session["filtr"].ToString();
}
var model = Session["fulltextsearch"];
return AdvancedCustomBindingCore(viewModel);
}
// return AdvancedCustomBindingCore(viewModel);
}
// Filtering
public ActionResult AdvancedCustomBindingFilteringAction(GridViewFilteringState filteringState)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplyFilteringState(filteringState);
//Zapamietujemy filtry - na okres sessji ... pozniej odczytujemy ogolne tak by przy nowej sesji zawsze byly domyslne
int FILTER_UserID = usr.users_ID;
string _FilterExpression = "";
if (Session["myGridStatefiltrKM"] != null)
{
var userFiltersList = iMagoDataProvider.wusr_f_GetUserFiters(FILTER_UserID, "GridView_mpid_" + menu_pozycje_ID).Where(x => x.wusr_GrdFiltMenForSessionidId == Convert.ToInt32(Session["myGridStatefiltrKM"])).ToList().OrderByDescending(m => m.DomyslnyFiltr).ThenByDescending(m => m.DateCreated);
foreach (var item in userFiltersList)
{
_FilterExpression = item.FilterExpression.ToString();
}
}
return AdvancedCustomBindingCore(viewModel);
}
// Sorting
public ActionResult AdvancedCustomBindingSortingAction(GridViewColumnState column, bool reset)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplySortingState(column, reset);
return AdvancedCustomBindingCore(viewModel);
}
// Grouping
public ActionResult AdvancedCustomBindingGroupingAction(GridViewColumnState column)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplyGroupingState(column);
return AdvancedCustomBindingCore(viewModel);
}
Partial View
[HTML]
#{
SortedList<string, IMago.Models.model_Uprawnienia> rights = ViewBag.Rights;
}
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "GridView_mgKar";
settings.CallbackRouteValues = new { Controller = "KartotekaMaterialowa", Action = "GridViewMgKarPartial" };
if (PageHelper.isVisible(rights, "GridView_mgKar_Grid_Oper_Filtr"))
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Filtering,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingFilteringAction" }
);
if (PageHelper.isVisible(rights, "GridView_mgKar_Grid_Oper_Group"))
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Grouping,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingGroupingAction" }
);
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.KeyFieldName = "SymKar;LogoP;JM;SymWL";
settings.SettingsPager.Visible = true;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.SettingsBehavior.AllowSelectByRowClick = false;
settings.Settings.ShowFilterBar = GridViewStatusBarMode.Visible;
settings.Settings.ShowFooter = true;
settings.SettingsSearchPanel.Visible = false;
settings.Settings.ShowFilterRowMenuLikeItem = true;
settings.Settings.ShowHeaderFilterButton = true;
settings.EnableRowsCache = false;
settings.Styles.AlternatingRow.Enabled = DefaultBoolean.True;
settings.Styles.AlternatingRow.BackColor = System.Drawing.Color.White;
settings.Styles.Row.BackColor = System.Drawing.Color.WhiteSmoke;
settings.Styles.FocusedRow.CssClass = "EmptyFocusedRow";
settings.Styles.RowHotTrack.CssClass = "RowHover";
settings.Styles.Cell.Wrap = DefaultBoolean.False;
settings.Styles.Cell.Font.Size = FontUnit.Smaller;
settings.Styles.Header.Font.Size = FontUnit.XSmall;
settings.Styles.Header.Font.Bold = true;
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_SymKar"))
settings.Columns.Add(c =>
{
c.FieldName = "SymKar";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymKar").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_Nag_Kol_pd_isstandard")) //Przy ZPW
settings.Columns.Add(column =>
{
column.FieldName = "pd_isstandard";
column.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolpd_isstandard").ToUpper();
column.Width = 20;
column.HeaderStyle.Wrap = DefaultBoolean.True;
column.ColumnType = MVCxGridViewColumnType.CheckBox;
column.ReadOnly = true;
//column.PropertiesEdit.DisplayFormatString = "c";
column.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_SymKarObcy"))
settings.Columns.Add(c =>
{
c.FieldName = "SymKarObcy";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymKarObcy").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_OpiKar"))
settings.Columns.Add(c =>
{
c.FieldName = "OpiKar";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolOpikar").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_L_OpiKar_EN"))
settings.Columns.Add(c =>
{
c.FieldName = "L_OpiKar_EN";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolOpikarEn").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_JM"))
settings.Columns.Add(c =>
{
c.FieldName = "JM";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolJM").ToUpper();
c.Width = 50;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_CenaNetto"))
settings.Columns.Add(c =>
{
c.FieldName = "CenaNetto";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolCenaNetto").ToUpper();
c.PropertiesEdit.DisplayFormatString = PageHelper.N2_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_SymWL"))
settings.Columns.Add(c =>
{
c.FieldName = "SymWL";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymWL").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_IloscPAL"))
settings.Columns.Add(c =>
{
c.FieldName = "IloscPAL";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolIloscCalopaletowa").ToUpper();
c.Width = 50;
c.PropertiesEdit.DisplayFormatString = PageHelper.N0_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_StanDys"))
settings.Columns.Add(c =>
{
c.FieldName = "StanDys";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolStanWolny").ToUpper();
c.Width = 50;
c.PropertiesEdit.DisplayFormatString = PageHelper.N0_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_GruKar"))
settings.Columns.Add(c =>
{
c.FieldName = "GruKar";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymKarGrup").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_Waga"))
settings.Columns.Add(c =>
{
c.FieldName = "Waga";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolWaga").ToUpper();
c.Width = 50;
c.PropertiesEdit.DisplayFormatString = PageHelper.N3_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_LogoP"))
settings.Columns.Add(c =>
{
c.FieldName = "LogoP";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolLogoP").ToUpper();
// c.PropertiesEdit.DisplayFormatString = PageHelper.N3_Format
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_RodzajHandlowy"))
settings.Columns.Add(c =>
{
c.FieldName = "RodzajHandlowy";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolRodzajHandlowy").ToUpper();
// c.PropertiesEdit.DisplayFormatString = PageHelper.N3_Format
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Grid_Oper_Sort"))
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Sorting,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingSortingAction" }
);
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Paging,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingPagingAction" }
);
settings.EnableCallbackAnimation = false;
settings.CommandColumn.Visible = true;
settings.CommandColumn.ShowSelectCheckbox = true;
settings.CommandColumn.Width = Unit.Pixel(65);
settings.SettingsBehavior.ConfirmDelete = true;
settings.SettingsBehavior.AllowFocusedRow = true;
settings.ClientSideEvents.SelectionChanged = "OnSelectionChanged";
settings.ClientSideEvents.EndCallback = "OnEndCallback";
settings.CustomJSProperties = (sender, e) =>
{
e.Properties["cpFilterExpression"] = (sender as MVCxGridView).FilterExpression;
MVCxGridView g = sender as MVCxGridView;
Dictionary<int, object> dict = new Dictionary<int, object>();
int startIndex = g.PageIndex * g.SettingsPager.PageSize;
int endIndex = startIndex + g.SettingsPager.PageSize;
int kluczpomocny = 0;
for (int i = startIndex; i < endIndex; i++)
{
string klucz = g.GetRowValues(i, "SymKar") + "|" + g.GetRowValues(i, "LogoP") + "|" + g.GetRowValues(i, "JM") + "|" + g.GetRowValues(i, "SymWL");
dict[kluczpomocny] = klucz + "<|>" + g.GetRowValues(i, "LogoP") + "<|>" + g.GetRowValues(i, "JM") + "<|>" + g.GetRowValues(i, "SymWL") + "<|>" + g.GetRowValues(i, "CenaNetto")+"<|>"+ g.GetRowValues(i, "SymKar");
kluczpomocny++;
}
e.Properties["cpData"]=dict;
};
}).BindToCustomData(Model).GetHtml()
official reply from DevExpress:
"Thank you for the sample project and database backup. I was able to reproduce both issues on my side. I also analyzed how your data layer works when this behavior is reproducible and now I see what causes the issue: you are placing an IQueriable model instance in a static field which is shared among different requests.
As far as I understand, you used the code for the helper class from our Custom Data Binding (Advanced) demo. In this demo, the data source can't be different: a query is always executed on the non-parameterized Emails data set. That's why we put it in a static property.
In your case, the static Model property will not work correctly for multiple concurrent requests. On each request, you are changing an IQueriable instance to a user-specific parameterized query. Due to the fact that an IQueriable instance uses the lazy-loading feature, a query is only executed when the ToList method is invoked (it is done internally in the GridView extension code). That's why you may encounter a situation when the following scenario occurs: you set a model for Grid1 and start building a database query in the GetDataAdvanced method, but at that time, Grid2 set its own model. Thus, substituting the model (the parameterized query to a stored procedure) of the first SQL query built by Grid1.
To fix this issue, I suggest that you make the GridViewCustomBindingHandlers class non-static and create an instance of this class for each controller. This will resolve the issue with the same data for two different users. Make sure that the 'MultipleActiveResultSets' parameter in the connection string is set to 'True'. I demonstrated the implementation of this approach in the updated sample project in the attachment.
Regarding the code in our demo: I described why we implemented it in this way above. However, our implementation in the demo made you implement your own data layer incorrectly. As we try to show the best practices in our demos, the fact that our implementation caused confusion did not go unnoticed. I passed the information regarding your scenario to the team for discussion. This will help us implement better demos/examples in the future or update the existing ones."
I have a patial view with following code(with custom data binding):
Partial View
#{
Html.EnableClientValidation();
Html.EnableUnobtrusiveJavaScript();
var grid = Html.DevExpress().GridView(settings => {
settings.Name = "GridView1";
settings.KeyFieldName = "StudentId";
settings.CallbackRouteValues = new { Controller = "CustomBinding", Action = "MyGridViewPartial" };
settings.CustomActionRouteValues = new { Controller = "Editing", Action = "ChangeEditModePartial" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialAddNew" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialUpdate" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialDelete" };
settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;
settings.SettingsBehavior.ConfirmDelete = true;
settings.SettingsPopup.EditForm.Width = 600;
settings.CommandColumn.Visible = true;
settings.CommandColumn.ShowNewButton = true;
settings.CommandColumn.ShowDeleteButton = true;
settings.CommandColumn.ShowEditButton = true;
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Paging,
new { Controller = "MyController", Action = "MyPagingAction" }
);
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Sorting,
new { Controller = "MyController", Action = "MySortingAction" }
);
settings.SettingsAdaptivity.AdaptivityMode = GridViewAdaptivityMode.Off;
settings.SettingsAdaptivity.AdaptiveColumnPosition = GridViewAdaptiveColumnPosition.Left;
settings.SettingsAdaptivity.AdaptiveDetailColumnCount = 1;
settings.SettingsAdaptivity.AllowOnlyOneAdaptiveDetailExpanded = false;
settings.SettingsAdaptivity.HideDataCellsAtWindowInnerWidth = 0;
settings.Columns.Add("StudentId");
settings.Columns.Add("StudentName");
settings.Columns.Add("StudentAge");
settings.Columns.Add("StudentGrade");
settings.Columns.Add("StudentAddress");
settings.PreRender = (sender, e) =>
{
((MVCxGridView)sender).StartEdit(0);/**//This is the Exception line**
};
settings.CellEditorInitialize = (s, e) =>
{
ASPxEdit editor = (ASPxEdit)e.Editor;
editor.ValidationSettings.Display = Display.Dynamic;
};
});
if (ViewData["EditError"] != null){
grid.SetEditErrorText((string)ViewData["EditError"]);
}
}
#grid.BindToCustomData(Model).GetHtml()///Custom binding
Please suggest the solutions:
Exception:
A primary key field specified via the KeyFieldName property is not found in the underlying data source. Make sure the field name is spelled correctly. Pay attention to the character case.
Are you sure that the Model contains (StudentId) property and you retrieve it from db successfully and also it is public with getter and setter
I have an entry field at the bottom of the screen in one of my projects. However, on iOS, when you click the entry field, the keyboard is displayed over top the entry field and obscures the vision of it. Therefore, people can't see what they're typing.
How can I solve this problem? Is there a way that I can move the entry field so it is displayed above the keyboard when in focus?
//NOTE: the entry field that needs to be moved is userEntry
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using CloudClubv1._2_;
using Backend;
using Xamarin.Forms;
using System.Collections.ObjectModel;
namespace FrontEnd
{
public class ClubChatPage : ContentPage
{
public static ObservableCollection<FrontComment> CurrentCommentsList;
ObservableCollection<FrontComment> commentsList;
ColorHandler ch;
Entry userEntry;
ParentFrontClub club;
bool isMember;
Image bBack, bSettings;
public static ListView listView;
TapGestureRecognizer settingsTgr, backButtonTgr;
public ClubChatPage(ParentFrontClub club, List<DBItem> chatList, List<Account> commentUsers, List<Account> requestUsersList, bool isMember)
{
this.isMember = isMember;
settingsTgr = new TapGestureRecognizer();
settingsTgr.Tapped += SettingsTgr_Tapped;
backButtonTgr = new TapGestureRecognizer();
backButtonTgr.Tapped += BackButtonTgr_Tapped;
this.club = club;
ch = new ColorHandler();
this.BackgroundColor = Color.Black;
this.Title = club.Title;
NavigationPage.SetHasNavigationBar(this, false);
this.commentsList = new ObservableCollection<FrontComment>();
int clubRequestCount = 0;
System.Diagnostics.Debug.WriteLine(chatList.Count.ToString());
chatList.Reverse();
for (int i = 0; i < chatList.Count; i++)
{
if (chatList[i].GetType() == typeof(Comment))
{
if (commentUsers[i] != null)
{
this.commentsList.Add(new FrontComment((Comment)chatList[i], commentUsers[i - clubRequestCount]));
}
}
else if (chatList[i].GetType() == typeof(ClubRequest))
{
this.commentsList.Add(new FrontComment((ClubRequest)chatList[i], requestUsersList[clubRequestCount], this.isMember));
clubRequestCount++;
}
}
CurrentCommentsList = this.commentsList;
updatePage();
}
private void updatePage()
{
bBack = new Image
{
Source = FileImageSource.FromFile("arrow_back.png"),
WidthRequest=30,
// Scale = ,
HorizontalOptions = LayoutOptions.StartAndExpand,
VerticalOptions = LayoutOptions.Center,
HeightRequest = 30,
Aspect = Aspect.AspectFill
};
bBack.GestureRecognizers.Add(backButtonTgr);
var actionBarLabel = new Label
{
Text = this.club.Title,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Center,
TextColor = ch.fromStringToColor("white"),
FontSize = 22,
FontAttributes = FontAttributes.Bold
};
bSettings = new Image
{
Source = ImageSource.FromFile("settings.png"),
Scale = .8,
HorizontalOptions = LayoutOptions.EndAndExpand,
VerticalOptions = LayoutOptions.Center
};
bSettings.GestureRecognizers.Add(settingsTgr);
var actionBarLayout = new StackLayout
{
Children =
{
bBack,
actionBarLabel,
bSettings
},
HeightRequest= 30,
Orientation = StackOrientation.Horizontal,
BackgroundColor = ch.fromStringToColor(this.club.clubColor),
VerticalOptions = LayoutOptions.Center,
Padding = new Thickness(10,10,0,10)
};
listView = new ListView
{
ItemsSource = CurrentCommentsList,
ItemTemplate = new DataTemplate(typeof(CommentViewCell)),
HasUnevenRows = true,
SeparatorVisibility = SeparatorVisibility.None,
SeparatorColor = ch.fromStringToColor("white"),
BackgroundColor = ch.fromStringToColor("white")
};
if (CurrentCommentsList.Count != 0) {
listView.ScrollTo (CurrentCommentsList [CurrentCommentsList.Count () - 1], ScrollToPosition.End, false);
}
listView.ItemTapped += ListView_ItemTapped;
MessagingCenter.Subscribe<CommentViewCell, FrontComment>(this, "hi", async (sender, args) =>
{
var comment = (FrontComment)args;
var answer = await DisplayAlert("Report User", "Do you really want to report " + comment.AuthorUsername + "?", "Yes", "No");
if (answer)
{
await App.dbWrapper.CreateBan(comment.AuthorId, comment.Id, App.dbWrapper.GetUser().Id);
comment.ShowReport = false;
comment.UpdateProperty("ShowReport");
}
else
{
}
//updatePage();
});
userEntry = new Entry
{
BackgroundColor = ch.fromStringToColor("white"),
TextColor = ch.fromStringToColor("black"),
VerticalOptions = LayoutOptions.End,
IsEnabled = isMember,
Placeholder = "Tap to chat"
};
userEntry.Completed += UserEntry_Completed;
userEntry.Focused += UserEntry_Focused;
Label lEmptyChat = new Label
{
Text = "There are no messages. Type below!",
FontSize = 38,
TextColor = ch.fromStringToColor("black"),
XAlign = TextAlignment.Center,
YAlign = TextAlignment.Center,
VerticalOptions = LayoutOptions.FillAndExpand
};
if (CurrentCommentsList.Count != 0)
{
Content = new StackLayout
{
Children =
{
actionBarLayout,
listView,
userEntry
},
BackgroundColor = ch.fromStringToColor("lightGray"),
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
}
else
{
Content = new StackLayout
{
Children =
{
actionBarLayout,
lEmptyChat,
userEntry
},
BackgroundColor = ch.fromStringToColor("lightGray"),
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
}
}
private void UserEntry_Focused(object sender, FocusEventArgs e)
{
}
private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
var item = (FrontComment)e.Item;
for(int i = 0; i < CurrentCommentsList.Count; i++)
{
if (CurrentCommentsList[i].ShowReport==true)
{
CurrentCommentsList[i].ShowReport = false;
CurrentCommentsList[i].UpdateProperty("ShowReport");
}
}
for (int i = 0; i < CurrentCommentsList.Count; i++)
{
if (CurrentCommentsList[i].Id == item.Id && CurrentCommentsList[i].ClubRequestBool == false)
{
CurrentCommentsList[i].ShowReport = true;
CurrentCommentsList[i].UpdateProperty("ShowReport");
}
}
// updatePage();
}
private async void UserEntry_Completed(object sender, EventArgs e)
{
if (userEntry.Text != "")
{
// var joinClub = await App.dbWrapper.JoinClub(club.Id);
var commentOutput = await App.dbWrapper.CreateComment(userEntry.Text, club.Id);
//System.Diagnostics.Debug.WriteLine("OUTPUT: "+joinClub);
userEntry.Text = "";
listView.ScrollTo(CurrentCommentsList[CurrentCommentsList.Count() - 1], ScrollToPosition.End, false);
// updatePage();
}
}
private async void BackButtonTgr_Tapped(object sender, EventArgs e)
{
await App.dbWrapper.RemoveCurrentClubId();
var btn = sender as Image;
btn.IsEnabled = false;
await Navigation.PopAsync();
btn.IsEnabled = true;
}
private async void SettingsTgr_Tapped(object sender, EventArgs e)
{
//var btn = sender as TapGestureRecognizer;
//btn.Tapped -= SettingsTgr_Tapped;
// bSettings.GestureRecognizers.Remove(settingsTgr);
var tagsList = await App.dbWrapper.GetTags(club.Id);
var usersList = await App.dbWrapper.GetClubMembers(club.Id);
var frontClubMemberList = new List<FrontClubMember>();
var isMember = await App.dbWrapper.IsMember(club.Id);
var founderAccount = await App.dbWrapper.GetAccount(club.founderId);
var prevRating = await App.dbWrapper.GetUserRating(club.Id);
var myFriendRequests = await App.dbWrapper.GetFriendRequests();
for (int i = 0; i < usersList.Count; i++)
{
var storedFriendship = await App.dbWrapper.GetFriendship(usersList[i].Id);
if(storedFriendship == 1) //Indicates request was sent from either user
{
// var accReq = App.dbWrapper.GetAccountFriendRequests(usersList[i].Id);
storedFriendship = 3;
var accReq = new List<FriendRequest>();
for (int j = 0; j < myFriendRequests.Count; j++)
{
if (myFriendRequests[j].AuthorId == usersList[i].Id)
{
storedFriendship = 1;//indicates request was sent by other acc
}
}
}
if (usersList[i].Id == App.dbWrapper.GetUser().Id) storedFriendship= 4;
frontClubMemberList.Add(new FrontClubMember(usersList[i], storedFriendship));
}
var btn = sender as Image;
btn.GestureRecognizers.Remove(settingsTgr);
btn.InputTransparent = true;
await Navigation.PushAsync(new ChatInfoPage(tagsList, club, frontClubMemberList, isMember, founderAccount.Username, prevRating));
btn.GestureRecognizers.Add(settingsTgr);
btn.InputTransparent = false;
}
//used by backend push notifications to scroll to new comments
public static void ScrollToCurrent(){
listView.ScrollTo(CurrentCommentsList[CurrentCommentsList.Count() - 1], ScrollToPosition.End, false);
}
}
}
Simply wrap the content in a ScrollView - this will allow the Entry fields to be moved when the Keyboard appears.
I encountered a problem with popup control inside modal edit form of the gridview.
the problem is: popup control won't hide when i click on modal form context area! it just reordered.
please see attached movie first then read the code.
thanks.
here is my code:
MODEL:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public int Avg { get; set; }
}
CONTROLLER:
public class HomeController : Controller
{
public ActionResult Index()
{
Session["Students"] = new List<Student>()
{
new Student { Id = 1, Name = "N1", Family = "f1", Avg = 1 } ,
new Student { Id = 2, Name = "N2", Family = "f2", Avg = 2 } ,
new Student { Id = 3, Name = "N3", Family = "f3", Avg = 3 } ,
new Student { Id = 4, Name = "N4", Family = "f4", Avg = 4 } ,
};
return View(Session["Students"]);
}
public ActionResult PartialGridView(Student student)
{
return PartialView("Index", Session["Students"]);
}
}
View
#model List<Test.Models.Student>
#Html.DevExpress().GridView(settings =>
{
settings.Name = "GvStudent";
settings.KeyFieldName = "Id";
settings.CallbackRouteValues = new { Controller = "Home", Action = "PartialGridView" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "AddStudentPartialGridView" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "UpdateStudentPartialGridView" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "DeleteStudentPartialGridView" };
settings.SettingsEditing.Mode = GridViewEditingMode.PopupEditForm;
settings.SettingsPopup.EditForm.Modal = true;
settings.SettingsPopup.EditForm.HorizontalAlign = PopupHorizontalAlign.WindowCenter;
settings.SettingsPopup.EditForm.VerticalAlign = PopupVerticalAlign.WindowCenter;
settings.SettingsPopup.EditForm.Width = 400;
settings.SettingsPopup.EditForm.Height = 200;
settings.SettingsText.PopupEditFormCaption = "Student";
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
settings.Columns.Add(Name =>
{
Name.FieldName = "Name";
});
settings.Columns.Add(Family =>
{
Family.FieldName = "Family";
});
settings.Columns.Add(Avg =>
{
Avg.FieldName = "Avg";
});
settings.SetEditFormTemplateContent(content =>
{
Html.DevExpress().Button(btnShow =>
{
btnShow.Name="btnShow";
btnShow.ClientSideEvents.Click = "function(s, e){popupControl.ShowAtElement(document.getElementById(s.name));}";
}).Render();
});
}).Bind(Model).GetHtml()
#{
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "popupControl";
settings.CloseAction = CloseAction.OuterMouseClick;
settings.PopupVerticalAlign = PopupVerticalAlign.Below;
settings.PopupHorizontalAlign = PopupHorizontalAlign.LeftSides;
settings.ShowHeader = false;
settings.ShowFooter = false;
settings.AllowDragging = false;
settings.AutoUpdatePosition = true;
settings.Width = 320;
settings.SetContent(() =>
{
ViewContext.Writer.Write("hello world!");
});
}).GetHtml();
}
my code is too long so sorry :)
#model IEnumerable<Osos11.Models.Customers>
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "gvEditing";
settings.KeyFieldName = "sno";
settings.CallbackRouteValues = new { Controller = "Customer", Action = "EditingPartial" };
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Columns.Add(column =>
{
column.Caption = "#";
column.SetDataItemTemplateContent(c =>
{
ViewContext.Writer.Write(
Html.ActionLink("Edit", "EditingEdit", new { sno = DataBinder.Eval(c.DataItem, "sno") }) + " " +
Html.ActionLink("Delete", "EditingDelete", new { sno = DataBinder.Eval(c.DataItem, "sno") },
new { onclick = "return confirm('Do you really want to delete this record?')" })
);
});
column.SetHeaderTemplateContent(c =>
{
ViewContext.Writer.Write(
Html.ActionLink("New", "EditingEdit", new { sno = -1 }).ToHtmlString()
);
});
column.Settings.AllowDragDrop = DefaultBoolean.False;
column.Settings.AllowSort = DefaultBoolean.False;
column.Width = 70;
});
settings.Columns.Add("Name");
//settings.Columns.Add(column =>
//{
// column.FieldName = "CategoryID";
// column.Caption = "Category";
// column.ColumnType = MVCxGridViewColumnType.ComboBox;
// var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
// comboBoxProperties.DataSource = NorthwindDataProvider.GetCategories();
// comboBoxProperties.TextField = "CategoryName";
// comboBoxProperties.ValueField = "CategoryID";
// comboBoxProperties.ValueType = typeof(int);
//});
settings.Columns.Add("CustomerNumber");
//settings.Columns.Add("UnitPrice").PropertiesEdit.DisplayFormatString = "c";
//settings.Columns.Add("UnitsInStock");
//settings.Columns.Add("Discontinued", MVCxGridViewColumnType.CheckBox);
settings.ClientLayout = (s, e) =>
{
if (e.LayoutMode == ClientLayoutMode.Loading)
{
if (Session["GridState"] != null)
e.LayoutData = (string)Session["GridState"];
}
else
Session["GridState"] = e.LayoutData;
};
settings.PreRender = (s, e) =>
{
if (ViewData["VisibleID"] == null) return;
ASPxGridView grid = (ASPxGridView)s;
grid.MakeRowVisible(ViewData["VisibleID"]);
};
}).Bind(Model).GetHtml()
I got this error
Compiler Error Message: CS1660: Cannot convert lambda expression to type 'DevExpress.Web.Mvc.GridViewSettings' because it is not a delegate type
It seems that this issue is caused by the fact that any expression in the GridView's definition is not valid.
As a result, the entire GridView's definition (lambda expression) cannot be recognized by the View Engine.