Dynamic ComboBox Datasource Form Load - c#

I'm creating a dynamic combo box and adding to a form. I'm trying to fill the combo box with a DataSource from an ArrayList and then selecting an item in the combo box based off a value from a property.
Problem is, the combo box items don't get bound until after the Form_Load event has finished and the form is visible. So the combo box is empty when I try to set the selected index of the combo box. See code for what I'm doing in detail, and refer to comments in code:
Dim cboValues As New ComboBox
cboValues.Width = fieldControlWidth
cboValues.DropDownStyle = ComboBoxStyle.DropDownList
cboValues.Name = "cboResult"
For Each d As SystemTaskResult In [Enum].GetValues(GetType(SystemTaskResult))
Dim cv As New ComboBoxDisplayValue(d.ToString, d)
arrValues.Add(cv)
Next
cboValues.DataSource = arrValues
cboValues.DisplayMember = "Display"
cboValues.ValueMember = "Value"
Dim val As SystemTaskResult = DirectCast(p.GetValue(Me.Task, Nothing), SystemTaskResult)
'Was trying to get this to work, but commented out to try the below
'cboValues.SelectedIndex = cboValues.Items.IndexOf(New ComboBoxDisplayValue(val.ToString, val))
'Then this doesn't work because the combo box hasn't updated it's DataSource yet, which is probably the reason for the above not working as well.
For i = 0 To cboValues.Items.Count - 1
cboValues.SelectedIndex = i
If cboValues.SelectedValue = val Then
Exit For
End If
Next
holdPanel.Controls.Add(cboValues)
How to select the right selected index for combo box without a hack (Load timer or something stupid like that)?

Try Form.Shown. See :
How do I execute code AFTER a form has loaded?

Related

The value is not within the expected range

Can we render two UI element at same grid position in SelectionChanged event of a combo box.
The exact problem is i have grid and inside the grid there are two rows the first row will always show me a ComboBox(of which i was talking about line before) on selecting
different item will render different UI elemnts at same position in the second row of the grid.
So i tried to do the rendering of the UI element in the SelectionChanged event of the Combo.
But the problem happening is when i select the first element then it is displayed properly but when i try to select the second UI element to be rendered at same position on Combo selection change then it gives a warning
"the value is not within the expected range." at Line : "bigGrid.Children.Add(ck);"
My code to do this is:
Grid childGrid = createChildGrid();
Grid ck = new Grid(); //This ck will contain ComboBox at row zero and UI element at second row
ck.RowDefinitions.Add(new RowDefinition());
ck.RowDefinitions.Add(new RowDefinition());
int loopCount = 0; //This variable will help in changing the row index
if (loopCount == 0)
{
ComboBox cmb = new ComboBox();
//Here i add items in Combo:
foreach(string ccyp in attributeName)
{
if (ccyp != null)
cmb.Items.Add(ccyp);
}
cmb.SelectionChanged += (o, e) =>
{
txtblkName.Text = cmb.SelectedValue.ToString();
ck = generateUIElementCorrespondingTotxtLabelNameObtainedOnComboSelection(txtblkName.Text); //this function will return a grid containing the selected UI elemnt from combo box.
Grid.SetRow(ck, loopCount);
bigGrid.Children.Add(ck); //**THIS LINE GIVE EXCEPTION: "the value is not within the expected range."**
};
}
Grid.SetColumn(cmb, 1);
childGrid.Children.Add(cmb);
Grid.SetRow(childGrid, loopCount);
bigGrid.Children.Add(childGrid);
loopCount++;// I incrtease loop count so that on selection changed event of combo UI will be displayed on second row loopcount=1
EDIT: On debugging i get :The result of break point is : loopcount=1 (for rendering of combo item in second row)this " Grid.SetRow(ck, loopCount); bigGrid.Children.Add(ck);" and for combo box display loopcount= 0 (i mean here : "Grid.SetRow(childGrid, loopCount); bigGrid.Children.Add(childGrid); loopCount++;")
From question Silverlight: Value does not fall within the expected range exception
'This error can be caused when there are two elements being added with the same name.' What identifiers are added to the combo boxes?
If this is the problem, as suggested in the linked question, you could add a unique identifier to each combo box.

Databound Dropdown not accessible

I took a check box list control in c# and I data-bound it with a table and now I am trying to access its selected items in a string variable using this code and I took a label too so that it can show which values are selected.
string val = this.CheckBoxList1.SelectedItem.ToString();
Label1.Text = val;
on debugging this code I receive no values in string and therefore label doesn't prints anything out of the selected items of the databound checkboxlist.
string text = this.CheckBoxList1.SelectedItem.Text;
string value = this.CheckBoxList1.SelectedItem.Value ;
Have a look at ListControl.SelectedItem

Combo Box Size Issue After All Items Are Removed

My application contains a ComboBox that the user can delete items from. When the program starts up it populates the ComboBox from a list of strings read in from a configuration file.
Here is the code to add items:
// version list is an array of strings
foreach (string version in versionList)
{
versionComboBox.Items.Add(version);
}
if (versionComboBox.Items.Count > 0)
{
versionComboBox.SelectedIndex = 0;
}
Here is a screenshot of the combo box after it's been populated:
If the user clicks the Delete button the program removes the selected item from the ComboBox using the following code:
if (versionComboBox.SelectedIndex >= 0)
{
versionComboBox.Items.Remove(versionComboBox.SelectedItem);
}
if (versionComboBox.Items.Count > 0)
{
versionComboBox.SelectedIndex = 0;
}
Here is a screenshot of the combo box after a few items have been removed:
The problem I am having is when the last item is removed the ComboBox resizes itself to the size it was when it was initially populated. There aren't any items in the ComboBox but it sizes itself as if there were.
Here is a screenshot after all the items have been removed:
As you can see the size is too big. I would think that after all the items were cleared it would look like the following:
Any ideas as to why this is happening?
Try to use this at the end of your code when you are filling the combobox items:
comboBoxNumTreno.IntegralHeight = true; // auto fit dropdown list
Then to clear it up:
comboBoxNumTreno.ResetText();
comboBoxNumTreno.Items.Clear();
comboBoxNumTreno.SelectedIndex = -1;
comboBoxNumTreno.DropDownHeight = 106; // default value
comboBoxNumTreno.IntegralHeight = false;
I know this is an old post, but it took me a long time to figure this out and I wanted to let anyone in the future know. After you clear your combo box just do a blank add items and it resets the height.
comboBox1.Items.Clear();
comboBox1.Items.Add("");
To clear your combo box you can add this:
if (versionComboBox.Items.Count == 0)
{
versionComboBox.Text = string.Empty;
versionComboBox.Items.Clear();
versionComboBox.SelectedIndex = -1;
}
Another approach is to manipulate the items in the data source and rebind the control each time (a lot less for you to worry about).
set DropDownHeight property to fix size
versionComboBox.DropDownHeight = 106; // default value

converting cells into text boxes where check box is checked

I am using mysql and asp.net with c#. I have a grid view which will display dynamically selected table data. I am able to display the data of selected table. In the first column i have added a check box and a Button outside Grid view. When user selects Check box and clicks on button, the selected rows must turn into text boxes. I am able to find the seleted check box, but i'm unable to convert the cells into text boxes. Here's my code:
int n = GridView1.HeaderRow.Cells.Count;
for( int i=0; i < GridView1.Rows.Count;i++)
{
GridViewRow row = GridView1.Rows[i];
bool isChecked = ((CheckBox)row.FindControl("CheckBox1")).Checked;
{
for( int j=0;j<n;j++)
{
TextBox txt = ((TextBox)GridView1.Rows[i].Cells[j]).Text;
}
}
}
At this line: TextBox txt = ((TextBox)GridView1.Rows[i].Cells[j]).Text;
i get a warning :
cannot convert 'System.Web.UI.Controls.TableCell' to type 'System.Web.UI.Controls.TextBox
I am unable to resolve this. Please help. Thank you
Try this.
You can remove one or few lines based on your hands-on with C#.
Concept is, you should create a TextBox, assign cell text that textbox and then Add that newly created textbox to child controls of Grid Cell of particular row.
Mark this solution if you found useful.
bool isChecked = ((CheckBox)row.FindControl("CheckBox1")).Checked;
if(isChecked)
{
for( int j=0;j<n;j++)
{
TextBox tbForCell = new TextBox();
tbForCell.Text = GridView1.Rows[i].Cells[j].Text;
GridView1.Rows[i].Cells[j].Text = "";
GridView1.Rows[i].Cells[j].Controls.Add(tbForCell);
}
}
If you want to avoid the TextBox to appear in CheckBox Column please initialise loop variable j with 1 instead of 0.
for( int j=1;j<n;j++)
Your method call is finding the cell. The Textbox is a control contained within the cell. Try something like this instead:
TextBox txt = ((TextBox) GridView1.Rows[i].Cells[j].FindControl("textbox name")).Text;
The FindControl method is documented here.
Also take #Bartdude's advice about using editable gridviews. If one will work at least as well as what you're trying to hand-roll, it's worth the time learning how to use it.

Setting default item in combo box

I have a function for setting items in a combobox and one item is to be set by default like
--SELECT LIST--
public void SetOperationDropDown()
{
int? cbSelectedValue = null;
if(cmbOperations.Items.Count == 0)
{
//This is for adding four operations with value in operation dropdown
cmbOperations.Items.Insert(0, "PrimaryKeyTables");
cmbOperations.Items.Insert(1, "NonPrimaryKeyTables");
cmbOperations.Items.Insert(2, "ForeignKeyTables");
cmbOperations.Items.Insert(3, "NonForeignKeyTables");
cmbOperations.Items.Insert(4, "UPPERCASEDTables");
cmbOperations.Items.Insert(5, "lowercasedtables");
//ByDefault the selected text in the cmbOperations will be -SELECT OPERATIONS-.
cmbOperations.Text = "-SELECT OPERATIONS-";
}
else
{
if(!string.IsNullOrEmpty("cmbOperations.SelectedValue"))
{
cbSelectedValue = Convert.ToInt32(cmbOperations.SelectedValue);
}
}
//Load the combo box cmbOperations again
if(cbSelectedValue != null)
{
cmbOperations.SelectedValue = cbSelectedValue.ToString();
}
}
Can anyone suggest a way to do this?
I've rewritten this answer to clarify some stuff.
First, the "default" text must be added as combo item as well.
Usage of combo.Text property just adds descriptive text to combobox which is "lost" first time user do something with a control.
If you like to permanently have "default" text in your combo, you must add it as an combobox item.
By the code you provided, just modify the
cmbOperations.Text = "-SELECT OPERATIONS-"; to
cmbOperations.Items.Insert(0, "-SELECT OPERATIONS-");
Note that this way you add the item "-SELECT OPERANDS-" to the 0th (read first) position in the list.
Also make sure that all your following items are increased by 1, because they are now moved by one space down in list.
Finally, put cboOperations.SelectedIndex = 0; line at the end of code. By doing so, you're telling combobox to display your "default" item initially when the form (or control) loads.
One more thing. I'm not pretty sure what do you want to achieve with the code beyond setting combo items, but if you like to check what user selected use cboOperations.SelectedIndex property which contains currently selected item in combo. You can add simple if(cboOperations.SelectedIndex == someIntValue){...}
The rest is your program logic ;)

Categories