I have a problem which I can't figure out.
I have an DataGridViewComboboxCell,
List<ComboBoxItem> klanten = new List<ComboBoxItem>();
foreach (ICustomer customer in CustomerFactory.CreateCustomers())
{
klanten.Add(new ComboBoxItem(customer.Naam, customer.Id));
}
klanten.Add(new ComboBoxItem("Klant aanvraag", -1));
uxInvoerenKlant.DataSource = klanten;
uxInvoerenKlant.DisplayMember = "Text";
uxInvoerenKlant.ValueMember = "Value";
When the option "Klant aanvraag" is selected the user gets a window where the user can choose another customer.
This is for the reason the user was not assigned for a specific project for that customer.
When the user chose one it will be changed in the Combobox with the following code.
uxUrenInvoeren[collumnIndex, row.Index].Value = uxInvoerenKlant.Items[klantIndex];
klantindex is the customer that needs to be selected, because it is retrieved from the combobox. It is the right kind of object in my opinion.
After this, the datagridview_dataerror event is raised where I get the Format exception with the following exception text.
DataGridViewComboBoxCell value is not valid.
What is the problem?
I found the problem myself.
The uxUrenInvoeren[collumnIndex, row.Index].Value contained the value of the ComboBoxItem and not the ComboBoxItem itself. The code now looks like this:
ComboBoxItem item = uxInvoerenKlant.Items[klantIndex] as ComboBoxItem;
if (item != null)
{
uxUrenInvoeren[collumnIndex, row.Index].Value = item.Value;
}
In this way it goes well.
Thanks for the help!
I think it may be your value of -1. Maybe you need to start with 0
You should add the selected value to the items collection of the combobox, the exception is raised since the value assigned is not found in the Item collection of the ComboBoxColumn and hence not a valid value.
Try adding it using Add
(dataGridView1.Columns[0] as DataGridViewComboBoxColumn).Items.Add
Solution :
Private Sub gvPrint_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles gvPrint.DataError
If e.Context = DataGridViewDataErrorContexts.Formatting Or e.Context = DataGridViewDataErrorContexts.PreferredSize Then
e.ThrowException = False
End If
End Sub
Related
I had a databound combobox in my windows form I populate it by a function deptload() IN FORM LOAD
public void DeptcomboLoad()
{
DataTable dt = depttrans.getDeptName();
Cmb_Department.DataSource = dt;
Cmb_Department.DisplayMember = "DepartmentName"; //CHAR
Cmb_Department.ValueMember = "DepartmentPK"; //INT
}
Now when an employee of a department (say accounts DepartmentName="Accounts " , DepartmentPK=23 ) login I want the ComboBox text to be selected as "acounts "
and when I go to get the selected value of the ComboBox I should get 23
I tried
Cmb_Department.selectedtext="Accounts"
Cmb_Department.Text="Accounts"
but its not giving the selected value
Can anyone give a suggestion
Instead of trying to put a value INTO the combobox, try to GET the SelectedItem like this:
string txt= Cmb_Department.SelectedItem.Text
or just:
string txt= Cmb_Department.SelectedText
To change selected value of the combobox you can use
SelectedItem property or SelectedIndex.
Index must be exact number in your data sourse, and Item must be exact object from datasource
You can get it to select the right item by issuing something like this:
Cmb_Department.SelectedValue = 23;
Where 23 comes from some other variable, maybe on another object, maybe from a local variable, whatever works in your case.
Now, to get the selected value you can use this statement:
var val = Cmb_Department.SelectedValue;
To get the selected text (which would be the text associated with the value):
var text = ((DataRow)Cmb_Department.SelectedItem)["DepartmentName"];
The reason I'm prescribing the aforementioned is because the SelectedText property is volatile, and the Text property doesn't always work based on how the DropDownStyle is set.
However, some would probably argue to get the same as the aforementioned you could issue this statement:
var text = Cmb_Department.Text;
I have two comboBox cb_Brand and cb_Model on a winForm.
cb_Model populates values on brand Select.
the problem is: if we select the brand any and select the any model under that brand, cb_Model does not loose the value of previous model selected.
for example: If we select the brand Audi and model A3
and the select the Brand Ford, when I click on cb_Model to select the model, it displayed the A3 as selected model, but still other models in list are belong to ford.
my code is:
private void cb_Brand_SelectedIndexChanged(object sender, EventArgs e)
{
// Clear Current Data
cb_Model.Text = "";
cb_Model.Items.Clear();
CarModel _carmodel = new CarModel ();
// Get Selected Car Brnad
int CarBrandID = _carmodel .GetCarBrandID(cb_Brand.Text);
//Enable choice of Model
SortedList<int, Model> colM;
colM = Model.ReadModel(CarBrandID);
cb_Model.DisplayMember = "ModelText";
foreach (Model objM in colM.Values)
{
cb_Model.Items.Add(objM);
}
}
Any Idea Please..
Thanks
unable to find the reason but sorted out with a temp fix:
private void cb_Model_Click(object sender, EventArgs e)
{
cb_Model.Text = "";
}
Thanks a lot guys
cheers
Instead of adding the items manually like this:
foreach (Model objM in colM.Values)
{
cb_Model.Items.Add(objM);
}
Let .NET take care of it for you and replace it with this:
cb_Model.DataSource = colMValues;
Which will bind the data to the list and refreshes the comboboxes items automatcially when a data source is set.
You will also not need these lines anymore:
// Clear Current Data
cb_Model.Text = "";
cb_Model.Items.Clear();
Have a read of this for more info on binding lists (and other data sources) to ComboBoxes:
How to: Bind a Windows Forms ComboBox or ListBox Control to Data (MSDN)
#w69rdy suggests an excellent solution.
The reason cb_Model did not change it's value is because you never changed the value. cb_Model.Items.Clear() does not change the selected index; only the items are removed from the combo box.
Using the code sample provided in your question:
// Clear Current Data
cb_Model.Text = "";
cb_Model.Items.Clear();
cb_Model.SelectedIndex = -1; // would effectively clear the previously selected value.
i had same problem now and Combobox's ResetText method solved the problem for me
This would work
combobox.ResetText();
I've tried your example. For me it worked as it should have.
You could try setting the cb_model.SelectedText to "" or SelectedItem to null
I found that keeping the scope of the data source near the loading of the combo box worked for me. I had a datatable with class level scope and it did not clear but then I brought it into function level scope and had it clear after the load and this worked.
I have a similar problem,tried cmb.resettext it clears text but not value.In my load form I have the below code:
Dim cmd As New SqlCommand("SELECT stud_id,name FROM student_details WHERE stud_id NOT IN (SELECT stud_id FROM student_details WHERE hostel_id!=0)", sqlcont.Conn)
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim dat As New DataTable
Dim j As Integer
For j = 0 To dat.Rows.Count - 1
dr.Read()
Next
dat.Load(dr)
cmbstud.DisplayMember = "name"
cmbstud.ValueMember = "stud_id"
cmbstud.DataSource = New BindingSource(dat, Nothing)
dr.Close()
In my btnhostel click event I have the below code:
frmallocateHostel_Load(Nothing, Nothing)
this I put in attempt to reload my dataset and thus my comboboxes.Using cmbstud.resettext simply clears the text not the value.
I have same problem then I used
combobox1.SelectedIndex=-1
and it works.
I am dynamically creating a combobox like this:
public Control GenerateList(Question question)
{
// Get a list with answer possibilities
List<QuestionAnswer> answers = question.GetAnswers();
// Get a collection of given answers
Collection<QuestionnaireAnswer> givenAnswers = question.GetFilledAnswers();
ComboBox cmb = new ComboBox();
cmb.Name = "cmb";
cmb.DataSource = answers;
cmb.DisplayMember = "Answer";
cmb.ValueMember = "Id";
// Check an answer is given to the question
if (givenAnswers != null && givenAnswers.Count > 0)
{
cmb.SelectedValue = givenAnswers[0].AnswerId;
}
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.SelectedIndexChanged += new EventHandler(cmb_SelectedIndexChanged);
cmb.Leave += new EventHandler(cmb_Leave);
return cmb;
}
The problem is,when executing cmb.SelectedValue = givenAnswers[0].AnswerId; cmb.SelectedValue is always null.
When debugging and I explore answers (the datasource) I see that Id (ValueMember) is exactle the same as AnswerId (in the if statement). Both have the same type (long) and the same value, but SelectedValue stays null.
Is there something I don't see?
EDIT:
It looks like the combobox stays empty. When I replace cmb.SelectedValue = givenAnswers[0].AnswerId; with cmb.SelectedIndex = 0; I get an ArgumentOutOfRangeException. This while the answers collections count is 2. So the datasource isn't null... Very strenge huh?
Solution:
The SelectedValue, SelectedIndex, SelectedItem properties can't be set until the control is added to the form. After the control is added to the form, the selectedValue, -Index and -Item properties can be set.
Solution:
The SelectedValue, SelectedIndex, SelectedItem properties can't be set until the control is added to the form. After the control is added to the form, the selectedValue, -Index and -Item properties can be set.
I met this weird issue before, at last I gave up and used another way:
cmb.Items.FindByValue(givenAnswers[0].AnswerId).Selected = true;
It worked fine...Hope you good luck!
cmb.SelectedIndex = cmb.FindStringExact("Desired Value")
The cmb.FindStringExact("Desired String") returns the index of the value you would like to select and the cmb.SelectedIndex sets the combobox to that index.
Thanks to Billious for showing me the light!
FYI - This is the VB.NET Winforms Version.
Are you looking at the same property?
cmb.ValueMember = "Id";
..
cmb.SelectedValue = givenAnswers[0].AnswerId;
You're refering to another ValueMember then the Id you're posting into the SelectedValue.
Besides that you might want to try to set your Display- and Value-member before databinding. It's faster.
Make sure QuestionAnswer has public accessors corresponding (same name) to the Display/Value Members you use.
I ran into the same problem, and found that my issue was I was treating SelectedValue as an integer, when in actual fact it was an object. The "FindByValue" solution from Danny Chen above doesn't work in WinForms, so I tried using "FindStringExact" and searched on the DisplayMember:
cmb.Items.FindStringExact(<Display string>)
Not an ideal solution, but it worked.
I have a bound dropdown list populated with a table of names through a select, and databinding. it shoots selectedindexchanged that (through a postback) updates a certain gridview.
What happens is, since it runs from changing the index, the one that always comes selected (alexander) can only me chosen if you choose another one, then choose alexander. poor alexander.
What I want is to put a blanc option at the beginning (default) and (if possible) a option as second.
I can't add this option manually, since the binding wipes whatever was in the dropdown list and puts the content of the datasource.
Set the AppendDataBoundItems property to True. Add your blank, then data bind.
ddl.AppendDataBoundItems = true;
ddl.Items.Add("Choose an item");
ddl.DataSource = foo;
ddl.DataBind();
The AppendDataBoundItems property
allows you to add items to the
ListControl object before data
binding occurs. After data binding,
the items collection contains both the
items from the data source and the
previously added items.
protected void SetAddrList()
{
TestDataClassDataContext dc = new TestDataClassDataContext();
dc.ObjectTrackingEnabled = false;
var addList = from addr in dc.Addresses
from eaddr in dc.EmployeeAddresses
where eaddr.EmployeeID == _curEmpID && addr.AddressID == eaddr.AddressID && addr.StateProvince.CountryRegionCode == "US"
select new
{
AddValue = addr.AddressID,
AddText = addr.AddressID,
};
if (addList != null)
{
ddlAddList.DataSource = addList;
ddlAddList.DataValueField = "AddValue";
ddlAddList.DataTextField = "AddText";
ddlAddList.DataBind();
}
ddlAddList.Items.Add(new ListItem("<Add Address>", "-1"));
}
I created this code example using adventure works to do a little practice with Linq and it is very similar to the previous answer. Using linq still shouldn't matter for the answer the last dddlAddList.Items.Add is what you need. "Add Address" = first selected option and -1 = the value.
How can i add 10 items to listbox dynamically to a listbox and after that I want to show the selected item value in click event of list box.
I tried like this
for(int i=1;i<10 ;i++)
{
mylistbox.Items.Add(i.ToString());
}
in click event handler
MessageBox.Show(mylistbox.SelectedValue.ToString());
it is showing error.
Whats the wrong with this?
Try using the SelectedItem property instead.
SelectedValue only works when you fill the ListBox with objects and have a ValueMember assigned.
Here is a minimal example:
var mylistbox = new ListBox {Dock = DockStyle.Fill};
mylistbox.Click += (sender, e) =>
MessageBox.Show(mylistbox.SelectedItem.ToString());
for (int i = 1; i < 10; i++)
{
mylistbox.Items.Add(i.ToString());
}
new Form {Controls = {mylistbox}}.ShowDialog();
Use the following code on the click handler
MessageBox.Show(mylistbox.Text.ToString()); //This will show the selected item as your requirement.
replace the .SelectedValue with .Text
Dmitriy has it exactly.
A good way to check what is happening when you're debugging is to highlight 'mylistbox.SelectedValue' and right-click, then select 'Add Watch'. You can then track the value of that property in the Watch window.
You can do this with any variable, and any time it shows null and you're trying to use that value you know it will throw a Null Reference Exception.
It's also good for picking up letters in a string you're trying to convert to an integer, and other similar "d'oh!" moments.