I usually do web programming but have a requirement for a windows form in this project I'm working on now.
I'm using SubSonic to get a list of jobs and load a combobox:
JobCollection jobs = new JobCollection().Load();
cboJobs.DisplayMember = "Name";
cboJobs.ValueMember = "Id";
cboJobs.DataSource = jobs;
When the user selects an item and clicks the search button I need to query the database using the job "Id" field.
TransactionCollection transactions = new TransactionCollection();
if (!String.IsNullOrEmpty(txtTransactionId.Text))
{
transactions.Where("id", txtTransactionId.Text);
}
else
{
transactions.Where("raw_data", Comparison.Like, "%" + txtFind.Text + "%");
}
transactions.Where("job_id", Convert.ToInt32(cboJobs.SelectedItem));
transactions.Load();
The line that is having the problem is the one that goes "Convert.ToInt32(cboJobs.SelectedItem)".
How do I get the job id versus the name?
You might want to look at the SelectedValue property of your combobox. You set the ValueMember to the ID, so the SelectedValue should contain the correct value.
You have already gotten (a good) answer, but I thought it might be in place to point this out anyway: in your application's combo box, each item will actually be a full Job object, not only a string representation of one. So the SelectedItem property will return the Job object that is currently selected in the ComboBox. You can access any of its members simply by casting it to Job:
Job currentJob = cboJobs.SelectedItem as Job;
if (currentJob != null)
{
// here you can access currentJob.Name, currentJob.Id or any other member
}
Related
How to filter a combobox based on another combobox? ... again :)
I'm writing an web app to learn. I'm using Visual Studio 2012, Silverlight 5, C#, and SQl Server for the data source.
I have one table loading into a datagrid and comboboxes to filter the datagrid. Up to this point everything is working just right.
The comboboxes are "FilterState" and "FilterWaterWay". Note they are not in the datagrid.
I want to select a state and re-populate the FilterWaterWay with only those waterways in the state.
I've seen a lot of ways to do this but none of them seem to match my setup. I could be wrong and just not know it.
From a learning standpoint, I would like to know how to implement this in all 3 of the following query data examples but I'll settle for just one. The last one is my favorite.
Thanks for any and all help.
I would not mind using the following to load comboboxes, filtered or not, but I can't firgure out how to
Restirct the GetQuery to only one field
Make that field distinct
This loads all data from the GetQuery to the datagrid.
LoadOperation<MASTER_DOCKS> loadOp = this._DocksContext.Load(this._DocksContext.GetMASTER_DOCKSQuery());
DocksGrid.ItemsSource = loadOp.Entities;
This loads all data from the GetQuery to the datagrid after it's been filtered
EntityQuery<MASTER_DOCKS> query = _DocksContext.GetMASTER_DOCKSQuery();
query = query.Where(s => s.WTWY_NAME == WaterwaytoFilterBy && s.STATE == StateToFilterBy);
LoadOperation<MASTER_DOCKS> loadOp = this._DocksContext.Load(query);
DocksGrid.ItemsSource = loadOp.Entities;
This is how I am currently loading the comboboxes. This works fine for the load but I don't see how to filter.
The DomainService.cs does not know my other combobox (FilterState) that I want to use as the filter for this combobox (FilterWaterway).
If I could query the ObservableCollection in the xaml I might be able to get it to work but it seems kind of chunky.
Adapted from http://www.jonathanwax.com/2010/10/wcf-ria-services-datagrid-filters-no-domaindatasource-2/
XAML =
private ObservableCollection<string> waterWayFilterList;
public ObservableCollection<string> WaterWayFilterList
{
get { return waterWayFilterList; }
set { waterWayFilterList = value; }
}
private void DoPopulateFilter()
{
//Call Invoke Method to get a list of distinct WaterWays
InvokeOperation<IEnumerable<string>> invokeOp = _DocksContext.FillWaterWayList();
invokeOp.Completed += (s, e) =>
{
if (invokeOp.HasError)
{
MessageBox.Show("Failed to Load Category Filter");
}
else
{
//Populate Filter DataSource
WaterWayFilterList = new ObservableCollection<string>(invokeOp.Value);
//Add a Default "[Select]" value
WaterWayFilterList.Insert(0, "[Select WaterWay]");
FilterWaterWay.ItemsSource = WaterWayFilterList;
FilterWaterWay.SelectedItem = "[Select WaterWay]";
}
};
}
DomainService.cs =
[Invoke]
public List<string> FillWaterWayList()
{
return (from r in ObjectContext.MASTER_DOCKS
select r.WTWY_NAME).Distinct().ToList();
}
Here's the closest I've gotten so far and it seems straight forward.
It returns no errors but the displayed result reads System.Collections.Generic.List'1[System.Char]
The record count in the dropdown is correct which leads me to think it's on the right track.
Only what is displayed is wrong. A casting problem perhaps?
I would still have to get the result from the FilterState Combo box in where "TX" is.
var filter = from r in _DocksContext.MASTER_DOCKS
where r.STATE.Equals("TX")
select r.WTWY_NAME.Distinct().ToList();
MyComboBox.ItemsSource = filter;
Without parentheses, you're doing the .Distinct().ToList() on the string (which implements IEnumerable<char>, which is why those operations work), which results in a List<char> (which isn't what you're looking for). You need to add parentheses so you get the distinct waterways:
var filter = (from r in _DocksContext.MASTER_DOCKS
where r.STATE.Equals("TX")
select r.WTWY_NAME).Distinct().ToList();
Note that if two waterways might have the same name, but actually be distinct, you'll need to instead select distinct r, and then differentiate them in the dropdown somehow, e.g.
var filter = (from r in _DocksContext.MASTER_DOCKS
where r.STATE.Equals("TX")
select r).Distinct().ToList();
// generated classes are partial, so you can extend them in a separate file
public partial class MASTER_DOCKS
{
// the dropdown uses the ToString method to show the object
public override string ToString()
{
return string.Format("{0} ({1})", WTWY_NAME, ID);
}
}
I have table with 4 primary key fields. I load that in to drop down list in my WinForm application created by using C#.
On the TextChanged event of drop down list I have certain TextBox and I want to fill the information recived by the table for the certain field I selected by the drop down list.
So as I say the table having 4 fields. Can I get those all 4 fields into value member from the data set, or could you please tell me whether is that not possible?
Thank you.
Datatable dt=dba.getName();
cmb_name.ValueMember="id";
cmb_name.DisplayMember="name";
cmb_name.DataSource=dt;
this is normal format.. but i have more key fields.. so i need to add more key fields..
You can use DataSource property to bind your source data to the ComboBox (e.g. a List of Entities, or a DataTable, etc), and then set the DisplayMember property of the ComboBox to the (string) name of the field you want to display.
After the user has selected an Item, you can then cast the SelectedItem back to the original row data type (Entity, DataRow, etc - it will still be the same type as you put in), and then you can retrieve your 4 composite keys to the original item.
This way you avoid the SelectedValue problem entirely.
Edit:
Populate as follows:
cmb_name.DisplayMember = "name";
cmb_name.DataSource = dt;
// Ignore ValueMember and Selected Value entirely
When you want to retrieve the selected item
var selectedRow = (cmb_name.SelectedItem as DataRowView );
Now you can retrieve the 4 values of your PK, e.g. selectedRow["field1"], selectedRow["field2"], selectedRow["field3"] etc
If however you mean that you want to DISPLAY 4 columns to the user (i.e. nothing to do with your Table Key), then see here How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?
cmb_name.DisplayMember = "name";
cmb_name.DataSource = dt;
DataRowView selectedRow = (cmb_name.SelectedItem as DataRowView );
The result will be here:
MessageBox.Show(selectedRow.Row[0].ToString());
MessageBox.Show(selectedRow.Row[1].ToString());
MessageBox.Show(selectedRow.Row[2].ToString());
MessageBox.Show(selectedRow.Row[3].ToString());
.....
If you want to get some data from a ComboBox in to a List you can use something like this
List<string> ListOfComboData = new List<string>();
ListOfComboData = yourComboBox.Items.OfType<string>().ToList<string>();
I have no real idea if this is what you mean as the question is very poorly structured. I hope this helps...
Edit: To put the selected text in to some TextBox use
yourTextBox.Text = youComboBox.Text;
in the SelectedIndexChanged event of your ComboBox.
You could follow the approach here with the following class:
public class ComboBoxItem
{
public string Text { get; set; }
public object[] PrimaryKey { get; set; }
}
private void Test()
{
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.PrimaryKey = new object[] { primaryKey1, primaryKey2, primaryKey3, primaryKey4};
comboBox1.Items.Add(item);
comboBox1.SelectedIndex = 0;
MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}
I am having a problem to change a selected item in a drop-down.
The way I use is (a property in the code behind which sets the new selection):
public char Candy
{
set
{
var newSelection = ddlCandy.Items.FindByValue(value.ToString());
ddlCandy.ClearSelection();
newSelection.Selected = true;
}
}
Is this a recommended and proper way?
recommended approach is to simply assign the SelectedValue property with the Value you have and the DropDownList control will find and select the proper item for you, if any.
Safe way is fist Find the given item from DropDownList and set it as SelectedValue
ListItem oListItem = DropDownList1.Items.FindByValue("yourValue");
if(oListItem != null)
{
DropDownList1.SelectedValue = oListItem.Value;
}
if you directly assign SelectedValue it may through an exception if it is not exist in the list like bellow.
'DropDownList' has a SelectedValue which is invalid because it does
not exist in the list of items.
I usually prefer to use SelectedValue:
DropDownList1.SelectedValue = "Foo";
I use combobox in c# windows form. I bound the item list as below:
var employmentStatus = new BindingList<KeyValuePair<string, string>>();
employmentStatus.Add(new KeyValuePair<string, string>("0", "[Select Status]"));
employmentStatus.Add(new KeyValuePair<string, string>("1", "Contract"));
employmentStatus.Add(new KeyValuePair<string, string>("2", "Part Time"));
employmentStatus.Add(new KeyValuePair<string, string>("3", "Permanent"));
employmentStatus.Add(new KeyValuePair<string, string>("4", "Probation"));
employmentStatus.Add(new KeyValuePair<string, string>("5", "Other"));
cmbEmployeeStatus.DataSource = employmentStatus;
cmbEmployeeStatus.ValueMember = "Key";
cmbEmployeeStatus.DisplayMember = "Value";
cmbEmployeeStatus.SelectedIndex = 0;
I save the selected value in database eg.1 or 2. Now I want to set selected value from database item like:
cmbEmployeeStatus.SelectedValue =employee.employmentstatus;
But combobox not selected with value. How can I do that?
Try this one.
cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);
In order to do the database style ComboBoxes manually trying to setup a relationship between a number (internal) and some text (visible), I've found you have to:
Store you items in a list (You are close - except the string,string - need int,string)
DataSource property to the list (You are good)
DataMember,DataValue (You are good)
Load default value (You are good)
Put in value from database (Your question)
Get value to put back in database (Your next question)
First things first. Change your KeyValuePair to so it looks like:
(0,"Select")
(1,"Option 1")
Now, when you run your sql "Select empstatus from employees where blah" and get back an integer, you need to set the combobox without wasting a bunch of time.
Simply: *** SelectedVALUE - not Item ****
cmbEmployeeStatus.SelectedValue = 3; //or
cmbEmployeeStatus.SelectedValue = intResultFromQuery;
This will work whether you have manually loaded the combobox with code values, as you did, or if you load the comboBox from a query.
If your foreign keys are integers, (which for what I do, they all are), life is easy. After the user makes the change to the comboBox, the value you will store in the database is SelectedValue. (Cast to int as needed.)
Here is my code to set the ComboBox to the value from the database:
if (t is DBInt) //Typical for ComboBox stuff
{
cb.SelectedValue = ((DBInt)t).value;
}
And to retrieve:
((DBInt)t).value = (int) cb.SelectedValue;
DBInt is a wrapper for an Integer, but this is part of my ORM that gives me manual control over databinding, and reduces code errors.
Why did I answer this so late? I was struggling with this also, as there seems to be no good info on the web about how to do this. I figured it out, and thought I'd be nice and post it for someone else to see.
In windows Appliation
we use like this
DDLChangeImpact.SelectedIndex = DDLChangeImpact.FindStringExact(ds.Tables[0].Rows[0]["tmchgimp"].ToString());
DDLRequestType.SelectedIndex = DDLRequestType.FindStringExact(ds.Tables[0].Rows[0]["rmtype"].ToString());
Use the SelectedIndex property for the respective employee status in the combo box.
Below will work in your case.
cmbEmployeeStatus.SelectedItem =employee.employmentstatus;
When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index. If the object does not exist in the list, the SelectedIndex property is left at its current value.
EDIT
I think setting the Selected Item as below is incorrect in your case.
cmbEmployeeStatus.SelectedItem =**employee.employmentstatus**;
Like below
var toBeSet = new KeyValuePair<string, string>("1", "Contract");
cmbEmployeeStatus.SelectedItem = toBeSet;
You should assign the correct name value pair.
cmbEmployeeStatus.Text = "text"
I suspect something is not right when you are saving to the db. Do i understand your steps as:
populate and bind
user selects and item, hit and save.. then you save in the db
now if you select another item it won't select?
got more code, especially when saving? where in your code are initializing and populating the bindinglist
A possible solution:
cmbEmployeeStatus.SelectedValue = cmbEmployeeStatus.Items.FindByText("text").Value;
try this
combobox.SelectedIndex = BindingSource.Item(9) where "9 = colum name 9 from table"
To set value in the ComboBox
cmbEmployeeStatus.Text="Something";
Try this:
KeyValuePair<string, string> pair = (KeyValuePair<string,string>)this.ComboBox.SelectedItem;
This may have been already asked but I can't seem to find this specific question, so here goes...
I have a form in C# where every textbox is bound to a field in a row. Rows can be cycled through by some buttons on the bottom but all the data displayed at a time in the from is from one row. Any changes that are made get updated back to the database when the user clicks "update"
One field (class) is an enumeration (0,1,2) where only the value is stored in the database, but doesn't mean much to the user. I was asked to make this more obvious to the user, so I decided to go with a dropdown style combo box. Since the database didn't have any reference to what the values meant, I decided to use the DataBindings instead of DataSource so I could just use the index as the data bind, but it seems that SelectedItem or Value are not the way to do this.
Here is my goal:
1 exists in database, so "B" is selected in combo box.
User selects "C" and updates the database, 2 is now stored in the database.
Any thoughts on what I need to get this working?
I assume you have a BindingSource on your form to bind to the data. You can bind the SelectedIndex property of the ComboBox as follows:
comboBox.DataBindings.Add("SelectedIndex", bindingSource, "PropertyInTheDataSource");
Actually I was able to bind it to a custom Object. It's a little too much work for such a simple task. But you have complete control on Display/Value pairs. Anyway, I thought I'd share and you decide:
Create a new class (say CustomItem) with 2 fields:
Public int Value{get;set;}
public string Title {get;set;}
Then in you form:
var item1 = new CustomItem() { Title = "A", Value = 10 };
var item2 = new CustomItem() { Title = "B", Value = 20 };
var item3 = new CustomItem() { Title = "C", Value = 30 };
var lst = new List<CustomItem>();
lst.Add(item1);
lst.Add(item2);
lst.Add(item3);
comboBox1.DataSource = lst;
comboBox1.DisplayMember = "Title";
comboBox1.ValueMember = "Value";
Now You have a databound combobox in case you don't have BndingSource in your form.
Just remember to define your class's Title and Value as properties otherwise it wouldn't work.