How to set value property of NumericUpDown from a string value? - c#

I want to get values from a selected row of DataGridView and assign them into a few different
controls on a Form when a control's name match a column's name (there is TextBox, ComboBox and NumericUpDown).
This is how I am populating the controls currently:
Form myForm = new Form();
if (comboBoxTable.Text == "Client")
{
myForm = new EditClientDataWindow();
}
else if (comboBoxTable.Text == "Agency")
{
myForm = new EditAgencyDataWindow();
}
else if (comboBoxTable.Text == "Medicine")
{
myForm = new EditMedicineDataWindow();
}
string val;
foreach (Control c in myForm.Controls)
{
for (int i = 0; i < dataGridViewMDB.ColumnCount; i++)
{
val = dataGridViewMDB.SelectedRows[0].Cells[i].Value.ToString();
if (dataGridViewMDB.Columns[i].Name.ToString() ==
c.Name.ToLower().Replace(c.GetType().ToString().ToLower().Replace("system.windows.forms.", ""), ""))
{
if (c is NumericUpDown)
(c as NumericUpDown).Value = Convert.ToInt32(val);
else
c.Text = val;
}
}
}
With the exception of NumericUpDown, the other types of controls are correctly populated. For the NumericUpDown, I only ever get the default -1 value. I've also tried to use decimal.Parse() and Convert.ToDecimal() instead of Convert.ToInt32(), but there is no change in the result.
The range of NumericUpDown had been set to -1 and 999.

It's not an answer, but a way to reduce a space for error searching, because it's a lot of things going on under the hood.
Can you please change your code to
foreach (Control c in myForm.Controls)
{
if (c is NumericUpDown)
(c as NumericUpDown).Value = 12;
else
c.Text = "12";
}
After this all controls should be set to 12. Can you please test it and get back with the observations.

Related

Variable in C# for loop

I have got many buttons in my Application Form. And I would like to check every buttons text (compare). How can I achive that ?
for (i = 1; i < 30; i++)
{
if (this.button1.Text == "Hello") //here is PROBLEM
{
//..some statement
}
}
So next time this.button1.Text must change to this.button2.Text and so on...
this.button[i].Text not working.
Buttons are not arrays. Each one is a discreet object, and a child of its container.
Ideally, you need to build a collection (array, list, whatever) of the buttons and iterate through that collection, rather than using an index variable (i).
Here's a good approach: https://stackoverflow.com/a/3426721/820068
This is a correct syntax:
foreach (Control button in this.Controls)
{
if (button.GetType() == typeof(Button) && button.Text == "Hello")
{
//..some statement
}
}
I'm quite sure that this is a windows form.
And in windows form you can iterate the controls like this.
foreach (Control c in panel.Controls)
{
string cType = c.GetType().ToString();
// check all buttons
if (cType == "System.Web.UI.WebControls.Button")
{
if(((Button)c).Text == "Hello")
{
}
}
}
So what the code does is to iterate all the controls inside a panel and check each control if it's type is a button.
Update:
As Wesley said, much better approach for the condition is to implement it like this
if (c is Button && c.Text.Equals("Hello")) {
for (int i = 1; i < 3; i++)
{
var buttonName = "button" + i;
Button button = this.Controls.Find(buttonName, true).FirstOrDefault() as Button;
string text = button.Text;
}
try this code.

Make multiple Textboxes visible or invisible using for loop

In my form I've 50 textboxes in visible=false state, when a user enter particular number , those many textboxes should be displayed and the remaining textboxes should remain in visible false state.
Should end up looking something like this:
foreach (var control in this.Controls)
{
var textbox = control as TextBox;
if (var != null) textbox.Visible = true;
}
You can loop throug all textbox controls like this:
foreach (Control item in this.form1.Controls)
{
System.Web.UI.HtmlControls.HtmlInputText tbx = item as System.Web.UI.HtmlControls.HtmlInputText;
if (tbx!= null)
{
if(tbx.Text == "some text")
tbx.Visible = false; // or true how ever you want it
else
tbx.Visible = true;
}
}
So if tbx is not null, item is textbox, actually:
<input type="text"/>
You can do this same trick with other HtmlControls.
Change form1 to that form you, which controls you want to loop through.
You can wrap all your control inside a Asp.net Panel Control.
int counter = 0;
int numberOfTextBoxtoShow = 4; // set by user
foreach (Control c in Panel1.Controls)
{
if (c is TextBox)
{
if (counter < numberOfTextBoxtoShow)
{
c.Visible = true;
counter++;
}
else c.Visible = false;
}
}

Problem with the DevExpress XtraGridView control

I have one xtragrid control on my devxpress form . I've created the columns of my grid at runtime when i load the form . I'm developing the Field chooser for my grid view which is situated on the same form. For that i used the repositoryItemCheckedComboBoxEditcontrol & in that control i added the column names which will be present in the xtragrid.
Basically i created the columns to the xtragrid with the Visible property to false. When user checks particular column name by using repositoryItemCheckedComboBoxEdit then i set the Visible to true & again if user unchecked the column name then again i set the visible to false. & while creating column i set the width of the column.
Problem which i'm facing is that if user select the all fields from the repositoryItemCheckedComboBoxEdit then the grid control should show the horizontal scroll bar automatically when require.
And another problem is that with the columns is besides setting the width of the column, it is not showing the required width of that column . it shrinks that all column width .
code which i use for creating column to the xtragridview at run time is as follows -
public void AddGridColumn(string fieldName, string caption, int nRowWidth, RepositoryItem Item, object oCollection, string DisplayMember, string ValueMember, string format, FormatType type)
{
DevExpress.XtraGrid.Columns.GridColumn column = ColumnView.Columns.AddField(fieldName);
column.Caption = caption;
column.ColumnEdit = Item;
column.DisplayFormat.FormatType = type;
column.DisplayFormat.FormatString = format;
column.VisibleIndex = ColumnView.VisibleColumns.Count;
column.Width = nRowWidth;
}
code for the field chooser is as follows -
I used this function for filling the items of the repositoryItemCheckedComboBoxEdit control
private void FieldCollection()
{
allFields = new ArrayList();
columnNames = new Dictionary<string, string>();
allFields.Clear();
repositoryItemCheckedComboBoxEdit1.Items.Clear();
for (int i = 0; i < gvBase.Columns.Count; i++)
{
allFields.Add(gvBase.Columns[i].Caption );
if (gvBase.Columns[i].FieldName != "ContactID")
{
if (gvBase.Columns[i].Visible == true)
{
if (gvBase.Columns[i].Caption != "Label1" && gvBase.Columns[i].Caption != "Label2" && gvBase.Columns[i].Caption != "Label3" && gvBase.Columns[i].Caption != "Label4" && gvBase.Columns[i].Caption != "Label5")
repositoryItemCheckedComboBoxEdit1.Items.Add(gvBase.Columns[i].Caption, CheckState.Checked);
if (!columnNames.ContainsKey(gvBase.Columns[i].Caption))
columnNames.Add(gvBase.Columns[i].Caption, gvBase.Columns[i].FieldName);
}
else
{
if (gvBase.Columns[i].Caption != "Label1" && gvBase.Columns[i].Caption != "Label2" && gvBase.Columns[i].Caption != "Label3" && gvBase.Columns[i].Caption != "Label4" && gvBase.Columns[i].Caption != "Label5")
repositoryItemCheckedComboBoxEdit1.Items.Add(gvBase.Columns[i].Caption, CheckState.Unchecked);
if (!columnNames.ContainsKey(gvBase.Columns[i].FieldName))
columnNames.Add(gvBase.Columns[i].Caption, gvBase.Columns[i].FieldName);
}
}
}
cmbFieldChooser.EditValue = "";
}
this is used for the repositoryItemCheckedComboBoxEdit control event -
private void cmbFieldChooser_EditValueChanged(object sender, EventArgs e)
{
ArrayList temp = new ArrayList();
temp.AddRange(allFields);
string[] strFields = cmbFieldChooser.EditValue.ToString().Split(',');
for (int i = 0; i < strFields.Length; i++)
{
if (temp.Contains(strFields[i].Trim()))
temp.Remove(strFields[i].Trim());
if (strFields[i] != "")
{
if (columnNames.ContainsKey(strFields[i].Trim()))
{
if (gvBase.Columns[columnNames[strFields[i].Trim()]].Visible == false)
{
gvBase.Columns[columnNames[strFields[i].Trim()]].Visible = true;
gvBase.Columns[columnNames[strFields[i].Trim()]].BestFit();
}
}
}
}
if (temp.Count < 20)
{
for (int j = 0; j < temp.Count; j++)
{
if (columnNames.ContainsKey(temp[j].ToString().Trim()))
{
gvBase.Columns[columnNames[temp[j].ToString().Trim()]].Visible = false;
}
}
}
cmbFieldChooser.EditValue = repositoryItemCheckedComboBoxEdit1.GetCheckedItems();
if ((cmbFieldChooser.EditValue.ToString()).Split(',').Length > 5)
{
gvBase.OptionsView.ColumnAutoWidth = false;
gvBase.BestFitColumns();
gvBase.HorzScrollVisibility = ScrollVisibility.Always;
}
else
{
gvBase.OptionsView.ColumnAutoWidth = true;
gvBase.HorzScrollVisibility = ScrollVisibility.Never;
}
}
How to resolve this problem?
thanks.
How many columns do you have in your Grid?
I see you have code there to turn off the ColumnAutoWidth once you go past 5 columns (ie 6 columns or more). Have you debugged this condition to ensure the ColumnAutoWidth is indeed being turned off?
As per BestFitColumns Help Doc the BestFitColumns will only calculate for the first n rows as per the BestFitMaxRowCount property unless it it set to -1, could this be a cause?
The other thing that seems a little odd if that you are setting the EditValue of cmdFieldChooser within the cmdFieldChooser_EditValueChanged event... why so?

ASP.net -- Identifying a specific control in code behind

I have a page that holds 5 texboxes each name similar but with a numerial suffix. Example:
tbNumber1, tbNumber2, tbNumber3 and so on.
The reason it's like that is because those textboxes are generated dynamically based on some parameter. I never know how many textboxes will be need for a particular record.
How can I loop trough the text contents of these texboxes?
MY first instinct was to do something like the following, but that obviously does't work :)
for (int i = 0; i <= 3; i++)
{
string foo = tbNumber+i.Text;
//Do stuff
}
Wahts the best way to go trough each of these textboxes?
Thanks!!!
You might be able to do something like this:
for( int i = 0; i < upperLimit; i++ )
{
TextBox control = Page.FindControl("tbNumber" + i) as TextBox;
if( control != null ) {
// do what you need to do here
string foo = control.Text;
}
}
Possibly try something like
foreach(Control control in Page.Controls)
{
//Do stuff
}
If you're generating them dynamically, put them in a List<TextBox> as you generate them:
// in the Page_Load or whereever you generate the textboxes to begin
var boxes = new List<TextBox>();
for (int i = 0; i < numRecords /* number of boxes */; i++) {
var newBox = new TextBox();
// set properties here
boxes.Add(newBox);
this.Controls.Add(newBox);
}
Now you can loop through the textboxes without using crufty string techniques:
foreach (var box in boxes) {
string foo = box.Text;
// stuff
}
What you need is a recursive FindControl like function. Try something like this:
for (int i=0; i<3; i++)
{
Control ctl = FindControlRecursive(Page.Controls, "tbNumber", i.ToString());
if (ctl != null)
{
if (ctl is TextBox)
{
TextBoxControl tbc = (TextBox)ctl;
// Do Something with the control here
}
}
}
private static Control FindControlRecursive(Control Root, string PrefixId, string PostFix)
{
if (Root.ID.StartsWith(PrefixId) && Root.ID.EndsWith(PostFix))
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, PrefixId, PostFix);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
If you're using a CheckBoxList control you should be able to loop through each checkbox in the control.
foreach(var checkbox in checkboxlistcontrol)
{
string name = checkbox.Text;
}
If you're not using a CheckboxList control, you might want to consider using one as an option.

dynamically call a control

Let's say I have 30 controls, all lbls, all called "lblA" with a number after.
I also have 30 textboxes, same thing - called "txtB" with a number after.
How exactly would I formated this.
for (i = 1; i < this.controls.count;i++)
{
if ("lblA"+i=null)
{
break;
}
string A = string A + ("lblA" + i).Text
string B = string B + ("txtB" + i).Text
}
I've tried a few different things like calling the object with this.controls[i] but it's not exactly what I want. What I am doing is I have a lot of labels and text boxes in a form that are added at run time. I need to loop through the form to get them all. I'm writting it as a for each with quite a few ifs, but I'm curious if there's a dynamic way to do it.
I've looked for about 1-1:30 hours online and found nothing close to, thanks for the help all.
var labels = new Dictionary<int, string>();
for (i = 1; i < this.controls.count;i++)
{
var label = FindControl("lblA" + i) as Label;
if (label == null)
{
break;
}
labels.Add(i, label.Text);
}
What you want to use is the FindControl method.
Example in VB:
Dim txtMileage As TextBox = CType(cphLeft.FindControl("txtMileage" & iControlCountDays.ToString()), TextBox)
Maybe this will solve what you're after:
void GetSpecialControls() {
const string TXT_B = "txtB";
const string LBL_A = "lblA";
List<TextBox> textBoxList = new List<TextBox>();
List<Label> labelList = new List<Label>();
foreach (Control ctrl in this.Controls) {
Label lbl = ctrl as Label;
if (lbl != null) {
if (lbl.Text.IndexOf(LBL_A) == 0) {
labelList.Add(lbl);
}
} else {
TextBox txt = ctrl as TextBox;
if (txt != null) {
if (txt.Text.IndexOf(TXT_B) == 0) {
textBoxList.Add(txt);
}
}
}
}
Console.WriteLine("Found {0} TextBox Controls.", textBoxList.Count);
Console.WriteLine("Found {0} Label Controls.", labelList.Count);
}

Categories