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.
Related
I'm using MpAndroidChart for my app. I can create piechart successfully but I have a question. I want an event listener to handle item clicked when user touched one of piechart item.How can I do it?
My Code is as below;
>
int[] ydata = { 5, 2, 3, 1 };
string[] xdata= { "one","two","three","four" };
PieChart pieChart;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
pieChart = FindViewById<PieChart>(Resource.Id.chart1);
pieChart.RotationEnabled = true;
pieChart.HoleRadius = 0;
pieChart.SetTransparentCircleAlpha(0);
pieChart.SetCenterTextSize(20);
pieChart.SetDrawEntryLabels(true);
pieChart.SetUsePercentValues(false);
pieChart.AnimateX(1000, Easing.EasingOption.EaseInOutCubic);
pieChart.Description.Text = "test";
addDataSet();
pieChart.SetTouchEnabled(true);
}
private void addDataSet()
{
List<PieEntry> yEntry = new List<PieEntry>();
List<string> xEntry = new List<string>();
for (int i = 0; i < ydata.Length; i++)
{
yEntry.Add(new PieEntry(ydata[i],xdata[i]));
}
for (int i = 0; i < xdata.Length; i++)
{
xEntry.Add(xdata[i]);
}
PieDataSet piedataset = new PieDataSet(yEntry, "test");
piedataset.SliceSpace = 0;
piedataset.ValueTextSize = 20;
int[] colors= { Color.Blue,Color.Red,Color.Green,Color.White};
piedataset.SetColors(colors);
Legend legend = pieChart.Legend;
legend.Form=Legend.LegendForm.Circle;
PieData pieData = new PieData(piedataset);
//pieData.SetValueFormatter(new int);
pieData.SetValueTextColor(Color.White);
pieChart.Data = (pieData);
pieChart.Invalidate();
}
You could use SetOnChartValueSelectedListener to set a ChartValueSelectedListener.
For example, in onCreate():
pieChart.SetOnChartValueSelectedListener(new MyListener(this));
And the listener:
public class MyListener : Java.Lang.Object, IOnChartValueSelectedListenerSupport
{
Context mContext;
public MyListener(Context context) {
this.mContext = context;
}
public void OnNothingSelected()
{
// throw new NotImplementedException();
}
public void OnValueSelected(Entry e, Highlight h)
{
PieEntry pe = (PieEntry)e;
Toast.MakeText(mContext, pe.Label+ " is clicked, value is "+ pe.Value, ToastLength.Short).Show();
}
}
The result is:
I am developing a mvc5 web application. I am trying to store the user's location (Latitude, Longitude) to a database. I can save the location name. But, i can't save latitude and longitude info. How can i insert these?
Thanks for your help.
listing.Cshtml file:
<fieldset>
<legend>[[[Location]]]</legend>
<div class="form-group">
<label>[[[Location]]]</label>
<input type="text" class="form-control input-lg" placeholder="[[[Enter Location]]]" id="Location" name="Location" value="#Model.ListingItem.Location">
</div>
<input type="hidden" id="Longitude" name="Longitude" value="#Model.ListingItem.Longitude" />
<input type="hidden" id="Latitude" name="Latitude" value="#Model.ListingItem.Latitude" />
<div class="form-group">
<div id="map-canvas"></div>
</div>
</fieldset>
listingController:
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> ListingUpdate(Listing listing, FormCollection form, IEnumerable<HttpPostedFileBase> files)
{
if (CacheHelper.Categories.Count == 0)
{
TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
TempData[TempDataKeys.UserMessage] = "[[[There are not categories available yet.]]]";
return RedirectToAction("Listing", new { id = listing.ID });
}
var userIdCurrent = User.Identity.GetUserId();
// Register account if not login
if (!User.Identity.IsAuthenticated)
{
var accountController = BeYourMarket.Core.ContainerManager.GetConfiguredContainer().Resolve<AccountController>();
var modelRegister = new RegisterViewModel()
{
Email = listing.ContactEmail,
Password = form["Password"],
ConfirmPassword = form["ConfirmPassword"],
};
// Parse first and last name
var names = listing.ContactName.Split(' ');
if (names.Length == 1)
{
modelRegister.FirstName = names[0];
}
else if (names.Length == 2)
{
modelRegister.FirstName = names[0];
modelRegister.LastName = names[1];
}
else if (names.Length > 2)
{
modelRegister.FirstName = names[0];
modelRegister.LastName = listing.ContactName.Substring(listing.ContactName.IndexOf(" ") + 1);
}
// Register account
var resultRegister = await accountController.RegisterAccount(modelRegister);
// Add errors
AddErrors(resultRegister);
// Show errors if not succeed
if (!resultRegister.Succeeded)
{
var model = new ListingUpdateModel()
{
ListingItem = listing
};
// Populate model with listing
await PopulateListingUpdateModel(listing, model);
return View("ListingUpdate", model);
}
// update current user id
var user = await UserManager.FindByNameAsync(listing.ContactEmail);
userIdCurrent = user.Id;
}
bool updateCount = false;
int nextPictureOrderId = 0;
// Set default listing type ID
if (listing.ListingTypeID == 0)
{
var listingTypes = CacheHelper.ListingTypes.Where(x => x.CategoryListingTypes.Any(y => y.CategoryID == listing.CategoryID));
if (listingTypes == null)
{
TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
TempData[TempDataKeys.UserMessage] = "[[[There are not listing types available yet.]]]";
return RedirectToAction("Listing", new { id = listing.ID });
}
listing.ListingTypeID = listingTypes.FirstOrDefault().ID;
}
if (listing.ID == 0)
{
listing.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
listing.IP = Request.GetVisitorIP();
listing.Expiration = DateTime.MaxValue.AddDays(-1);
listing.UserID = userIdCurrent;
listing.Enabled = true;
listing.Currency = CacheHelper.Settings.Currency;
updateCount = true;
_listingService.Insert(listing);
}
else
{
if (await NotMeListing(listing.ID))
return new HttpUnauthorizedResult();
var listingExisting = await _listingService.FindAsync(listing.ID);
listingExisting.Title = listing.Title;
listingExisting.Description = listing.Description;
listingExisting.Tags = listing.Tags;
listingExisting.Active = listing.Active;
listingExisting.Price = listing.Price;
listingExisting.ContactEmail = listing.ContactEmail;
listingExisting.ContactName = listing.ContactName;
listingExisting.ContactPhone = listing.ContactPhone;
listingExisting.Latitude = listing.Latitude;
listingExisting.Longitude = listing.Longitude;
listingExisting.Location = listing.Location;
listingExisting.ShowPhone = listing.ShowPhone;
listingExisting.ShowEmail = listing.ShowEmail;
listingExisting.CategoryID = listing.CategoryID;
listingExisting.ListingTypeID = listing.ListingTypeID;
listingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
_listingService.Update(listingExisting);
}
// Delete existing fields on item
var customFieldItemQuery = await _customFieldListingService.Query(x => x.ListingID == listing.ID).SelectAsync();
var customFieldIds = customFieldItemQuery.Select(x => x.ID).ToList();
foreach (var customFieldId in customFieldIds)
{
await _customFieldListingService.DeleteAsync(customFieldId);
}
// Get custom fields
var customFieldCategoryQuery = await _customFieldCategoryService.Query(x => x.CategoryID == listing.CategoryID).Include(x => x.MetaField.ListingMetas).SelectAsync();
var customFieldCategories = customFieldCategoryQuery.ToList();
foreach (var metaCategory in customFieldCategories)
{
var field = metaCategory.MetaField;
var controlType = (BeYourMarket.Model.Enum.Enum_MetaFieldControlType)field.ControlTypeID;
string controlId = string.Format("customfield_{0}_{1}_{2}", metaCategory.ID, metaCategory.CategoryID, metaCategory.FieldID);
var formValue = form[controlId];
if (string.IsNullOrEmpty(formValue))
continue;
formValue = formValue.ToString();
var itemMeta = new ListingMeta()
{
ListingID = listing.ID,
Value = formValue,
FieldID = field.ID,
ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
};
_customFieldListingService.Insert(itemMeta);
}
await _unitOfWorkAsync.SaveChangesAsync();
if (Request.Files.Count > 0)
{
var itemPictureQuery = _listingPictureservice.Queryable().Where(x => x.ListingID == listing.ID);
if (itemPictureQuery.Count() > 0)
nextPictureOrderId = itemPictureQuery.Max(x => x.Ordering);
}
if (files != null && files.Count() > 0)
{
foreach (HttpPostedFileBase file in files)
{
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
// Picture picture and get id
var picture = new Picture();
picture.MimeType = "image/jpeg";
_pictureService.Insert(picture);
await _unitOfWorkAsync.SaveChangesAsync();
// Format is automatically detected though can be changed.
ISupportedImageFormat format = new JpegFormat { Quality = 90 };
Size size = new Size(500, 0);
//https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
// Initialize the ImageFactory using the overload to preserve EXIF metadata.
using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
{
var path = Path.Combine(Server.MapPath("~/images/listing"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg"));
// Load, resize, set the format and quality and save an image.
imageFactory.Load(file.InputStream)
.Resize(size)
.Format(format)
.Save(path);
}
var itemPicture = new ListingPicture();
itemPicture.ListingID = listing.ID;
itemPicture.PictureID = picture.ID;
itemPicture.Ordering = nextPictureOrderId;
_listingPictureservice.Insert(itemPicture);
nextPictureOrderId++;
}
}
}
await _unitOfWorkAsync.SaveChangesAsync();
// Update statistics count
if (updateCount)
{
_sqlDbService.UpdateCategoryItemCount(listing.CategoryID);
_dataCacheService.RemoveCachedItem(CacheKeys.Statistics);
}
TempData[TempDataKeys.UserMessage] = "[[[Listing is updated!]]]";
return RedirectToAction("Listing", new { id = listing.ID });
}
My page screenshot:
enter image description here
Consequently, i can insert location in my db. But, i can't latitude and longitude insert.
How can i solve this problem?
initmap function:
function initMap() {
var isDraggable = $(document).width() > 480 ? true : false; // If document (your website) is wider than 480px, isDraggable = true, else isDraggable = false
var mapOptions = {
draggable: isDraggable,
scrollwheel: false, // Prevent users to start zooming the map when scrolling down the page
zoom: 7,
center: new google.maps.LatLng(39.8688, 32.2195),
};
#{ var hasLatLng = #Model.ListingItem.Latitude.HasValue && #Model.ListingItem.Longitude.HasValue; }
var hasLatLng = #hasLatLng.ToString().ToLowerInvariant();
#if (hasLatLng){
<text>
mapOptions = {
center: new google.maps.LatLng(#Model.ListingItem.Latitude.Value.ToString(System.Globalization.CultureInfo.InvariantCulture), #Model.ListingItem.Longitude.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)),
zoom: 7
};
</text>
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
#if (hasLatLng){
<text>
var marker = new google.maps.Marker({
position: new google.maps.LatLng(#Model.ListingItem.Latitude, #Model.ListingItem.Longitude),
map: map
});
marker.setVisible(true);
</text>
}
geocoder = new google.maps.Geocoder();
var input = (document.getElementById('Location'));
// Try HTML5 geolocation
if (#Model.ListingItem.ID == 0){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
geocoder.geocode({ 'latLng': pos }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(14);
map.setCenter(pos);
marker = new google.maps.Marker({
position: pos,
map: map,
content: results[1].formatted_address
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
$('#Location').val(results[1].formatted_address);
$('#Latitude').val(pos.lat());
$('#Longitude').val(pos.lng());
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// Set lat/long
$('#Latitude').val(place.geometry.location.lat());
$('#Longitude').val(place.geometry.location.lng());
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(12);
}
marker.setIcon(({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
google.maps.event.addDomListener(input, 'keydown', function (e) {
if (e.keyCode == 13) {
if (e.preventDefault) {
e.preventDefault();
}
else {
// Since the google event handler framework does not handle
e.cancelBubble = true;
e.returnValue = false;
}
}
});
}
save button:
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> [[[Save]]]</button>
<i class="fa fa-remove"></i> [[[Cancel]]]
</div>
</div>
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 am working on MVC and it is my first unit test so exucse me if there is stupid i do.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WebApplication2.Controllers;
using System.Web.Mvc;
namespace WebApplication2.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var ctrl = new HomeController();
var res = ctrl.tableData1("AllDevices") as ViewResult;
Assert.AreEqual("tableData1", res.ViewName);
}
}
}
Where HomeController ActionResult() is:
public ActionResult tableData1(string status)
{
List<tableData1> tableDataModel = new List<tableData1>();
tableDataModel.Add(new tableData1()
{
ID="1",
Name = "Shekhar",
Status = "AllVehicles",
Location = "Pilani",
Odometer = "check1",
PS = "BatteryOff",
IG = "PowerOf",
GPS = "GpsOf",
AC = "Off",
Door = "-",
Speed = "152Km/Hr",
Fuel = "14000 Ltrs",
Temp = "52",
State = "Stopped",
Map = "Map click",
Time = "1:00PM",
Lat = "28.3802817",
Long = "75.6070956"
});
if (status != "AllVehicles")
{
for (int i = 0; i < tableDataModel.Count; i++)
{
if (status != tableDataModel[i].Status)
{
tableDataModel.RemoveAt(i);
i--;
}
}
}
else if (status == "AllVehicles")
{
for (int i = 0; i < tableDataModel.Count; i++) { } //useless
}
else
{
return Content("Inside else condition");
}
return View(tableDataModel);
}
When i try to do this i obtain an error like this : http://prntscr.com/7lwe0c
Could some one please let me know why i have this error and how to solve it ?
I'm building an app were i add tablerows to a view programmatically. I add a deletebutton to every row that is an ImageButton. Now i have a few questions.
Can i use an ImageButton for this?
How do i get the tablerow id
where the deletebutton was clicked?
How can i convert the eventargs
from a clickhandler into MenuItemOnMenuItemClickEventArgs or vice
versa?
How should my clickhandler look like?
Here is my sourcecode:
public class CalculatorSide2 : Activity
{
private Button stepButton;
private IntentHelper intentHelper = new IntentHelper();
private string age;
private string estLife;
private string estPens;
private string[] pensions;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
intentHelper.IntentSide2(Intent, out age, out estLife,out estPens);
SetContentView(Resource.Layout.calculatorside2);
TableLayout tl_layout = FindViewById<TableLayout>(Resource.Id.tableLayout1);
ImageView plusButton = FindViewById<ImageView>(Resource.Id.plusButton);
stepButton = FindViewById<Button>(Resource.Id.cside2stepButton);
plusButton.Click += (sender, e) =>
{
PopupMenu popupMenu = new PopupMenu(this, plusButton);
popupMenu.Inflate(Resource.Menu.popupmenu);
fillPopupMenu(popupMenu);
popupMenu.Show();
popupMenu.MenuItemClick += (s1, arg) =>
{
string info = arg.Item.TitleFormatted.ToString();
string id = arg.Item.ItemId.ToString();
var inputDialog = new AlertDialog.Builder(this);
EditText userInput = new EditText(this);
userInput.InputType = (Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);
inputDialog.SetTitle(info);
inputDialog.SetView(userInput);
inputDialog.SetPositiveButton("Ok", (ss, ee) =>
{
TextView rowInfo = new TextView(this);
rowInfo.SetLines(2);
rowInfo.TextSize = 20;
rowInfo.SetTextColor(Android.Graphics.Color.Black);
rowInfo.Text = info + ": \n" + userInput.Text + "€";
ImageButton delete = new ImageButton(this);
delete.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.delete_icon));
TableRow row = new TableRow(this);
row.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
row.SetBackgroundColor(Android.Graphics.Color.Rgb(255, 153, 0));
row.SetPadding(0, 0, 0, 30);
row.AddView(rowInfo);
row.AddView(delete);
tl_layout.AddView(row);
});
inputDialog.SetNegativeButton("Cancel", (se, es) => { });
inputDialog.Show();
};
};
stepButton.Click += (object sender, EventArgs e) =>
{
var step = new Intent(this, typeof(CalculatorSide3));
step.PutExtra("Age", age);
step.PutExtra("EstPens", estPens);
step.PutExtra("EstLife", estLife);
step.PutStringArrayListExtra("Pensions", pensions);
StartActivity(step);
};
}
private void fillPopupMenu(PopupMenu menu)
{
int groupId = 0;
int i = 0;
int menuItemId = Android.Views.Menu.First;
int menuItemOrder = Android.Views.Menu.None;
foreach (var item in Enum.GetNames(typeof(PopupMenuItems)))
{
string itemString = item.ToString();
menu.Menu.Add(groupId, menuItemId + i, menuItemOrder + i, itemString.Replace("_", " "));
i++;
}
}
}
I hope someone understands what i mean, bc english is not my native language.
public class CalculatorSide2 : Activity
{
private Button stepButton;
private IntentHelper intentHelper = new IntentHelper();
private string age;
private string estLife;
private string estPens;
private string[] pensions;
private Dictionary<int,string> temp;
private TableLayout tl_layout;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
intentHelper.IntentSide2(Intent, out age, out estLife,out estPens);
SetContentView(Resource.Layout.calculatorside2);
tl_layout = FindViewById<TableLayout>(Resource.Id.tableLayout1);
ImageView plusButton = FindViewById<ImageView>(Resource.Id.plusButton);
stepButton = FindViewById<Button>(Resource.Id.cside2stepButton);
temp = new Dictionary<int,string>();
int i = 0;
plusButton.Click += (sender, e) =>
{
PopupMenu popupMenu = new PopupMenu(this, plusButton);
popupMenu.Inflate(Resource.Menu.popupmenu);
fillPopupMenu(popupMenu);
popupMenu.Show();
popupMenu.MenuItemClick += (s1, arg) =>
{
string info = arg.Item.TitleFormatted.ToString();
string id = arg.Item.ItemId.ToString();
var inputDialog = new AlertDialog.Builder(this);
EditText userInput = new EditText(this);
userInput.InputType = (Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);
inputDialog.SetTitle(info);
inputDialog.SetView(userInput);
inputDialog.SetPositiveButton("Ok", (ss, ee) =>
{
TextView rowInfo = new TextView(this);
rowInfo.SetLines(2);
rowInfo.TextSize = 20;
rowInfo.SetTextColor(Android.Graphics.Color.Black);
rowInfo.Text = info + ": \n" + userInput.Text + "€";
ImageButton delete = new ImageButton(this);
delete.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.delete_icon));
delete.Focusable = false;
delete.Clickable = false;
TableRow row = new TableRow(this);
row.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
row.SetBackgroundColor(Android.Graphics.Color.Rgb(255, 153, 0));
row.SetPadding(0, 0, 0, 30);
row.Id = 10 + i;
row.Click += new EventHandler(HandleClick);
row.AddView(rowInfo);
row.AddView(delete);
tl_layout.AddView(row);
temp.Add(row.Id,userInput.Text);
i++;
});
inputDialog.SetNegativeButton("Cancel", (se, es) => { });
inputDialog.Show();
};
};
stepButton.Click += (object sender, EventArgs e) =>
{
if (temp.Count != 0)
{
pensions = new string[temp.Count];
var j = 0;
foreach (KeyValuePair<int, string> pair in temp)
{
pensions[j] = pair.Value;
j++;
}
}
else
{
pensions = new string[0];
}
var step = new Intent(this, typeof(CalculatorSide3));
step.PutExtra("Age", age);
step.PutExtra("EstPens", estPens);
step.PutExtra("EstLife", estLife);
step.PutStringArrayListExtra("Pensions", pensions);
StartActivity(step);
};
}
private void fillPopupMenu(PopupMenu menu)
{
int groupId = 0;
int i = 0;
int menuItemId = Android.Views.Menu.First;
int menuItemOrder = Android.Views.Menu.None;
foreach (var item in Enum.GetNames(typeof(PopupMenuItems)))
{
string itemString = item.ToString();
menu.Menu.Add(groupId, menuItemId + i, menuItemOrder + i, itemString.Replace("_", " "));
i++;
}
}
public void HandleClick(object sender, EventArgs e)
{
var clickedTR = sender as TableRow;
int trId = clickedTR.Id;
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Löschen");
builder.SetMessage("Möchten Sie den Eintrag wirklich löschen?");
builder.SetPositiveButton("Ja", (ssr,args) => {
temp.Remove(trId);
tl_layout.RemoveView(clickedTR);
});
builder.SetNegativeButton("Nein",(sse,arge) => { });
builder.SetCancelable(false);
builder.Show();
}
}