combobox shows value that isn't in the datasource - c#

I have a combobox (using databindings)
I load the combobox values as follows:
cb.BeginUpdate();
cb.DisplayMember = "Display";
cb.ValueMember = "Value";
cb.DataSource = cbvalues.GetBindingTable(true);
if (cb.Items != null && cb.Items.ValueList != null)
cb.Items.ValueList.FormatFilteredItems = DefaultableBoolean.True;
cb.EndUpdate();
the cbvalues list contains several members (for example true/false/both)
the databindings occur as follows:
cb.DataBindings.Add("Value",
_data,
_data.GetPropertyName(bo => bo.cbvalue),
false,
DataSourceUpdateMode.OnPropertyChanged).BindingComplete += someotherfunctionname;
Now for the sake of reason, I for example always get the value Unknown from my object.
I would like to have my combobox showing nothing at all, just an empty combobox. Instead I get the value 'Unknown' in it. How can I disable this kind of behaviour.

Related

Getting current value of comboBox in SelectedValueChange event

I follow this instructions to create multi select combobox
So I have something like this:
var empList = db.GetTableBySQL($"exec getTaskAssignableEmployeeList");
checkBoxComboBox1.DataSource = new Utility.ListSelectionWrapper<DataRow>(empList.Rows, "Abbreviation");
checkBoxComboBox1.DisplayMemberSingleItem = "Name";
checkBoxComboBox1.DisplayMember = "NameConcatenated";
checkBoxComboBox1.ValueMember = "Selected";
checkBoxComboBox1.Tag = empList.Rows;
checkBoxComboBox1.SelectedValueChanged += ComboEmployee_SelectedValueChanged;
As you can see I have ComboEmployee_SelectedValueChanged Event. So when I click into one checkbox I want to retrieve value of comboBox as:
private void ComboEmployee_SelectedValueChanged(object sender, EventArgs e)
{
var db = new SQLConnMgr();
var employeeComboBox = sender as CheckBoxComboBox;
var taskDataRow = employeeComboBox.Tag as DataRow;
var taskTypeName = taskDataRow["Name"] as string;
}
But I'm getting error because taskDataRow is always null, then when it try to execute var taskTypeName = taskDataRow["Name"] as string; I'm getting:
Object reference not set to an instance of an object.'
Why I cant retrieve taskDataRow fro\m comboBox? Regards
If you want to know which items are selected, you have two options:
Use the CheckBoxItems property on the ComboBox which is a list of items wrapping each item in the ComboBox.Items list. The CheckBoxComboBoxItem class is a standard CheckBox, and therefore the bool value you are looking for is contained in Checked.
Or if you stored a reference to the ListSelectionWrapper<T>, you could use that to access the Selected property of the binded list.
-
if (ComboBox.CheckBoxItems[5].Checked)
DoSomething();
OR
if (StatusSelections.FindObjectWithItem(UpdatedStatus).Selected)
DoSomething();
You are getting Null Reference exception because you have saved table.Rows in the tag of the combobox not the DataRow in the below line that why you are getting exception.
var taskDataRow = employeeComboBox.Tag as DataRow;
To resolve the issue, Iterate through CheckBoxItems and there you can
get the selected item text. After that filter the data rows on the
basis of selected item text or value.

DataGridViewComboBoxCell Value not being set properly

I've been trying to set the value of an individual DataGridViewComboBoxCell for the last 4 hours and I've been getting nowhere. The most common solution I've seen was to set the .Value member of the DataGridViewComboBoxCell to one of the Items, which I tried and it complained the value was not valid.
DataTable documentTypes = _codedValues.GetCodedValues(Database.DOCUMENT_TYPE_TABLE); documentTypes.Columns[Database.PROFESSION_ID_COLUMN].AllowDBNull = true;
documentTypes.Columns[Database.CODE].AllowDBNull = true;
this.cbxDocumentType.DisplayMember = Database.VALUE;
this.cbxDocumentType.ValueMember = Database.CODE;
this.cbxDocumentType.DataSource = documentTypes.DefaultView;
int rowId = this.dgvDocumentList.Rows.Add(doc.actualName, doc.fileName);
DataGridViewComboBoxCell obj = (DataGridViewComboBoxCell)this.dgvDocumentList.Rows[rowId].Cells[2];
obj.Value = obj.Items[0];
After the message box comes up that tells me DataGridViewComboBoxCell view is not valid, I see the .ToString output of the object being set, which is System.Data.DataRowValue.
Depending what your datasource contains you must use the correct casts to access the correct fields.
Try this:
DataGridViewComboBoxCell cell =
(DataGridViewComboBoxCell)this.dgvDocumentList.Rows[rowId].Cells[2];
cell.Value = ((DataRowView)cell.Items[0]).Row.ItemArray[0];
This assumes that the Items are DataRowViews and that the ValueMember is in the first field.
You can test the type by writing an intermediate step:
var item = cell.Items[0];
And use the debugger to look into the resulting type..

Check if DataGridViewComboBox is empty

I have a datagridview with a combobox column that is bound to an enum as follows:
var D = (DataGridViewComboBoxColumn)dgvInputs.Columns[2];
D.ValueType = typeof(MyType);
D.ValueMember = "Value";
D.DisplayMember = "Display";
D.DataSource = new MyType[] {
MyType.Rev,
MyType.Model,
MyType.User,
MyType.Status
}.Select(x => new { Display = x.ToString(), Value = (int)x }).ToList();
The datagridview is then bound to a DataTable named ParameterTable:
BindingSource ParamSource = new BindingSource();
ParamSource.DataSource = DataEntry.ParameterTable;
dgvInputs.AutoGenerateColumns = false;
dgvInputs.DataSource = ParamSource;
dgvInputs.Columns[0].DataPropertyName = "Name";
dgvInputs.Columns[1].DataPropertyName = "Prompt";
dgvInputs.Columns[2].DataPropertyName = "Type";
dgvInputs.Columns[3].DataPropertyName = "Width";
dgvInputs.Columns[4].DataPropertyName = "Default Value";
When the user finishes editing the table, I need to validate it. In particular, I need to test that the Type has been defined in each row, and that the Default Value is compatible with the Type.
The problem is, every test I've found for checking if the Type has been set has failed. When I later try to cast the value as MyType as part of testing the default value, I get an error. When I check the .Value property on the empty Type cell in the debugger, it shows a value of "{}".
Currently, I have this code for the test, in the Validating event for the datagridview itself. I have tried various other versions and they have also failed:
foreach (DataGridViewRow Row in dgvInputs.Rows) {
if (!Row.IsNewRow) {
// test other columns ...
DataGridViewComboBoxCell Cell = (DataGridViewComboBoxCell)(Row.Cells[2]);
if (Cell == null || Cell.Value as string == string.Empty) {
// Error ...
}
MyType PType = (MyType)(Cell.Value);
How can I test if a DataGridViewComboBox cell has not been set, and what is this value "{}"?
FYI - I am using VS 2008, and .Net 3.5 SP1. Not my choice. Just what is available to me.
There are a couple problems with this code.
First, D.ValueType = typeof(MyType); is incorrect because from what I see, you are binding to int field. Just remove that line, ValueType will be inferred from the data source.
Now, the main issue. When binding to a data table, the non entered value is represented by DBNull.Value. I would suggest you checking for both null and DBNull.Value. When entered, the value type in your case will be int, but you can safely unbox it to MyType.
The code should be something like this
//...
var value = Row.Cells[2].Value;
if (value == null || value == DBNull.Value)
{
// Error ...
}
else
{
var type = (MyType)value;
// Check if type contains a valid value ...
}

how to set the default value to the drop down list in C#?

DataSet dsCurrency = new DataSet();
dsCurrency = ParamCurrency.SelectCurrencys();
ddCurrencyField.DataSource = dsCurrency;
ddCurrencyField.DataTextField = "CurrencyName";
ddCurrencyField.DataValueField ="CurrencyCode";
ddCurrencyField.DataBind();
How to select a default value to the dropdownlist control using C#?
If you know the value will exist:
ddCurrencyField.FindItemByText("YourDefaultText").Selected = true;
else
ListItem selectedListItem = ddCurrencyField.Items.FindItemByText("YourDefaultText");
if (selectedListItem != null)
{
selectedListItem.Selected = true;
};
You can also find item by value :
ListItem selectedListItem = ddCurrencyField.Items.FindByValue("YourDefaultValue");
if (selectedListItem != null)
{
selectedListItem.Selected = true;
};
I assume in your datasource object (dsCurrency) is not parsing the default value for the dropdown.
So first you will have to add the default item. After binding the datasource do the following.
ddCurrencyField.Items.Insert(0, new ListItem("-- Select --",0));
With the above code you will have a default/first item selected as "--Select--". If it does not select the first item then simply set the SelectedIndex to 0.
There are 2 ways to set the default item after populating a dropdown.
you can use the "SelectedValue" property
you can use the "SelectedIndex" property
Most of the code samples are given in the previous answers. But I prefer to use the "FindByValue" method.
ddCurrencyField.SelectedIndex = ddCurrencyField.Items.IndexOf(ddCurrencyField.Items.FindByValue(myValue));
If you want to write a safe code please use the second option.
If this dropdown list is a combobox, use this:
ddCurrencyField.SelectedIndex = ddCurrencyField.Items.IndexOf("Wanted Value");

Setting default value to a DataGridViewComboBoxCell

The combobox displays a blank field by default even though the combobox is populated with a number of values
ColumnSpeed.DataSource = speedList;
ColumnSpeed.ValueType = typeof(string);
I also tried the following, but it still displays the blank text.
foreach (DataGridViewRow row in myDataGridView.Rows)
{
DataGridViewComboBoxCell cell = row.Cells[ColumnSpeed.Index] as DataGridViewComboBoxCell;
if (cell != null)
{
cell.DataSource = speedList;
cell.Value = cell.Items[0].ToString();
}
}
It could be that the ValueMember you assigned to your DataGridView is different from the DisplayMember you assigned. If that's the case, you'll get a blank value, plus you'll get a DataGridError firing.
You should try:
foreach (DataGridViewRow row in dgMain.Rows){
DataGridViewComboBoxCell pkgBoxCell = row.Cells[ColumnSpeed.Index]
pkgBoxCell.Value = ((Package) pkgBoxCell.Items(0)).Id
}
I converted that from vb.net, so it may not compile. In place of the line where i set the value, do whatever steps are necessary to retrieve and set the correct ValueMember value. In my example, I am casting the item to a specific type and using it's id.
I believe the code you have written should work .. just want to know where are you calling the same. It should work if you call it in the databinding_complete event of the grid
Once you set all the DataSources, try calling the DataGridView.Refresh() method. This is usually required to display changes to the DataSources.

Categories