RadComboBox Binding Selected Value - c#

I have a radcombobox and I'm trying to bind the selected value to data I'm pulling back from a table in my database.
<telerik:RadComboBox ID="cboRole" runat="server" DataValueField="UserType.ID" DataTextField="UserType.Value" Text='<%# Bind("UserType") %>' DataSourceID="odsCertifications" >
</telerik:RadComboBox>
Here is my data
public partial class Certification
{
public Certification()
{
this.Courses = new HashSet<CertificationCourse>();
}
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Duration { get; set; }
public Nullable<System.DateTime> Expiration { get; set; }
public bool IsActive { get; set; }
public string CreatedBy { get; set; }
public System.DateTime CreatedOn { get; set; }
public string UpdatedBy { get; set; }
public Nullable<System.DateTime> UpdatedOn { get; set; }
public Nullable<int> UserTypeID { get; set; }
public virtual ICollection<CertificationCourse> Courses { get; set; }
public virtual SystemCode UserType { get; set; }
}
The UserType has the attributes Value and ID upon which I'm trying to bind the DataTextFields and DataValueFields. However, I'm getting javascript exceptions when trying to bind this way. The javascript message if omitted so I can't fully see what the exact error message is.
Here is what the chrome js debugger is telling me is happening:
Uncaught Sys.WebForms.PageRequestManagerServerErrorException:
Sys.WebForms.PageRequestManagerServerErrorException: Object of type
System.Data.Entity.DynamicProxies.Certification_D985D293565CB0BFD87FA8F8F44D70ACF4130D6E138A82D6E486544C53D7FE10 does ...<omitted>...y.
<asp:ObjectDataSource runat="server" ID="odsCertifications" SelectMethod="GetActiveCertifications" TypeName="SitefinityWebApp.Controllers.CertificationController"></asp:ObjectDataSource>
public List<Certification> GetActiveCertifications()
{
using (var db = new Entities())
{
try
{
return db.Certifications.Include("UserType").Where(x => x.IsActive == true).OrderBy(x => x.Title).ToList();
}
catch (Exception ex)
{
ExceptionManager.LogException(this, ex);
return null;
}
}
}

I don't have any knowledge in the RAD version of Telerik, but I think the problem comes from the fact that you are trying to bind a SystemCode object to the ComboBox, and it can only probably handles simple types like int / string.
I guess you should be binding with the UserTypeID instead, but I'm not sure it would work because it's Nullable.

What would you like to do exactly? I guess "odsCertifications" is not a list. So if you would like to show only binded user type value which is in certification object. You don't need to bind any source to combobox. Just add list item to combobox in cs. side like:
cbcRole.Items.Add(new RadComboboxItem(){Value=odsCertifications.UserType.ID, Text=odsCertifications.UserType.Value}) //RadComboboxItem and properties can be different I wrote only as example.
If you would like to populate your combobox with all user types and show binded user type value which is in certification object as selected item, You have to bind UserType list object to your combobox like:
<telerik:RadComboBox ID="cboRole" runat="server" DataValueField="ID" DataTextField="Value" DataSourceID="userTypes" ></telerik:RadComboBox>
DataSourceID="userTypes" here, userTypes is must be List object like
List<UserType> userTypes;
Than you can set selected item in cs. side like:
cboRole.SelectedValue=odsCertifications.UserType.ID;

To get the actual server exception, remove AJAX. What you get is a server exception captured by MS AJAX during a partial postback and send (truncated) to the client as a JavaScript error.
I also think you may need to expose the string property you need as a direct field, not as a sub-field of the field you pass to the combo's property

Related

Correct way of binding xamarin forms picker value

My issue is that I have 2 picker controls. 1 of these picker controls is bound to list a and one of these picker controls is bound to list b. Both of these controls display the data I need them to with the correct display bindings working fine.
My problem is when I bind the selectedItem property, it works for list a but doesn't for list b. I've checked that the code is literally a like for like copy of each other.
I have been using the syncfusion Combobox but switched to the picker as I thought there was an issue here but there isn't. Whatever is happening is totally down to whatever I'm doing.
The usage scenario is that I bring down a list of payment types from my API and populate a picker based on this. This works.
The datasource for my main view contains an ID. When I am modifying a record, I run a method called update to find the selectedItem. I'm not happy with this approach and would be interested to see what other people use.
The update method gets the datasources for the pickers and finds what I would expect to be the selected item. This works fine also but doesn't bind.
[Serializable]
public class PaymentInformation :BaseModel
{
public int? ID { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public int? PaymentTypeId { get; set; }
public string PaymentTo { get; set; }
public string Location { get; set; }
public string Notes { get; set; }
public PersonInformation PersonBudget { get; set; }
public decimal AmountPaid { get; set; }
public decimal AmountReceived { get; set; }
public double TotalHours { get; set; }
public void Update(ObservableCollection<ResourceInformation> resources , ObservableCollection<PaymentTypeInformation> paymentTypes)
{
if(PaymentTypeId != null) this.PaymentTypeInformation1 = paymentTypes?.FirstOrDefault((paymentType) => paymentType.ID == PaymentTypeId.Value);
this.Resource = resources?.FirstOrDefault((resource) => resource.ResourceId == PersonBudget?.ID);
}
private PaymentTypeInformation _paymentTypeInformation;
private PaymentTypeInformation PaymentTypeInformation1 { get { return _paymentTypeInformation; } set { _paymentTypeInformation = value; OnPropertyChanged(nameof(PaymentTypeInformation1)); } }
private ResourceInformation _resource;
public ResourceInformation Resource { get { return _resource; } set { _resource = value; OnPropertyChanged(nameof(Resource)); } }
}
The underlying xaml is:
<Label Grid.Row="8" Grid.Column="0" Text="Payment Type:" />
<Picker BackgroundColor="White" Grid.Row="8" Grid.Column="1" ItemsSource="{Binding PaymentTypesDataSource}" ItemDisplayBinding="{Binding Path=DisplayText}" IsEnabled="{Binding IsProcessing, Converter={StaticResource reverseBoolConvertor}}" SelectedItem="{Binding DataSource.PaymentTypeInformation1, Mode=TwoWay}" />
The expected result is that the drop down initializes with the selectedItem which it doesn't (in one usage scenario - the other one works fine).
Couldn't see the wood for the trees.
private PaymentTypeInformation PaymentTypeInformation1
{
get
{
return _paymentTypeInformation;
}
set
{
_paymentTypeInformation = value;
OnPropertyChanged(nameof(PaymentTypeInformation1));
}
}
Can't bind to a private property - changed to public and immediately work. Stuck on this for a day as bonkers as that is to believe.

How to show selected item in Syncfusion DropDownList control

I am working on an ASP.NET MVC application using Syncfusion controls. I have a drop down list in my view. The model has a property "Categories" which is a List of type Category.
public class Category
{
public int XKategorieId { get; set; }
public int? Id { get; set; }
public string Hinweis { get; set; }
public string Kategorie { get; set; }
}
The model of the view also has a property "IdFromCategory". The model is:
public class ReportModel
{
public int? IdFromCategory { get; set; }
public List<Category> Categories { get; set; }
}
I am showing all the categories in the drop down list by setting the "DataSource" of "DropDownList". Now, my issue is that i want to show an item selected in the "DropDownList" when the view loads and that selected item will be the one with "Id" equals to "IdFromCategory ".
#Html.EJS().DropDownList("KundenBetreuung").DataSource(Model.Categories).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Text = "Kategorie", Value = "Id" }).Value(Model.IdFromCategory.ToString()).Width("100%").Render();
This is my code, i am unable to set the selected item in the "DropDownList"
In the Razor code, you have filled the value property with Model.IdFromCategory.ToString() (a string) where the declared properties IdFromCategory and Id both are integers. This mismatching type is the cause of the issue in your end and the value is not being set. To successfully set the value make sure that the value provided is available in the datasource and its type matches as well.
Suggest changing the code as follows
#Html.EJS().DropDownList("KundenBetreuung").DataSource(Model.Categories).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Text = "Kategorie", Value = "Id" }).Value(Model.IdFromCategory).Width("100%").Render();
Check the following example for further reference
Example

Is it possible to pass a value from click event to a ListView SelectMethod?

I have a third party Calendar control, named Day Pilot Calendar, which have an EventClickHandling event, this does a postback when I click on an event in the calendar. When I click on an Event, I would like to display details about that event in a listview, among other things. The details of the event (ID,name, start/end date) are stored in a database table. For every event there is one or two School subjects (like math test, english exam) which is stored in another table. What I'm trying to achieve is, when I click on an event, I get the EventID and want to pass it to a ListView, where I can compare to the SubjectIDs in the Subjects table to get every detail displayed about the subject too. My problem is, I don't know how to pass a value from the EventClick method to the listview SelectMethod or even if it possible.
I have managed to do this with a dropdownlist this way:
public IQueryable<Subject> GetEventDetails([Control] int ddlEvents)
{
var _db = new School.Models.SchoolContext();
IQueryable<Subject> query = _db.Subjects;
query = query.Where(p => p.SubjectID == ddlEvents);
return query;
}
Is it possible to do something like this but with a value from a click event?
Edit: I was asked to clear up some things and add more details:
I have the Event class:
public int EventID { get; set; }
public string EventName { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string Notes { get; set; }
public int Subject Subject {get; set;}
and I have the Subject class:
public int SubjectID { get; set; }
public string SubjectName { get; set; }
public string SubjectRoom { get; set; }
public ICollection<Event> Events { get; set; }
This is how the DayPilotCalendar EventClick method looks like without any specific code :
protected void DayPilotCalendar1_EventClick(object sender, DayPilot.Web.Ui.Events.EventClickEventArgs e)
{
<code here>
}
This is something I'd imagined, but it is completely wrong and may be stupid:
public IQueryable<Subject> GetEventDetails([Control] int ValueFromClickEvent)
{
var _db = new School.Models.SchoolContext();
IQueryable<Subjects> query = _db.Subjects;
query = query.Where(p => p.SubjectID == ValueFromClickEvent);
return query;
}
Implementation of the calendar:
<DayPilot:DayPilotCalendar ID="DayPilotCalendar1" runat="server" SelectMethod="GetEvents" DataEndField="EndDate" DataStartField="StartDate" DataTextField="EventName" DataValueField="EventID" Days="7" TimeFormat="Clock24Hours" EventClickHandling="PostBack" OnEventClick="DayPilotCalendar1_EventClick" StartDate="2018-05-30" />
Populate the calendar:
public IQueryable<Event> GetEvents()
{
var _db = new School.Models.SchoolContext();
IQueryable<Event> query = _db.Events;
return query;
}

Set Dropdownlist Selected Value in the View

I need to set the setectedValue of a DropDownList using razor, but because it's a list used several times in the same page, I can't set the selected value in the Controller, so how can I set it in the View?
Actual Controller List code:
ViewBag.CargaTipos = new SelectList(db.CargaTipos, "Id", "Nome").OrderBy(c => c.Text);
Actual View:
#Html.DropDownListFor(modelItem => item.CargaTipo.Id, (IEnumerable<SelectListItem>)ViewBag.CargaTipos)
Models:
[Table("Cargas")]
public class Carga
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[ForeignKey("CargaTipo")]
public int CargaTipo_Id { get; set; }
[Display(Name = "Tipo de Carga")]
public virtual CargaTipo CargaTipo { get; set; }
}
[Table("CargaTipos")]
public partial class CargaTipo
{
public CargaTipo()
{
this.Cargas = new HashSet<Carga>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Nome { get; set; }
public virtual ICollection<Carga> Cargas { get; set; }
}
Cannot set SelectedValue property outside constructor of SelectedList class. Use this instead
ViewBag.CargaTipos = db.CargaTipos;
View
#Html.DropDownListFor(modelItem => item.CargaTipo.Id,new SelectList(ViewBag.CargaTipos,"Id","Nome",YOUR_SELECTED_VALUE))
I suggest you to do it with some JQuery code(you can also use JavaScript depending of you), but I advice JQuery. So you will need to reference link of JQuery lib in your Layout
<script>
$(document).ready(function ()
{
$("idOfyourDropDownList option[value=Id]').attr('selected','selected');
})
</script>
I think when you put this script on your solution, by default you will have item selected by default.
I hope it will help
You can try to use documented behavior of Html.DropDownListFor<> like this:
#Html.DropDownListFor(modelItem => modelItem.CargaTipo_Id,
(IEnumerable<SelectListItem>)ViewBag.CargaTipos)
Pay attention on using declared variable in expression. In your case it is modelItem.
And you have to use CargaTipo_Id from main model, not Id from referened model.

How to databind to a label with a custom object collection in C# winforms

I'm using a VB power packs data repeater control. I need to bind a list of custom objects to labels inside the repeater. The following code works except for the Tip.User.UserName binding.
How can I bind to a property of an Inner class like Tip.User.UserName
public interface ITip
{
DateTime Date { get; set; }
int Id { get; set; }
int UserId { get; set; }
User User { get; set; }
Group Group { get; set; }
}
public interface IUser
{
string DisplayName { get; set; }
string UserName { get; set; }
}
List<Tip> currentTips = SearchTips(toolTxtSearch.Text, Convert.ToInt32(toolCmbTipGroups.ComboBox.SelectedValue));
lblTipId.DataBindings.Add(new Binding("Text", currentTips, "Id"));
lblTipUser.DataBindings.Add(new Binding("Text", currentTips, "User.UserName")); // this line doesnot work !!!
repeater.DataSource = currentTips;
Totally depends on what error you're getting because nested property syntax should work for WinForm bindings.
As a work around (maybe the DataRepeater isn't using regular binding mechanisms?) add a property to you ITip implementation to wrap it up:
public string UsersUserName
{
get { return User != null ? User.UserName : null; }
}
Edit: Also don't forget to implement INotifyPropertyChanged on your data objects if you want bindings to update when values do. In this case, send property changed events for both the User property of ITip implementations and the UserName of the IUser implementation.

Categories