I have a form which contains several CheckedListBox items, along with other controls. I'm trying to loop through each the controls and set its property values. Unfortunately, the SetItemChecked property is is not available in the Control class, so I can't figure out how to manipulate the Checked state of the control.
Here's what I have so far:
for (int i = 0; i < Controls.Count(); i++) {
switch(Controls[i].GetType().ToString()) {
case "System.Windows.Forms.TextBox":
case "System.Windows.Forms.RichTextBox":
Controls[i].Text=i.ToString();
break;
case "System.Windows.Forms.CheckedListBox":
Controls[i].SetItemChecked(0,true);
// ^^ This line doesn't work, because SetItemChecked is not available
break;
default:
Controls[i].Tag=i;
break;
}
}
You can cast the Control into a CheckedListBox Like this:
(Controls[i] as CheckedListBox).SetItemChecked(0,true);
I'm not sure of this one, but it might work also:
CheckedListBox myCbList= (ChecekdListBox) Controls[i];
myCbList.SetItemChecked(0,true)
Related
I have a user control (ucMarket) which contains (for the purpose of simplicity) two controls: a ListBox (ucListBox) and a Label (ucLabel). I need to create multiple instances of that user control on the page dynamically (depending on the results from a DataSet), and I add them using a foreach statement and the following:
Panel1.Controls.Add(ucMarket1);
But how do I get access to the ListBox properties like Rows ? The only thing I have found so far is to cast the control as a ListBox:
ListBox listBox1 = (ListBox)ucMarket1.FindControl("ucListBox");
listBox1.Rows = 10;
For the Label part, I guess I can also do something similar:
label1 = (Label)ucMarket1.FindControl("ucLabel");
But then, how do I put that information back into the user control ? Is there a way to work directly with the user control instead of casting ?
Ok a couple of things. from a naming convention point of view, don't call the label & listbox, ucSOMETHING. This is very confusing and not clear from your example whether you're referring to the asp:Label control or some custom userControl you've written. As for accessing your controls.
I'm assuming you are creating and adding a bunch of user controls in the following manner.
for(int i = 0; i < 5; i++)
{
var control = Page.LoadControl("~/Path/To/ucMarket.ascx");
control.Id = "ucMarket" + i;
Panel1.Controls.Add(control);
}
So your best bet is to expose the Listbox on your Control as a public property.
public class ucMarket : UserControl
{
public ListBox TheListBox
{
get { return ucListBox; }
}
}
That way you could access your listbox in the following way.
var ctrl = Panel1.FindControl("ucMarket1") as ucMarket;
ctrl.TheListBox.Rows ;
I've built a Winforms table layout which has many elements in each cell. What I'm trying to do is enumerate all controls of a particular type which I'm concerned with, and remove their corresponding Click values. This something done at runtime, which is why I'm not just setting the controls initial properties.
I've tried working with the Control.ControlCollection property although I've not had much luck, as it's not IEnumerable. Alternative I have the following code but the problem is the control is never found in Controls and a Null Reference exception is thrown because I'm, trying to set .Click on an empty object, but surely this object should exist! Help!?
for (int row = 1; row < tblLayoutPanel.RowCount; row++)
{
for (int column = 0; column < tblLayoutPanel.ColumnCount; column++)
{
Type controlType = tblLayoutPanel.GetControlFromPosition(column, row).GetType();
if (controlType == typeof(CTLLabel) ||
controlType == typeof(OutputLabel))
{
Controls[tblLayoutPanel.GetControlFromPosition(column, row).Name].Click += null;
// Control is never found! *why?*
}
}
}
The reason is that the parent control of the control that you are getting using GetControlFromPosition method is tblLayoutPanel. You are trying to get the child control of the tblLayoutPanel in the parent of the tblLayoutPanel control instead of tblLayoutPanel.Controls collection.
Instead of accessing the control like this, why you don't just use the control you've got by using GetControlFromPosition method. Try this:
tblLayoutPanel.GetControlFromPosition(column, row).Click
I have a form in C# with a drop down box. When that drop down box gets changed, I want it to load a custom user control into a panel. I get no compile errors, no runtime errors, but I also get no visible user control. The idea here is that each user control understands the configuration for a different scenario. I want to encapsulate each scenario in its own control and the drop down box allows the user to select the scenario, which loads the control for the user to perform configuration. By adjusting the options in the drop down, I can customize what scenarios a given customer has. As I said, my problem is I cannot get any of the controls to become visible. This is the code I am using for the drop down index change event handler:
private void ddlCollectorType_SelectedIndexChanged (object sender, EventArgs e)
{
m_currentControl = null;
pnlDeviceConfig.Controls.Clear ();
switch ((string) ddlCollectorType.SelectedItem)
{
case "SEL-421":
SEL421ASCIIControl s421 = new SEL421ASCIIControl (this);
m_currentControl = s421;
pnlDeviceConfig.Controls.Add (s421);
break;
case "SEL-421 (FTP)":
break;
case "GE D60":
GED6061850Control geD60 = new GED6061850Control (this);
m_currentControl = geD60;
pnlDeviceConfig.Controls.Add (geD60);
break;
case "GE D60 (TFTP)":
break;
case "MiCOM P442":
break;
}
}
I've only created a couple of the user controls so far, hence the empty case statements. When I make selections that should show me something, I get nothing (confirmed in the debugger that I am hitting the case statement body). Any help will be greatly appreciated!
To follow up on my comment, I'm guessing that the position and/or dimensions of your control are not set.
Try something like:
...
SEL421ASCIIControl s421 = new SEL421ASCIIControl (this);
m_currentControl = s421;
pnlDeviceConfig.Controls.Add (s421);
// TODO: Set real size and position.
s421.Left = 0;
s421.Top = 0;
s421.Width = 100;
s421.Height = 50;
break;
...
You also may use the Dock and Anchor properties of your control.
1 You can replace your Menu with PlaceHolder, he is ideal control for adding controls
here an example : http://www.developerfusion.com/code/3826/adding-controls-to-placeholders-dynamically/
2 And for your case you can try to adjust visible property of panel to true
I am using student record entry window form. I want that after submitting data, all fields of form(i.e radio button, combobox etc) and messages(warning and successful) should be reset so that new user can add data.
is their any built in function to reset form in csharp?
or I have to write clear method for this?
or can I regenerate the form?
You must first clear the controls and then use InitializeComponent method to work perfectly.
this.Controls.Clear();
this.InitializeComponent();
This you can achieve in two ways:-
1) you can clear the fields of the form in one method. say public void clear() And whenever you want to clear the form simply call this method.
2) In second way you can destory the instance of the form and generate the new instance of the same form and then show this.
I will recomeded 1st one for you.
This is what I used to create in my every page
private void ClearControls()
{
try
{
txtUserName.Text = string.Empty;
//txtPassword.Text = string.Empty;
txtFName.Text = string.Empty;
txtMName.Text = string.Empty;
txtLName.Text = string.Empty;
lblUserType.Text = string.Empty;
btnSave.Text = "Save";
fnMessage(false, "");
}
catch (Exception ex)
{
fnMessage(true, ex.Message);
}
}
Thanks
Implement data binding to a given object (good starting point here)
For resetting the form, create a new object and the binding will do it for you.
HTH
You can either re-create the form instance, or perhaps try something similar to this (untested):
foreach (Control ctl in this.Controls)
{
switch (ctl.GetType().ToString())
{
case "TextBox":
ctl.Text = null;
break;
case "ComboBox":
ctl.Text = null;
break;
}
}
Clearly, you can include as many different types of control as you wish and introduce other critieria (i.e. where control name begins with 'xyz' or where control resides within a particular panel).
Compared to other suggestions, the advantage of this approach is that if you have dozens of the same control type (typically textboxes), a few lines of code cover the lot. Additionally, if you add more controls of the covered types, you don't need to revisit the code to update it. Perhaps you could even create it as an extension method of your forms?
If form creation doesn't take too much resources it is easier to create new instance.
As i had same problem and my from was having nested controls. I tried CJM's method and it worked however i had to write a recursive function because of controls nesting (tab controls, containers, user controls etc)
Try out the following snippet if you want to clear whole form recursively
private void clearRecursive(Control control)
{
foreach (Control subcontrol in control.Controls)
{
switch (subcontrol.GetType().ToString().Replace("System.Windows.Forms.", ""))
{
case "TextBox":
TextBox textBox = (TextBox)subcontrol;
textBox.Text = null;
break;
case "ComboBox":
ComboBox comboBox = (ComboBox)subcontrol;
if (comboBox.Items.Count > 0)
comboBox.SelectedIndex = 0;
break;
case "CheckBox":
CheckBox checkBox = (CheckBox)subcontrol;
checkBox.Checked = false;
break;
case "RadioButton":
RadioButton radioButton = (RadioButton)subcontrol;
radioButton.Checked = false;
break;
case "TreeView":
TreeView tv = (TreeView)subcontrol;
foreach (TreeNode node in tv.Nodes)
{
node.Checked = false;
CheckChildren(node, false);
}
break;
case "ListBox":
ListBox listBox = (ListBox)subcontrol;
listBox.Items.Clear();
break;
case "CheckedListBox":
CheckedListBox chklstbox = (CheckedListBox)subcontrol;
for (int i = 0; i < chklstbox.Items.Count; i++)
{
chklstbox.SetItemCheckState(i, CheckState.Unchecked);
}
break;
}
if (subcontrol.HasChildren)
clearRecursive(subcontrol);
}
}
Call InitializeComponent method and Form_Load method.
I use Difference class as my datasource in treelist. Then I would like to show different icon with node according to property value of the type Difference. Here is my Code:
treeList1_GetStateImage(object sender, DevExpress.XtraTreeList.GetStateImageEventArgs e)
{
TreeListColumn tlColumn = treeList1.Columns["DifferenceType"];
DifferenceTypeEnum differenceType = (DifferenceTypeEnum)e.Node.GetValue(tlColumn);
switch (differenceType)
{
case DifferenceTypeEnum.Added:
e.NodeImageIndex = 0;
break;
case DifferenceTypeEnum.Deleted:
e.NodeImageIndex = 1;
break;
case DifferenceTypeEnum.Modified:
e.NodeImageIndex = 2;
break;
default:
throw new Exception("Difference with not specified type");
}
I would like to have the same icons when selected and when not selected and thats all, nothiung else, but now each time I click on a node NodeImageIndex is changed to 0, WHen nodes arent selected everything work fine,
ehh Im tired of this ...
thanks for any help
I would suggest that you also handle the GetSelectImage event to define which image should be shown when a certain node is selected.
I just want to know how can I connect specified icon with node according to the property of the type. Lests say Im bound to the fruit list andd if fruit has gaot typoe property set to banana let the image be banana.png if apple then apple.png and so on :)
imageCollection connectied with this treelist has got these images with corresponding indexes.