I'm trying to do this:
read multiple values from Windows registry (works). This looks like
\HKLM\...\Server1
int serverid 1
string serverName "SRVSQL01"
int serverport 1433
string database "MyDatabase1"
\HKLM\...\Server2
dword/int serverid 2
regsz/string serverName "SRVSQL02"
dword/int serverport 1433
regsz/string database "MyDatabase2"
The number of servers can vary.
List items. I can read the values from the registry, this works fine
Add values to multiple instances of a C# class (works)
I created a class "SQLServer" with 4 variables/values, as displayed above.
Then I create an array of multiple instances of this class, for example if there are 4 servers listed in the registry, I generate an array with length 4 and add the value of each server to its own entity of this class.
public class RegSQLListItem
{
public int MSSSQLID;
public string MSSQLServer;
public int MSSQLPort;
public string MSSQLDatabase;
}
display the list in a new Form by generating radio buttons, based on the number of "items" in an array.
I found some code here to dynamically generate a list of radio buttons with labels: https://msdn.microsoft.com/en-us/library/dwafxk44(v=vs.90).aspx
// Generate form
int ProjectCounter = (RegProjectRoot.GetSubKeyNames()).Count();
// other code
RadioButton[] radioButtons = new RadioButton[ProjectCounter];
for (int i = 0; i < ProjectCounter; ++i)
{
radioButtons[i] = new RadioButton();
radioButtons[i].TabIndex = i + 1;
radioButtons[i].Name = ProjectListItem[i].MSSQLDatabase;
radioButtons[i].Text = ProjectListItem[i].MSSQLDatabase;
radioButtons[i].Location = new System.Drawing.Point(10, 10 + i * 20);
this.Controls.Add(radioButtons[i]);
}
How can I capture which radio button is selected and how to I transfer the corresponding value to another routine in my program?
I'm particularly interested in clicking an "OK" button to capture the value of the currently active radio button and so select which database I want to connect to.
Is this a correct way to do this at all or is there an easier way?
I'm new to C#, so I'm not that familiar with the possibilities.
You can do this in two ways.
1. Add event handler like the following:
for (int i = 0; i < ProjectCounter; ++i)
{
radioButtons[i] = new RadioButton();
radioButtons[i].TabIndex = i + 1;
radioButtons[i].Name = "ProjectListItem[i].MSSQLDatabase";
radioButtons[i].Text = "ProjectListItem[i].MSSQLDatabase";
radioButtons[i].Location = new System.Drawing.Point(10, 10 + i * 20);
radioButtons[i].CheckedChanged += new EventHandler(rdo_CheckedChanged);
this.Controls.Add(radioButtons[i]);
}
And the Handler rdo_CheckedChanged will defined like the following:
private static void rdo_CheckedChanged(object sender, EventArgs e)
{
RadioButton rdoButton = sender as RadioButton;
if (rdoButton.Checked)
{
// procced the button is checked
}
}
2. Iterate through controls of type RadioButton
You can iterate through the controls and identify the selected radio button by using the following code:
foreach (RadioButton rdo in this.Controls.OfType<RadioButton>())
{
if (rdo.Checked)
{
// this is checked radio button
// Proceed with your code
}
}
Related
I have an array of button created dynamically, suppose 8 buttons, what I want is that when I click a particular button its background picture is changed and the name of button is stored in a linked list. When I click the same button again the background picture goes back to the original and the button name is deleted from linked list. Now I am able to do the first part, the second click is not working as I want it to.
Basically it's a datastructures project (shopping store) therefore I am using linked list, I have a linked list whose content is displayed through picture boxes[] and labels. Here what i am trying to do is when I click the picture box, the content of that particular node is added to a new linked list (added to the cart) and when I click on the picturebox again that particular item is deleted from the linked list (removed from the cart). Clicking it for the first time it is doing what i want it to do but the second click is not really working.
It's a datastructures project therefore I can't really use any built in classes for linked list, I had to write all methods myself and I did and they work.
cb[i].Click += (sender, e)=>{
if (flag == 0) {
// Console.WriteLine(obj.Retrieve(index).NodeContent);
// Console.WriteLine(obj.Retrieve(index).number);
inv.Add(obj.Retrieve(index).NodeContent, obj.Retrieve(index).number);
bill += Convert.ToInt32(obj.Retrieve(index).number);
cb[index].Image = Image.FromFile(#"F:\uni work\3rd semester\project images\rcart.jpg");
flag++;
}
else if (flag == 1)
{
// Console.WriteLine(bill);
bill -= Convert.ToInt32(obj.Retrieve(index).number);
// Console.WriteLine(bill);
inv.Delete(index);
cb[index].Image = Image.FromFile(#"F:\uni work\3rd semester\project images\cart.png");
flag--;
}
Since you are using a LinkedList it does have a Contains Method and a Remove Method that take a string. You haven't specified exactly what your problem is this should work. When you assign images to a control you loose the information that tells you what Image it is.
public partial class Form1 : Form
{
LinkedList<String> myList = new LinkedList<String>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 8; i++)
{
Button b = new Button() { Height = 30, Width = 70, Location = new Point(i, 50 * i),Name = "NewButton" + (i + 1).ToString() , Tag=i};
b.Click += b_Click;
this.Controls.Add(b);
}
}
void b_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if(myList.Contains(b.Name)) //Check if button is in the List then Change Picture and remove
{
b.BackgroundImage = Properties.Resources.Peg_Blue;
myList.Remove(b.Name);
}
else
{
b.BackgroundImage = Properties.Resources.Peg_Red;
myList.AddLast(b.Name);
}
}
}
Why not create a class for each button, containing the two images and switch between them on each click?
I have a method that adds items to my listbox called refreshInterface which is called as soon as the programe starts, adding names of homeforms in the listbox using the FormItems class, here is the rereshInterface method below
public void refreshInterface()
{
//int number = 0;
foreach (DataSet1.xspGetAnalysisUsageTypesRow homeForms in myDataSet.xspGetAnalysisUsageTypes)
{
var forms = new FormItems(homeForms);
listBox1.Items.Add(forms);
}
}
The FormItems class is this below
public class FormItems
{
public DataSet1.xspGetAnalysisUsageTypesRow types { get; set; }
public FormItems(DataSet1.xspGetAnalysisUsageTypesRow usageTypes)
{
types = usageTypes;
}
public override string ToString()
{
// returns the rows that are relating to types.xlib_ID
var libtyps = types.GetxAnalysisUsageRows();
var cnt = 0;
foreach (DataSet1.xAnalysisUsageRow ty in libtyps)
{
//returns true if ty is null
bool typeNull = ty.Isxanu_DefaultNull();
// if its false, if xanu_Default is set
if (!typeNull)
{
cnt += 1;
}
}
var ret = String.Format("set {0} [Set: {1}]", types.xlib_Desc, cnt);
//return this.types.xlib_Desc;
return ret;
}
}
Each listbox (the listbox is on the left of the homeform) item has a number of reports that can be added to it, so for instance, i select an homeform from my listbox, there are 12 textboxes on the right hand side and each textbox has a pair of buttons which are Browse and Clear. If I click on the browse button a new form appears, and i select a report from that form and add it to a particular textbox, the count for that homeform should update, and i clear a textbox for a particular homeform, the count should also update.
At the moment when i debug the application, it shows me the count of each Homeform depending on the amount of reports added to the homeform, but while the programe is running, if i add a new report to a homeform, the count does not update until i restart the debug session. I was told about using a Databinding method but not sure of how i could use it here
How do i ge my listbox item to update ?
You should probably look into binding. Here is a good place to start:
http://www.codeproject.com/Articles/140621/WPF-Tutorial-Concept-Binding
If you want a GUI to respond to data changes then binding is your best friend.
You should bind List Box component source to Observable Collection, every update you do to Observable Collection will update List Box data.
Might not be exact but should give you an idea.
public void refreshInterface()
{
Dictionary<int,string> items = new Dictionary<int,string>();
//int number = 0;
foreach (DataSet1.xspGetAnalysisUsageTypesRow homeForms in myDataSet.xspGetAnalysisUsageTypes)
{
var formitem = new FormItems(homeForms);
items.Add(formitem.someprop, formitem.toString());
}
listbox.DataSource = items;
listbox.DisplayMember = "Value";
listbox.ValueMember = "Key";
}
I work on windows application. It has one form in application which displays check boxes in check box list, here is the screen shot of form
It's single from of my application which i display in different languages And also my windows application is made in multiple languages Like English, German, Japanese etc..
My problem is that how to display translated text of check box in check box list
Here is my code :
this.checkedListBox1.FormattingEnabled = true;
this.checkedListBox1.Items.AddRange(new object[] {
"Select All",
"Amplitude1",
"Amplitude2",
"Amplitude3",
"Amplitude4",
"Amplitude5",
"Amplitude6",
"Amplitude7"});
this.checkedListBox1.Location = new System.Drawing.Point(96, 55);
this.checkedListBox1.Name = "checkedListBox1";
this.checkedListBox1.Size = new System.Drawing.Size(123, 124);
this.checkedListBox1.TabIndex = 8;
this.checkedListBox1.SelectedIndexChanged += new System.EventHandler(this.ckbselectall_CheckedChanged);
I made a single file to translate text of form, i put that code below where LCheckBox is my file from where i translate the text of check box in check box list
this.checkedListBox1.FormattingEnabled = true;
this.checkedListBox1.Items.AddRange(new object[] {
LCheckBox.SELECTALL,
LCheckBox.Amplitude1,
LCheckBox.Amplitude2,
LCheckBox.Amplitude3,
LCheckBox.Amplitude4,
LCheckBox.Amplitude5,
LCheckBox.Amplitude6,
LCheckBox.Amplitude7});
this.checkedListBox1.Location = new System.Drawing.Point(96, 55);
this.checkedListBox1.Name = "checkedListBox1";
this.checkedListBox1.Size = new System.Drawing.Size(123, 124);
this.checkedListBox1.TabIndex = 8;
this.checkedListBox1.SelectedIndexChanged += new System.EventHandler(this.ckbselectall_CheckedChanged);
But it gives me some error message
you can ask for the language at the begining and then create the checkbox list depending on the language. u can use different if cases for each language
In code I just use the items collection to modify the desired item.
So lets say you have a form with a button on it. When the button is clicked
you want to add one to all the items in the list, then the code to do that
would look as found below assuming that the listbox was named "_list" and
the button was named "_button."
private void FillList()
{
_list.BeginUpdate();
_list.Items.Clear();
for(int i =0 ; i <=9; i++)
_list.Items.Add(i);
_list.EndUpdate();
}
private void _button_Click(object sender, System.EventArgs e)
{
_list.BeginUpdate();
ListBox.ObjectCollection items = _list.Items;
int count = items.Count;
for(int i = 0; i < count; i++)
{
int integerListItem = (int)items[i];
integerListItem ++;
// --- Update The Item
items[i] = integerListItem;
}
_list.EndUpdate();
}
I am creating an application where a user will input grades and the program will output the weighted average. On load, it will ask for the number of categories for the assignments. The program will then dynamically create textboxes for the user to input information. The problem is that I can not figure out how to read the text that is inputed after I create the textboxes. Here is my code:
TextBox txtbx = new TextBox();
txtbx.Text = "";
txtbx.Name = "txtbx1";
txtbx.Location = new Point(10, 10);
txtbx.Height = 20;
txtbx.Width = 50;
Controls.Add(txtbx);
How can I change this code so I can find the current text in the box when the user submits?
If you are dynamically generating controls then obviously you won't be able to have a field for each one. But if you are trying to access the Controls collection for a named control, the ControlCollection can be indexed by name. After adding the text box with the specified name, you can simply do:
TextBox txtbx = (TextBox)Controls["txtbx1"];
You could use the FindControl method of the Page class.
This method takes a parameter which is the TextBox's ID, which you have to set upon creation:
txtbx.ID = "txtbx1";
Then you can select it:
TextBox txtbx1 = (TextBox)FindControl("txtbx1");
and use it.
Edit: Since the initial question added that he is refering to Windows Forms, my reply above is off-topic.
In Windows Forms, you should simply use a class member variable instead of a local variable. E.g.:
public partial class MyForm
{
...
private TextBox txtbx;
...
private void createControls()
{
txtbx = new TextBox();
txtbx.Text = "";
txtbx.Name = "txtbx1";
txtbx.Location = new Point(10, 10);
txtbx.Height = 20;
txtbx.Width = 50;
Controls.Add(txtbx);
}
private void someOtherFunction()
{
// Do something other with the created text box.
txtbx.Text = "abc";
}
}
This code for the Dynamically Add Textbox On Button Click
int count = 1;
public System.Windows.Forms.TextBox AddNewTextBox()
{
System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
this.Controls.Add(txt);
txt.Top = count * 25;
txt.Left = 100;
txt.Text = "TextBox " + this.count.ToString();
count = count + 1;
return txt;
}
private void Onbutton_Click(object sender, EventArgs e)
{
//Call the method AddNewTextBox that uses for Dynamically create Textbox
AddNewTextBox();
}
I hope this code will help you .
Thank You
Happy Coding:)
Keep a list of references of all text boxes on the form. Add the textBox reference to the list when you create them dynamically.
Then you can simply iterate through all text boxes in the list when you want to read their text.
Make sure that you name the text boxes as per their related category names. Then you can also Find the control in the list by their names.
class MyForm : Form
{
IList<TextBox> _textBoxes = new List<TextBox>();
private void AddTextBox(string categoryName){
var myTextBox = new TextBox();
myTextBox .Name = categoryName + "txtbx";
// set other properties and add to Form.Controls collection
_textBoxes.Add(myTextBox);
}
private TextBox FindTextBox(string categoryName)
{
return _textBoxes.Where( t => t.Name.StartsWith(categoryName)).FirstOrDefault();
}
}
All you need to do is set up an OnClick listener for your submit button and have it do something like this
private void OnSubmit(object sender, EventArgs args)
{
string yourText = txtbx.Text;
}
You'll have to keep a reference to the text box after you create it. yourText will contain the value you need. Hope this helps
I have an input field on my page where the user will type in the number of text inputs they want to create. The action for the button is:
int num_flds = int.Parse(a_fld.Text);
for (int i = 0; i < num_flds; i++)
{
TextBox tmp = new TextBox();
tmp.ID = "answer_box" + i;
tmp.Width = Unit.Pixel(300);
answer_inputs.Controls.Add(tmp);
}
Now, I have another button that the user would click after they have filled in all their dynamically-created text boxes. Questions, first of all, am I creating the text boxes dynamically in the correct place? How would I get the values out of the dynamically-created text boxes? (The dynamically-created text boxes are being added to the Panel "answer_inputs".
I recommend reading this and a few other articles about the topic of dynamically created controls. It is not quite as straightforward as you might think. There are some important page lifecycle issues to consider.
When creating web controls dynamically, I find it best to have the controls themselves report in the answers. You can achieve it like this:
Create something in your Page class to store the values:
private readonly Dictionary<TextBox, string> values=new Dictionary<TextBox, string>();
Make a method to act as a callback for the textboxes when their value changes:
void tmp_TextChanged(object sender, EventArgs e)
{
TextBox txt = sender as TextBox;
if(txt!=null)
{
values.Add(txt,txt.Text);
}
}
And then add this method to each textbox as they are added:
int num_flds;
if(!int.TryParse(a_fld.Text,out num_flds))
{
num_flds = 0;
}
for (int i = 0; i < num_flds; i++)
{
TextBox tmp = new TextBox();
tmp.ID = "answer_box" + i;
tmp.Width = Unit.Pixel(300);
answer_inputs.Controls.Add(tmp);
tmp.TextChanged += tmp_TextChanged;
}
Finally, you iterate through the dictionary on callback to see if it holds any values. Do this in the OnPreRender method for instance.
Edit: There is a problem with this, if the number of text fields are decreased on postback. Some safe way to recreate the previous textfields on postback should be employed.