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);
Related
Afternoon,
I have a search button which searches the list of the users is either by IDnumber,Username or department.
I have 2 list view which the users clicks and it load the selected user to the second list view. now the problem is after u clicked users from listview1 and u went to type ID,Username or select department and click search...It clears all the users you selected and bring new users u where searching.
I want to be able to select the users and be able to search without losing my current selected users from the listview
my code ;
//search button
private void Searchbutton_Click(object sender, EventArgs e)
{
try
{
listView1.Items.Clear();
string sID = string.IsNullOrEmpty(txtUserID.Text) ? null : txtUserID.Text;
string sDepartment;
if (cboDepartment.SelectedItem != null)
{
sDepartment = cboDepartment.SelectedItem.ToString();
}
else
{
sDepartment = "";
}
oConnection = new SqlConnection(_connectionString);
oCommand = new SqlCommand(#"Select us.sFieldValue5, u.sUserName, d.sName, TB_USER_CUSTOMINFO.sFieldValue2
From TB_USER u(nolock)
left join [TB_USER_CUSTOMINFO] us(nolock) on us.nUserIdn = u.nUserIdn
left join TB_USER_CUSTOMINFO on u.nUserIdn = TB_USER_CUSTOMINFO.nUserIdn
left join TB_USER_DEPT d(nolock) on d.nDepartmentIdn = u.nDepartmentIdn
where u.sUserName like '%'+ISNULL(#UserName,u.sUserName)+'%'
and us.sFieldValue5 = isnull(#IDNumber,us.sFieldValue5)
and d.sDepartment like '%'+isnull(#Department,d.sDepartment)+'%'", oConnection);
oCommand.Parameters.AddWithValue("UserName", string.IsNullOrEmpty(txtUsername.Text) ? DBNull.Value : (object)txtUsername.Text);
oCommand.Parameters.AddWithValue("IDNumber", string.IsNullOrEmpty(txtUserID.Text) ? DBNull.Value : (object)txtUserID.Text);
oCommand.Parameters.AddWithValue("Department", string.IsNullOrEmpty(sDepartment) ? DBNull.Value : (object)sDepartment);
oConnection.Open();
oDataset = new System.Data.DataSet();
SqlDataReader oReader = oCommand.ExecuteReader();
while (oReader.Read())
{
ListViewItem item1 = new ListViewItem(oReader[1].ToString());
item1.SubItems.Add(oReader[2].ToString());
item1.SubItems.Add(oReader[3].ToString());
item1.SubItems.Add(oReader[0].ToString());
listView1.Items.AddRange(new ListViewItem[] {item1});
}
oReader.Close();
oConnection.Close();
}
//selected users
private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
if (e.Item.Checked == true)
{
ListViewItem l = listView1.Items[e.Item.Index];
int i = l.SubItems.Count;
string sValue1 = l.SubItems[1].Text;
string sValue2 = l.SubItems[2].Text;
string sValue3 = l.SubItems[3].Text;
ListViewItem item1 = new ListViewItem(l.SubItems[0].Text.ToString());
item1.SubItems.Add(sValue3);
item1.SubItems.Add(sValue2);
item1.SubItems.Add(sValue1);
listView2.Items.AddRange(new ListViewItem[] { (ListViewItem)l.Clone() });
}
else if (e.Item.Checked == false)
{
ListViewItem l = listView1.Items[e.Item.Index];
foreach (ListViewItem i in listView2.Items)
{
if (i.SubItems[0].Text == l.SubItems[0].Text.ToString())
{
listView2.Items.Remove(i);
}
}
}
}
ListView remember which ListViewItems were checked. As soon as you say Items.Clear(), all that knowledge is lost.
To solve your problem, you will need to remember which users were checked, do your refresh, then go through and mark each user as checked again.
To do those steps, you really need to separate your model from your view. Create a User model object to hold the actual data, then populate your ListView with data from your model. When the user does another search, update or refresh your model objects, then rebuild your view.
Doing this model/view separation is a little more work up front, but future generations of maintenance programmers will bless your name.
BTW, ObjectListView -- an open source wrapper around a .NET ListView -- makes creating a fully functional ListView from a list of model objects trivially easy.
on windows form all textbox and combobox is bind from acctPackageBindingSource . My problem with biniding in combobox that display only int value means that is coming form acctPackage . And i want to display the name means 'Displaymember' of that value . That one is coming form different table name is sysCode. So how can i display the display member perfectly . Below is my code
// Here the all value is coming form Syscode table .
public void FillDropDown()
{
if (_commonComponent == null)
_commonComponent = new CommonComponent();
List<SysCode> _syscode = _commonComponent.GetByTableCodeForIncomeDedMapping("19");
bindingSourceSysCode.DataSource = _syscode;
packageCodeComboBox.DataSource = bindingSourceSysCode;
packageCodeComboBox.DisplayMember = "Desclong2";
packageCodeComboBox.ValueMember = "PackageCode";
}
//This part is bind my all value on the form
private void FillAcctPackage()
{
if (_commonComponent == null)
_commonComponent = new CommonComponent();
acctPackageBindingSource.DataSource = _commonComponent.GetAcctPackge();
}
I've read all the similiar posts about this darn control (DataGridViewComboBoxCell) and setting it's value programmatically but implementing all the suggestions hasn't worked. I could probably change the UI to get around this problem but I don't like to be beat!
private void PopulateAreaForRoleAssociation()
{
// If businessRoleList is null then no data has been bound to the dgv so return
if (businessRoleList == null)
return;
// Ensure businessArea repository is instantiated
if (businessAreaRepository == null)
businessAreaRepository = new BusinessAreaRespository();
// Get a reference to the combobox column of the dgv
DataGridViewComboBoxColumn comboBoxBusinessAreaColumn = (DataGridViewComboBoxColumn)dgvBusinessRole.Columns["BusinessArea"];
// Set Datasource properties to fill combobox
comboBoxBusinessAreaColumn.DisplayMember = "Name";
comboBoxBusinessAreaColumn.ValueMember = "Id";
comboBoxBusinessAreaColumn.ValueType = typeof(Guid);
// Fill combobox with businessarea objects from list out of repository
comboBoxBusinessAreaColumn.DataSource = businessAreaRepository.GetAll();
// loop through the businessRoles list which the dgv is bound to and get out each dgv row based upon the current id in the loop
businessRoleList.Cast<BusinessRole>().ToList().ForEach(delegate(BusinessRole currentRole)
{
DataGridViewRow currentRowForRole = dgvBusinessRole.Rows.Cast<DataGridViewRow>().ToList().Find(row => ((BusinessRole)row.DataBoundItem).Id == currentRole.Id);
// Get a reference to the comboBox cell in the current row
DataGridViewComboBoxCell comboBoxCell = (DataGridViewComboBoxCell)currentRowForRole.Cells[2];
// Not sure if this is necessary since these properties should be inherited from the combobox column properties
comboBoxCell.DisplayMember = "Name";
comboBoxCell.ValueMember = "Id";
comboBoxCell.ValueType = typeof(Guid);
// Get the business area for the current business role
BusinessArea currentAreaForRole = businessAreaRepository.FetchByRoleId(currentRole.Id);
// if the role has an associated area then set the value of the cell to be the appropriate item in the combobox
// and update the cell value
if (currentAreaForRole != null)
{
foreach (BusinessArea area in comboBoxCell.Items)
{
if (currentAreaForRole.Id == area.Id)
{
comboBoxCell.Value = area.Id;
dgvBusinessRole.UpdateCellValue(2, comboBoxCell.RowIndex);
}
}
}
});
}
The dgv is first bound to a binding list holding BusinessRole objects, then the combobox column is bound to a basic list of BusinessArea objects that come out of a repository class. I then loop through the bindinglist and pull out the row of the dgv that is bound to the current item in the bindinglist loop.
With that row I make a database call to see if the BusinessRole entity is associated with a BusinessArea entity. If it is then I want to select the item in the combobox column that holds the BusinessAreas.
The problem is that when the grid is loaded, all the data is there and the comboboxes are populated with a list of available areas, however any values that are set are not displayed. The code that sets the value is definately getting hit and the value I am setting definately exists in the list.
There are no data errors, nothing. It's just refusing to update the UI with the value I programmatically set.
Any help would be greatly appreciated as always.
Thanks
This code works for my first combo box I have in my row with the following code, but I try it with the next one in the row and it doesn't work. I could use the help with the rest I have 3 more to do. I do set the combo boxes on a second form from this form with the same code as is on the last line of the try block but using the cell information instead of the dataset
try
{
string strQuery = "select fundCode from vwDefaultItems where IncomeType = '" + stIncome + "'";
SqlDataAdapter daDefault = new SqlDataAdapter(strQuery, conn);
DataSet dsDefault = new DataSet();
daDefault.Fill(dsDefault);
strDefFund = dsDefault.Tables[0].Rows[0].ItemArray[0].ToString();
dgvCheckEntry.Rows[curRow].Cells[7].Value = dsDefault.Tables[0].Rows[0].ItemArray[0].ToString();
}
catch (Exception eq)
{
}
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();
}
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