SelectedValue of a new item in Combobox - ajax

I have been using the Ajax Combo box and I bind it from database, and all works fine. Later I used the selected value to get the results using Linq.
But whenever I add a new item in the same, that is combo box, I get the selected text as the selected value, so in that case it creates an exception.
What can be the better way of getting the selected value of the new item so that I can just by pass the exception.
Should I give it a temporary Id?
How to do that?
Cmbx.DataSource = ScmsFeeBLObj.Mthod();
Cmbx.DataTextField = "Text";
Cmbx.DataValueField = "Id";
Cmbx.DataBind();
protected void Cmbx_SelectedIndexChanged(object sender, EventArgs e)
{
String Id = Cmbx.SelectedValue.ToString();
obj = ScmsFeeBLObj.FillData(Id);
}
Back Code (In DAL):
public ELClass FillData(String Id)
{
Int32 ID= Convert.ToInt32(Id);
var q = (from schedules in context.FeeSchedules
where schedules .ScheduleId == ID
select schedules );
return q.SingleOrDefault();
}

Related

Dynamically generated columns in radgrid disappear after postback

Am using radgrid and creating it in aspx but on certain action i add more GridTemplateColumns to the grid.
private void CreateDateColumns(List<DateTime> occurenceList)
{
if (occurenceList != null && occurenceList.Count > 0)
{
int index = 1;
foreach (DateTime occurence in occurenceList)
{
string templateColumnName = occurence.Date.ToShortDateString();
GridTemplateColumn templateColumn = new GridTemplateColumn();
templateColumn.ItemTemplate = new MyTemplate(templateColumnName, index);
grdStudentAttendanceList.MasterTableView.Columns.Add(templateColumn);
templateColumn.HeaderText = templateColumnName;
templateColumn.UniqueName = templateColumnName;
index++;
}
}
}
private class MyTemplate : ITemplate
{
protected RadComboBox rcbAttendance;
private string colname;
private int _index;
public MyTemplate(string cName, int index)
{
colname = cName;
_index = index;
}
public void InstantiateIn(System.Web.UI.Control container)
{
rcbAttendance = new RadComboBox();
rcbAttendance.Items.Add(new RadComboBoxItem("---Select---", "-1"));
rcbAttendance.Items.Add(new RadComboBoxItem("Present", "1"));
rcbAttendance.Items.Add(new RadComboBoxItem("Absent", "2"));
rcbAttendance.Items.Add(new RadComboBoxItem("Leave", "3"));
rcbAttendance.ID = "rcbAttendance" + _index;
container.Controls.Add(rcbAttendance);
}
}
All are fine with creation but when i press save button or any combobox make postback the only dynamically generated columns content disappear and the other columns stay.
What i noticed that columns still in place with headertext but only content are disappeared (in my case content are comboboxes)
After enabling viewstate for grid only header text appear.
What should i do to keep columns contents after postback and get their values ?
When creating template columns programmatically, the grid must be generated completely in the code-behind using the Page_Init event. Then, you must create the templates dynamically in the code-behind and assign them to the ItemTemplate and EditItemTemplate properties of the column. To create a template dynamically, you must define a custom class that implements the ITemplate interface. Then you can assign an instance of this class to the ItemTemplate or EditTemplateTemplate property of the GridTemplateColumn object.
Blockquote
Column templates must be added in the Page_Init event handler, so that the template controls can be added to the ViewState.
Blockquote
Source: Telerik
Basicly, you need to create all GridTemplateColumns in the Page_Init. We had the same problem and this approach fixed it.

ObjectStateEntry GetModifiedProperties() incorrectly detects change to byte[] property

Does Entity Framework incorrectly detect changes to images?
I have a "Person" entity class defined as follows;
public class Person
{
public int Id { get; set; }
public byte[] Photo { get; set; }
}
I have bound the Photo to a PictureBox control on my form using a datasource.
There form also uses a dynamically created bindingNavigator.
I also have written an audit log to populate captured changes
The procedure calls the ObjectContext DetectChanges() and then
var entries = ObjectContext.ObjectStateManager.GetObjectStateEntries()
Which contains an entry showing that the Photo has been modified.
entry.OriginalValues[name] matches entry.CurrentValues[name]
The Column is varbinary(MAX) in SQL Server and the size of the picture files I have loaded are under 1Mb
If I set all of the columns to null the error no longer occurs
The code I use to get the file is
private void LoadPhotoButton_Click(object sender, EventArgs e)
{
using (var dlg = new OpenFileDialog())
{
dlg.Filter = "JPEG files |*.jpg";
if (dlg.ShowDialog() == DialogResult.OK)
{
PhotoPictureBox.Image = Image.FromFile(dlg.FileName);
}
}
}
I note here that hex zero can be inserted as padding characters when these fields are involved in string conversion.... could the binding be doing that somehow?
If I delete the picturebox from the form, or even bind the control as a text box instead of a picturebox then the behaviour is correct ( not that a picture bound to a text box is any use )
I am able to work around the problem by not binding directly to the picture box.
Instead I just load it on the BindingSource_CurrentChanged event using
private void BindingSource_CurrentChanged(object sender, EventArgs e)
{
var obj = (Person) BindingSource.Current;
this.PictureBox.Image = byteArrayToImage( obj.Photo);
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
I am using my work around - documented at the end of the question as a make do answer.

Windows Phone 7 Listbox selection data binding

I'm using this tutorial as a base for my first app. I'm trying to select a listbox item and view data from said item, but(my Android and iOS brain is having issues with this), how do I view the data binding behind that?
lstContact.ItemsSource = from contact in xmlContact.Descendants("contact")
select new ContactItem
{
ImageSource = contact.Element("Image").Value,
FName = contact.Element("FName").Value,
LName = contact.Element("LName").Value
Extension = contact.Element("Extension").Value,
Email = contact.Element("Email").Value,
ID = contact.Element("ID").Value
};
This is how I'm setting it up my data source, and it's pulling correctly. How would I go about going in and getting the email or extension from said listbox item?
In your example, lstContact.ItemsSource is effectively now a IEnumerable<ContactItem>. Assuming you want a 'selected' item, in your SelectionChanged event:
public void ListBoxContainerSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstContact.SelectedIndex == -1) return;
ContactItem contactItem = (ContactItem)lstContact.SelectedItem;
/*do something */
lstContact.SelectedIndex = -1;
}

Accessing User in Entity partial class via OnContextCreated()?

All of my tables have common audit fields: modifiedBy,modifiedDateTime, etc.
I would like to have these automatically set, and can set most of them with the following code:
partial class myEntities
{
partial void OnContextCreated()
{
this.SavingChanges += new EventHandler(Entities_SavingChanges);
}
private void Entities_SavingChanges(object sender, EventArgs e)
{
IEnumerable<ObjectStateEntry> objectStateEntries =
from ose
in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
where ose.Entity != null
select ose;
var auditDate = DateTime.Now;
var auditUser = System.Web.HttpContext.Current.User.Identity.Name;//I wish
foreach (ObjectStateEntry entry in objectStateEntries)
{
ReadOnlyCollection<FieldMetadata> fieldsMetaData = entry.CurrentValues.DataRecordInfo.FieldMetadata;
FieldMetadata modifiedField = fieldsMetaData.Where(f => f.FieldType.Name == "ModifiedBy").FirstOrDefault();
if (modifiedField.FieldType != null)
{
string fieldTypeName = modifiedField.FieldType.TypeUsage.EdmType.Name;
if (fieldTypeName == PrimitiveTypeKind.String.ToString())
{
entry.CurrentValues.SetString(modifiedField.Ordinal, auditUser);
}
}
}
}
}
The problem is that there doesn't appear to be any way to get access to the current user. The app is intranet only, using Windows auth.
Is there a way to either pass in a parameter, or get access to the HttpContext (which doesn't seem like it would be a good idea, but I'm stuck)? Is there a way to populate the EventArgs with information?
Check out the section where the poster has overridden the SaveChanges method (6th code box down on the page). This way you can pass in the UserID and perform your audit and not have to use an event handler.

BlackBerry - Add items to a ListField

Can someone please give me a simple example on how to add three rows to a ListField so that the list shows something like this?
Item 1
Item 2
Item 3
I just want to show a list in which the user can select one of the items and the program would do something depending on the item selected.
I've search all over the internet but it seems impossible to find a simple example on how to do this (most examples I found are incomplete) and the blackberry documentation is terrible.
Thanks!
You probably want to look at using an ObjectListField. Handling the select action is done throught the containing Screen object, I've done this below using a MenuItem, I'm not really sure how to set a default select listener, you may have to detect key and trackwheel events.
Some example code for you: (not tested!)
MainScreen screen = new MainScreen();
screen.setTitle("my test");
final ObjectListField list = new ObjectLIstField();
String[] items = new String[] { "Item 1", "Item 2", "Item 3" };
list.set(items);
screen.addMenuItem(new MenuItem("Select", 100, 1) {
public void run() {
int selectedIndex = list.getSelectedIndex();
String item = (String)list.get(selectedIndex);
// Do someting with item
});
screen.add(list);
You can override the navigationClick method like this:
ObjectListField list = new ObjectListField()
{
protected boolean navigationClick(int status, int time)
{
// Your implementation here.
}
};
final class SimpleListScreen extends MainScreen
{
public SimpleListScreen()
{
super(Manager.NO_VERTICAL_SCROLL);
setTitle("Simple List Demo");
add(new LabelField("My list", LabelField.FIELD_HCENTER));
add(new SeparatorField());
Manager mainManager = getMainManager();
SimpleList listField = new SimpleList(mainManager);
listField.add("Item 1");
listField.add("Item 2");
listField.add("Item 3");
}
}
//add listener so that when an item is chosen,it will do something
private ListField fList = new ListField(){
protected boolean navigationClick(int status, int time) {
System.out.println("omt Click");
return true;
};
};
You can detect the click on each list item by overriding
protected boolean navigationClick(int status,int time)
Then you just need to work out what to do in response to the click. The way I did this was by using an anonymous class, set for each list item.

Resources