I believe this question is kinda new-bie, but I can't solve it in correct way.
Brief description:
I have an inherited from ComboBox class that does some data bindings in constructor:
var mdl = new Model();
ValueMember = "id";
DisplayMember = "unit";
DataSource = mdl.getUnits();
All good here. The combobox is filled by required data.
Then I have another form with a function editIngridient. The function is following;
public bool editIngridient(int id)
{
currentId = id;
var row = mdl.getIngridient(id);
txtIngridient.Text = (string)row["ingridient"];
cmbUnit.ID = (int)row["unitId"];
numNotifyQty.Value = (int) row["notifyQty"];
ShowDialog();
return true;
}
Now, when the form popups, textbox and number box filled by needed values, while combobox is filled by first value.
If I will run the combobox data bind function as the first line inside editIngridient function - all works good.
Please point me to my stupidity.
Thanks a lot!
YOu didnt say what is your dataSource, but I assume thats DataTable, so you can do it:
DataRowView rowData = comboBox1.SelectedItem as DataRowView;
int id = Convert.ToInt32(rowData["id"]);
string name = rowData["unit"].ToString();
Related
I have a ListView populated with the code below. Ask you can see, I set both the DisplayMember and the ValueMember. What I am wanting to do is find a ListViewItem by its ValueMember. So essentially what I'm looking for is ListViewItem.Value. I know I can get SelectedValue for the ListView itself, but I just don't see any properties on the ListViewItem that give me what I'm looking for. Am I just missing something, or is there no way to do this?
private void PopulateList(Globals.DataFieldMappingTypes mappingType)
{
ListBox lst = GetListBox(mappingType);
ComboBox cbo = cboh.GetComboBox(new ComboBoxHandler.CboInfo(Globals.NodeTypes.DataField, mappingType));
string sql = "select DataFieldReferenceValueId, [Value] from DataFieldReferenceValueInfo where DataFieldId = " + cbo.SelectedValue.ToString();
DataTable tbl = dal.GetTable(sql, "DataFieldReferenceValue");
lst.DisplayMember = "Value";
lst.ValueMember = "DataFieldReferenceValueId";
lst.DataSource = tbl.DefaultView;
}
I think that you are not getting the values from DataTable correctly I guess.
I hope tbl.Rows[0][0].ToString() will have the DataFieldReferenceValueId and
tbl.Rows[0][1].ToString() will have the [Value]
Please check the below MSDN link
https://forums.asp.net/t/1188002.aspx?how+to+read+DataTable+Rows+value+and+put+it+into+the+string+
Instead of loading your dataTable straight in as the dataSource why don't you create a class to define the values?
public class SqlTable
{
public string Name {get;set;}
public string Value {get;set;}
}
var listPair = new List<SqlTable>();
Then load the list with your SqlDataReader and grab your desired pair with LINQ.
while (sdr.Read())
{
listPair.Add(new SqlTable() { Name = sdr[0].ToString(), Value = sdr[1].ToString() });
}
lst.DisplayMember = "Name";
lst.ValueMember = "Value";
lst.DataSoure = listPair;
SqlTable sqlTable = listPair.Find(x => x.Name == "Whatever name you are searching for") as SqlTable;
The SqlTable item is now the one you are searching for and you can get its properties by going:
string value = sqlTable.Value;
string name = sqlTable.Name;
Edit from comment begins here:
Well your first issue is that the 'lst' item in your example is a ListBox and not a ListView. It you switch it to a listview you can still feed your List of listPair items like so:
ListView lst = new ListView();
lst.View = View.Details;
foreach (var data in listPair)
{
lst.Items.Add(new ListViewItem(listPair.Name, listPair.Value);
}
So now you have a ListView that is a collection of your listPairs where each listPair is a ListViewItem. I assume you want to isolate the ListViewItem based on your value (or listPair.Value or sdr[1] or [Value] they are all the same now) in order to color it. You can now grab the listPair item like so:
SqlTable pair = listPair.Find(x => x.Value == "Whatever the Value value is that you want to color");
ListViewItem searchedItem = lst.FindItemWithText(pair.Name);
searchedItem.BackColor = System.Drawing.Color.Red; //or whatever color you choose
You can now use searchedItem to grab its index in the ListView and all its other properties. The ListPair just allows you to associate the values.
I'm trying to set a specific item as selectedItem in a DataGridComboBoxColumn. However a lot of research, I couln't find the right answer for me yet.
My scenario:
I have a programatically created a DataGrid which has an ObservableCollection<> as ItemsSource. As a last column, I want to add a DataGridComboBoxColumn to give the user a selection to choose from. Since such data can already be stored in the database, I need to "preset" the value from the collection stored in the database.
private void ManipulateColumns(DataGrid grid)
{
...
DataGridComboBoxColumn currencies = new DataGridComboBoxColumn();
//Here come the possible choices from the database
ObservableCollection<string> allCurrencies = new ObservableCollection<string>(Data.AllCurrencys);
currencies.ItemsSource = allCurrencies;
currencies.Header = "Currency";
currencies.CanUserReorder = false;
currencies.CanUserResize = false;
currencies.CanUserSort = false;
grid.Columns.Add(currencies);
currencies.MinWidth = 100;
//Set the selectedItem here for the column "Currency"
...
}
I found many tutorials for setting the selected item for normal ComboBoxes, but not for DataGridComboBoxColumns. I already tried it with currencies.SetCurrentValue(), but I can't find a suitable DependencyProperty from DataGridComboBoxColumn.
Can someone please help me out?
Thanks in advance.
Boldi
Building a DataGrid like that with C# code is messy. You should really take a look at using Data Binding instead. If you want to continue with building it in C#, then you are going to have to set the value per Row. There isn't a way to set a default for all the rows in a column. Say my DataGrid is bound to a collection of type Book. I can use the DataGrid SelectedItem property to get the Book object for the selected row, then set it's currency property. You're going to have to figure out what row you need to set the value for, get your object for that row, then set its currency property. This isn't a complete answer but it will get you started. Essentially, you are going to have to set it for each item in the DataGrid, not the column.
public class Book
{
public decimal price;
public string title;
public string author;
public string currency;
}
private void ManipulateColumns(DataGrid grid)
{
DataGridComboBoxColumn currencies = new DataGridComboBoxColumn();
//Here come the possible choices from the database
System.Collections.ObjectModel.ObservableCollection<string> allCurrencies = new System.Collections.ObjectModel.ObservableCollection<string>();
allCurrencies.Add("US");
allCurrencies.Add("asdf");
allCurrencies.Add("zzz");
currencies.ItemsSource = allCurrencies;
currencies.Header = "Currency";
currencies.CanUserReorder = false;
currencies.CanUserResize = false;
currencies.CanUserSort = false;
grid.Columns.Add(currencies);
currencies.MinWidth = 100;
//Set the selectedItem here for the column "Currency"
//currencies.
((Book)grid.SelectedItem).currency = "US Dollar";
}
I have a datagrid with 2 columns: 1 is normal textbox type and the other column is combobox type.
My user interface has another datagrid_1 which contains a list of names. When a user clicks on the row of datagrid_1 with names. It puts the value selected by the user in the row of datagrid_2 in 1st column and then expects user to select one of the values in the other column (combobox).
I am not sure how to assign a datasource to this combobox. I have tried the following code but I am getting error "Datagridview_2 combox value is not valid."
var source = new BindingSource();
var phase_7 = (phaseeqType.return_Distinct_Phase()
.Select(b => b).AsEnumerable()).ToList();
string[] P_combo = new string[phase_7.Count()];
for (int i = 0; i < phase_7.Count(); i++)
{
P_combo[i] = phase_7.ToString();
}
source.DataSource = phase_7;
dataGridView1.CurrentRow.Cells[1].Value = source;
Can anyone pls help?
Cells don't have a DataSource property, so you would have try casting it to something that does:
Example:
((DataGridViewComboBoxCell)dataGridView1.CurrentRow.Cells[1])
.DataSource = source;
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 trying to set selected item of comboBox on click event of DataGrid, but I could not. I have googled and tried different ways but without success.
For me SelectedIndex is working, but I could not find the index of items in ComboBox, so I could not select the item.
Not working code:
for (int i = 0; i < cmbVendor.Items.Count; i++)
if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
{
cmbVendor.SelectedIndex = i;
break;
}
You can get your item index by the .Items.IndexOf() method. Try this:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf(gridView1.GetFocusedRowCellValue("vVendor"));
You don't need to iterate.
You can find more information in Stack Overflow question How do I set the selected item in a comboBox to match my string using C#?.
The following is working for me perfectly. Pass any value or Text which is available in the combobox.
comboBox1.SelectedIndex = comboBox1.FindString(<combobox value OR Text in string formate>);
You have it in your if:
cmbVendor.SelectedItem = cmbVendor.Items[i];
At last I found it out. It's:
cmbVendor.Text = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.
If you have set ValueMember property for the ComboBox control, you can simply assingn the Value to the ComboBox control's SelectedValue property. You don't have to find the index explicitly.
Here's an example:
public class Vendor{
public int VendorId {get; set;}
public string VendorName {get; set;}
}
// Inside your function
var comboboxData = new List<Vendor>(){
new Vendor(){ vendorId = 1, vendorName = "Vendor1" },
new Vendor(){ vendorId = 2, vendorName = "Vendor2" }
}
cmbVendor.DataSource = comboboxData;
cmbVendor.DisplayMember = "VendorName";
cmbVendor.ValueMember = "ValueId";
// Now, to change your selected index to the ComboBox item with ValueId of 2, you can simply do:
cmbVendor.SelectedValue = 2;
Assuming gridView1.GetFocusedRowCellValue("vVendor") really works as expected, the following code should fix the problem.
string selected = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
foreach ( var item in cmbVendor.Items )
{
if (string.Compare(item.ToString(), selected, StringComparison.OrdinalIgnoreCase) == 0)
{
cmbVendor.SelectedItem = item;
break;
}
}
The original code had multiple calls to gridView1.GetFocusedRowCellValue("vVendor"), whereas you only need one.
The suggested "comboBox1.Items.IndexOf(" assumes too much about the content of cmbVendor.Items.
I had a similar problem and worked it out partially with the help of the other answers here. First, my particular problem was that
combobox1.SelectedItem = myItem;
was not working as expected. The root cause was that myItem was an object from a group which was effectively the same list as the items in the combobox, but it was actually a copy of those items. So myItem was identical to a valid entry, but itself was not a valid object from the combobox1 container.
The solution was to use SelectedIndex instead of SelectedItem, like this:
combobox1.SelectedIndex = get_combobox_index(myItem);
where
private int get_combobox_index(ItemClass myItem)
{
int i = 0;
var lst = combobox1.Items.Cast<ItemClass >();
foreach (var s in lst)
{
if (s.Id == myItem.Id)
return i;
i++;
}
return 0;
}
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String From DataGrid Cell value")
Try this this will work fine in C# Windows application
this works for me.....
string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;