Posts Tagged ‘combobox’
How to add object to a combobox
To add the object as an item to a combobox is pretty easy, it is the same as you are adding a string/numeric value.
Example:
-
Public class X
-
Public Name as String
-
Public Value as String
-
-
Public Sub New(StrName As String, StrValue As String)
-
Name = StrName
-
Value = StrValue
-
End Sub
-
End Class
-
-
To fill the combobox with the created object, let's say you have a combo box called cboX
-
dim Obj as X
-
For i as Integer = 0 to 10
-
cboX.Items.Add(New X("Name " & i.ToString(), "Value " & i.ToString())
-
Next
Then you need to set the DisplayMember property of the Combo box so that the Text displayed in the
combobox is not “namespace.X”.
-
cboX.DisplayMember = "Name"
How to Adjust DropdownWidth of the ComboBox
use this script to adjust the size of the combobox
private void AdjustWidthComboBox_DropDown(object sender, System.EventArgs e)
{
ComboBox senderComboBox = (ComboBox)sender;
int width = senderComboBox.DropDownWidth;
Graphics g = senderComboBox.CreateGraphics();
Font font = senderComboBox.Font;
int vertScrollBarWidth =
(senderComboBox.Items.Count>senderComboBox.MaxDropDownItems)
?SystemInformation.VerticalScrollBarWidth:0;
int newWidth;
foreach (string s in ((ComboBox)sender).Items)
{
newWidth = (int) g.MeasureString(s, font).Width
+ vertScrollBarWidth;
if (width < newWidth )
{
width = newWidth;
}
}
senderComboBox.DropDownWidth = width;
}
Add Custom Object to Combo box
Use Items.add (object) and make sure your object class is overriding the ToString()
Conversion from type ‘DataRowView’ to type ‘Integer’ is not valid.
Conversion from type ‘DataRowView’ to type ‘Integer’ is not valid this will occur during binding the combo box by setting the datasource and you have a code to execute inside the combobox_SelectedIndexChanged Event that retrieves the selected value of the combo box. The below script will give you an exception error at the time of setting the datasource of the combobox
Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboDemographics.SelectedIndexChanged
Messagebox.show(cboDemographics.SelectedValue)
End Sub
to correct this you have to check the selectedValue
Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboDemographics.SelectedIndexChanged
If TypeOf cboDemographics.SelectedValue Is DataRowView Then
Exit Sub
End If
Messagebox.show(cboDemographics.SelectedValue)
End Sub
How to Select item in combobox by value
How to Select item in combobox by value
Private sub ComboBoxSelect(value as string)
combobox1.SelectedValue = value
End Private