I have a RIA service that is to return a list of schools and populate a datagrid. This datagrid is duplicating the first result throughout the entire grid, as opposed to showing each item from source in its own row.
The service is as follows
var schools1 = (from i in DataContext.PrevSchools
join skl in DataContext.SchoolLists on i.School_id equals skl.School_Id
where i.Email_Address == email
select new PreviousSchools
{
PrevSchoolsId = i.PrevSchools_id,
AppEmail = i.Email_Address,
SchoolId = i.School_id,
DateAttended = i.YearsAttended,
Study = i.Study,
Credit = i.Credit,
CompleteStatus = i.Complete_Status,
Award = i.Award,
SchoolName = skl.School_name
}).Union(from i in DataContext.PrevSchools
join skl1 in DataContext.Schools on i.School_id equals skl1.School_id
where i.Email_Address == email && i.School_type_id == 1
select new PreviousSchools
{
PrevSchoolsId = i.PrevSchools_id,
AppEmail = i.Email_Address,
SchoolId = i.School_id,
DateAttended = i.YearsAttended,
Study = i.Study,
Credit = i.Credit,
CompleteStatus = i.Complete_Status,
Award = i.Award,
SchoolName = skl1.School_name
}).OrderBy(q => q.SchoolName);
return schools1;
The Databinding is:
this.PrevSchools.prevSchoolDataGrid.DataContext = SchoolsList;
The SchoolList is an ObservableCollection, it was set as a list and also a, IEnumerable, and it still yielded the duplicated results.
Fixed it, it was an error in the Model class, the key was set to the wrong property
Related
There is a strange behavior when using a ComboBox in VGridControl.
I have a list of objects:
var samples = new List<Samples>();
samples.Add(new Samples {Id = 1, Name = "s1"});
samples.Add(new Samples {Id = 2, Name = "s2"});
samples.Add(new Samples {Id = 3, Name = "s3"});
samples.Add(new Samples {Id = 4, Name = "s4"});
VGridControl has one row, and this row has a RowEdit = CheckedComboBoxEdit.
CheckedComboBoxEdit.ShowDropDown is set to "DoubleClick".
Then:
repositoryItemCheckedComboBoxEdit1.DataSource = samples;
repositoryItemCheckedComboBoxEdit1.ValueMember = "Id";
repositoryItemCheckedComboBoxEdit1.DisplayMember = "Name";
row.Properties.Value = "2, 4";
Repro steps:
When I press the drop down button and then check the CheckedState for each item - it's OK. It shows the correct values;
When I simply select the row (press the row itself) and do not expand the drop down list, then CheckedState of all items is "Unchecked".
I check using:
int checkedItems = 0;
foreach (var item in repositoryItemCheckedComboBoxEdit1.GetItems().Cast<CheckedListBoxItem>())
{
if (item.CheckState == CheckState.Checked)
{
checkedItems++;
}
}
So, how to get the checked values from CheckedComboBoxEdit?
I found a simple answer. In order to get row value, you can use:
var s = vGridControl.GetCellValue(row1, vGridControl.FocusedRecord).ToString();
This shows a stored value for a row. Then you can convert it into the list:
var list = s.Split(',').ToList();
Hi all the below solution works in that it creates a record in the MeetingRoomRequest table and also adds the associated amenities to that request into the MeetingRoomRequestAmenityLink table. However it just feels a bit clunky, so I was wondering if there is a nicer solution out there (i.e. not having to create 2 context instances) using MVC 3 and Entity Framework??
Please note i've set up the necessary relationships (one to many) in SQL Server and Entity Framework.
Also please note AmenityList is an array of id's (e.g. [1,2,4])
private readonly IDataRepository<MeetingRoomRequest> _meetingRoomRequestRepository = new DataRepository<MeetingRoomRequest>();
private readonly IDataRepository<MeetingRoomRequestAmenityLink> _meetingRoomRequestAmenityLinkRepository = new DataRepository<MeetingRoomRequestAmenityLink>();
var meetingRoomRequestToAdd = new MeetingRoomRequest
{
User = meetingRoomRequestViewModel.User,
UserEmail = meetingRoomRequestViewModel.UserEmail,
Title = meetingRoomRequestViewModel.Title,
Comments = meetingRoomRequestViewModel.Comments,
StartDateTime = meetingRoomRequestViewModel.StartTime,
EndDateTime = meetingRoomRequestViewModel.EndTime,
RequestStatusID = (int)Enums.RequestStatus.New,
AttendeeCount = meetingRoomRequestViewModel.AttendeeCount,
AttendeeType = meetingRoomRequestViewModel.AttendeeType,
OfficeID = meetingRoomRequestViewModel.OfficeId,
LocationID = meetingRoomRequestViewModel.LocationId,
};
_meetingRoomRequestRepository.Add(meetingRoomRequestToAdd);
_meetingRoomRequestRepository.SaveChanges();
var meetingRoomRequestAdded = meetingRoomRequestToAdd;
foreach (var item in meetingRoomRequestViewModel.AmenityList)
{
var meetingRoomRequestAmenityLinkToAdd = new MeetingRoomRequestAmenityLink
{
AmenityID = item,
MeetingRoomRequestID = meetingRoomRequestAdded.MeetingRoomRequestID
};
_meetingRoomRequestAmenityLinkRepository.Add(meetingRoomRequestAmenityLinkToAdd);
_meetingRoomRequestAmenityLinkRepository.SaveChanges();
}
The way you are going about it looks right, but there are some improvements that could be made in efficiency of processing the request.
Since these are a child/parent relationship, you can create the parent entity and then attached the childern in the foreach loop before you call save changes on the parent entity. EF will automatically populate the foreign key value on the child object with the primary (or associated key) from the parent.
You can continue to use your Entity without having to save it back out to a variable. EF's object tracking will continue to track this throughout your function.
By moving the savechanges outside of the foreach loop, you are reducing the number of calls. I believe the same amount of SQL will be sent on the one final call, but you may see increases of not having the connection open/close. There may be other built in efficiencies as well from EF
The Code
var meetingRoomRequestToAdd = new MeetingRoomRequest
{
User = meetingRoomRequestViewModel.User,
UserEmail = meetingRoomRequestViewModel.UserEmail,
Title = meetingRoomRequestViewModel.Title,
Comments = meetingRoomRequestViewModel.Comments,
StartDateTime = meetingRoomRequestViewModel.StartTime,
EndDateTime = meetingRoomRequestViewModel.EndTime,
RequestStatusID = (int)Enums.RequestStatus.New,
AttendeeCount = meetingRoomRequestViewModel.AttendeeCount,
AttendeeType = meetingRoomRequestViewModel.AttendeeType,
OfficeID = meetingRoomRequestViewModel.OfficeId,
LocationID = meetingRoomRequestViewModel.LocationId,
};
_meetingRoomRequestRepository.Add(meetingRoomRequestToAdd);
foreach (var item in meetingRoomRequestViewModel.AmenityList)
{
meetingRoomRequestToAdd.MeetingRoomRequestAmenityLinks.Add(new MeetingRoomRequestAmenityLink
{
AmenityID = item
});
}
_meetingRoomRequestRepository.SaveChanges();
I have a dude, i want to select a value from wpf Combobox
I have the next code:
private void CargarUnidades()
{
List<Unidades> unidades;
using (var sesion = NHibernateFluentConfiguracion.AbrirSesion())
{
using (var transaccion = sesion.BeginTransaction())
{
unidades = Unidades.ObtenerTodaslasUnidades();
}
}
cmbUnidad.ItemsSource = unidades;
cmbUnidad.DisplayMemberPath = "Nombre";
cmbUnidad.SelectedValuePath = "Nombre";
}
After I charge the unidades
CargarUnidades(); //Charge all unidades in the combobox
Articulos c = Articulos.Obtener(id_articulo);
//Get Articulo from the database for the id
//In the last query I get the unidad same that exists in cmbUnidad
//previusly charge
//I assing the value but in the combobox doesnt appear selected,
//appear nothing
cmbUnidad.SelectedValue = c.id_unidad;
txtCodigo.Text = c.Codigo;
.
.
.
.
How I can select a value from combobox???
Note: I m new in WPF and my english is not good je je je
Thanks for the answer Firo, I modify the code and this is the result
cmbUnidad.Items.Cast<Unidades>().FirstOrDefault(u => u.id_unidad == c.id_unidad.id_unidad);
I dont know if this is the best way but its functionaly :P
selectedValue must euqal (using Equals) with one of the values in the list hence assign the object not the id because the control does not know how to select based on the id
cmbUnidad.SelectedValue = c;
UPDATE: since the Articulos has only the id of unidades and not a reference (which i would have mapped) you have to search for it.
cmbUnidad.SelectedValue = cmbUnidad.Items.Cast<Unidades>().FirstOrDefault(u => u.Nombre == c.id_unidad);
As you can tell from my code, I'm absolute a beginner. After searching through other similar issues on LINQ to SQL problems, I find myself still seemingly stuck on two objectives. 1) Adding a new entry with input from the user selection from three comboboxes and a datepicker and 2) Updating an existing database entry using interactions from the datagridview.
My windows form datagridview is displaying the following output
**select b.Date, a.EmployeeName,
c.ProjectName, b.Hours
from dbo.Employees a
left outer join dbo.EmployeeProjectHours b
on a.EmployeeId = b.EmployeeId
left outer join dbo.Projects c
on b.ProjectId = c.ProjectId**
Here is my ADD method the user is providing me with ProjectName, EmployeeName, Date and Hours. Any thoughts for a layman would be appreciated.
I don't get an error running the insert, but nothing is added to my dab as well
using (ProjectHoursDataContext dbInsert = new ProjectHoursDataContext())
{
this.Validate();
EmployeeProjectHour empHours = new EmployeeProjectHour();
empHours.Date = dateDateTimePicker.Value;
empHours.Hours = Convert.ToDecimal(hoursComboBox.Text);
empHours.ProjectId = dbInsert.Projects.First(p => p.ProjectName == projectNameComboBox.Text).ProjectId;
empHours.EmployeeId = dbInsert.Employees.First(m => m.EmployeeName == employeeNameComboBox.Text).EmployeeId;
db.EmployeeProjectHours.InsertOnSubmit(empHours);
dbInsert.SubmitChanges();
}
Here is my Update attempting to use updates directly from the datagridview. I get the following error: A first chance exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll
using (ProjectHoursDataContext dbUpdate = new ProjectHoursDataContext())
{
this.Validate();
dataGridView1.AutoGenerateColumns = true;
projectBindingSource.DataSource = dbUpdate;
projectBindingSource.DataMember = "Updates";
projectBindingSource.EndEdit();
dbUpdate.SubmitChanges();
}
My best guess so far is, you want to edit and change existing Employee, Project and EmployeeProjectHours records.
So you would do:
using (ProjectHoursDataContext dbInsert = new ProjectHoursDataContext())
{
this.Validate();
// Get the records
Employee emp = new Employee();
Project proj = new Project();
EmployeeProjectHour empHours = new EmployeeProjectHour();
// Set new values to Employees tables
emp = dbInsert.Employees
.First(m => m.EmployeeName == employeeNameComboBox.Text);
//just get the empployee
//setting values will update it
emp.EmployeeName = employeeNameComboBox.Text;
// GET an existing project
proj = dbInsert.Projects
.First(p => p.ProjectName == projectNameComboBox.Text);
//update its values.
proj.ProjectName = projectNameComboBox.Text;
proj.ProjectDescription = "Test";
//GET an empHours
empHours = dbInsert.Projects.First(p => p.EmployeeId == emp.EmployeeId &&
p.ProjectId == proj.ProjectId);
//set its values
empHours.Date = dateDateTimePicker.Value;
empHours.Hours = Convert.ToDecimal(hoursComboBox.Text);
dbInsert.SubmitChanges();
}
Aside from the new code below, I also set my increment status for my projects database to NO. I had set it yes from a previous stackoverflow discussion. Thanks
public void AddInfo()
{
db.Connection.Open();
this.Validate();
EmployeeProjectHour empHours = new EmployeeProjectHour();
empHours.Date = dateDateTimePicker.Value;
empHours.Hours = Convert.ToDecimal(hoursComboBox.Text);
empHours.ProjectId = db.Projects.First(p => p.ProjectName == projectNameComboBox.Text).ProjectId;
empHours.EmployeeId = db.Employees.First(m => m.EmployeeName == employeeNameComboBox.Text).EmployeeId;
db.EmployeeProjectHours.InsertOnSubmit(empHours);
db.SubmitChanges();
db.Connection.Close();
}
In the code below, the combo box named "ConnectionType" shows the selected item, but one cannot change the selected item (it seems like there is only one item in the combo box). If I comment out the line
typeCol.DataPropertyName = "ConnectionTypeName";
then the combo box is selectable, but the correct item is not selected, of course. What am I doing wrong??
Thanks.
private void LoadConnectionsGrid()
{
_dc = new EnterpriseEntities();
dataGridViewConnections.AutoGenerateColumns = false;
dataGridViewConnections.DataSource = _dc.Connection.Include("ConnectionType");
DataGridViewComboBoxColumn typeCol =
(DataGridViewComboBoxColumn)dataGridViewConnections.Columns["ConnectionType"];
typeCol.DataPropertyName = "ConnectionTypeName";
var qry = from c in _dc.ConnectionType
select c.Type;
typeCol.DataSource = qry;
DataGridViewTextBoxColumn nameCol =
(DataGridViewTextBoxColumn)dataGridViewConnections.Columns["ConnectionName"];
nameCol.DataPropertyName = "Name";
DataGridViewTextBoxColumn connStrCol =
(DataGridViewTextBoxColumn)dataGridViewConnections.Columns["ConnectionString"];
connStrCol.DataPropertyName = "ConnectionString";
}
Ultimately, I could not get data binding, the entity framework, and comboboxes to play nice and I just created the data grid brute force (code below). This means that I handle inserts, updates and deletes by hand.
private void LoadConnectionsGrid()
{
DataGridViewComboBoxColumn typeCol =
(DataGridViewComboBoxColumn)dataGridViewConnections.Columns["ConnectionType"];
var qry = from c in _dc.ConnectionType
select c.Type;
typeCol.DataSource = qry;
dataGridViewConnections.Rows.Clear();
foreach (Connection conn in _dc.Connection.Include("ConnectionType"))
{
dataGridViewConnections.Rows.Add(conn.Name,
conn.ConnectionType.Type, conn.ConnectionString);
}
}