C# Form Dynamic Controls - c#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DENEME1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label1.Text += "1 ";
}
else if (radioButton2.Checked)
{
label1.Text += "2 ";
}
else if (radioButton3.Checked)
{
label1.Text += "3 ";
}
else if (radioButton4.Checked)
{
label1.Text += "4 ";
}
.....
.....
.....
.....
}
}
}
If i have more than 10 radio buttons how can i control which one are selected. I tried it like above but i think that it isn't the correct way. How can i make it better? For example if i have 100 radio buttons how can i get the selected one?

Here is an option
RadioButtons are in panels (border is to show this)
Originally each RadioButton text was radioButtonn
There is no logic here to decide which RadioButton may or may not be checked, only provides a list to work with.
String extension needed
public static class StringExtensions
{
public static string Numbers(this string sender) =>
Regex.Replace(sender, "[^0-9 _]", "");
}
Control extensions
public static class ControlExtensions
{
public static IEnumerable<T> Descendants<T>(this Control control) where T : class
{
foreach (Control child in control.Controls)
{
T thisControl = child as T;
if (thisControl != null)
{
yield return (T)thisControl;
}
if (child.HasChildren)
{
foreach (T descendant in Descendants<T>(child))
{
yield return descendant;
}
}
}
}
public static List<RadioButton> RadioButtonList(this Control control) =>
control.Descendants<RadioButton>().ToList();
public static List<RadioButton> RadioButtonListChecked(this Control control) =>
control.RadioButtonList().Where(rb => rb.Checked).ToList();
}
Form code
public partial class Form2 : Form
{
private List<RadioButton> _checkedRadioButtons = new List<RadioButton>();
public Form2()
{
InitializeComponent();
Shown += OnShown;
}
private void OnShown(object sender, EventArgs e)
{
this.RadioButtonList().ForEach(rb =>
{
rb.CheckedChanged += OnCheckedChanged;
rb.Checked = false;
rb.Text = rb.Text.Numbers(); // original names are radioButton1, radioButton2 etc
});
label1.Text = "";
}
private void OnCheckedChanged(object sender, EventArgs e)
{
ProcessChecked(sender);
}
private void ProcessChecked(object sender)
{
if (!(sender is RadioButton radioButton) || !radioButton.Checked) return;
_checkedRadioButtons = this.RadioButtonListChecked();
if (_checkedRadioButtons.Count > 0)
{
label1.Text = string.Join(" ",
_checkedRadioButtons.Select(rb => rb.Text));
}
}
private void RadioButtonsCheckedButton_Click(object sender, EventArgs e)
{
if (_checkedRadioButtons.Any())
{
var checkedList = _checkedRadioButtons.Select(rb => rb).ToArray();
var names = string.Join("\n", checkedList.Select(rb => rb.Name));
MessageBox.Show(names);
}
}
}

The following code dynamically checks whether the control is RadioButton and then fetches the RadioButton name number and displays it on the label.
foreach (Control ctr in this.Controls)
{
if (ctr is RadioButton)
{
RadioButton radioButton = (RadioButton)ctr;
if (radioButton.Checked)
{
//get number in radioButton
string num = "";
foreach(Char c in radioButton.Name)
{
if (Char.IsDigit(c))
num += c;
}
label1.Text += num + " ";
}
}
}

label1.Text += Controls.OfType<RadioButton>().FirstOrDefault(_ => _.Checked)?.Text;

Related

Auto refresh value in ListViewItem

I'm currently working on an application for an industrial robot. The application connects to all robot controllers in the network and lists them in a ListViewItem. Using a double click on one of the controllers detail information in a second ListVieItem is displayed. Till now I managed to connect to the robot controllers and use the double click to show the information. The problem now is that the value of the variable inside the controller is changing, but I do not know how to adjust my code, so the change will be displayed automatically.
The code I use:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ABB.Robotics.Controllers;
using ABB.Robotics.Controllers.Discovery;
using ABB.Robotics.Controllers.RapidDomain;
using ABB.Robotics.Controllers.IOSystemDomain;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private NetworkScanner networkScanner = null;
private Controller ctrl = null;
private Controller controller = null;
private Task[] tasks = null;
private NetworkWatcher networkwatcher = null;
private Num rapidNum;
private double VarValue = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
networkScanner = new NetworkScanner();
networkScanner.Scan();
ControllerInfoCollection controllers = networkScanner.Controllers;
networkwatcher = new NetworkWatcher(networkScanner.Controllers);
networkwatcher.Found += new EventHandler<NetworkWatcherEventArgs>(HandleFoundEvent);
networkwatcher.Lost += new EventHandler<NetworkWatcherEventArgs>(HandleLostEvent);
networkwatcher.EnableRaisingEvents = true;
foreach (ControllerInfo controller in controllers)
{
ListViewItem item = new ListViewItem(controller.IPAddress.ToString());
item.SubItems.Add(controller.Id);
item.SubItems.Add(controller.Availability.ToString());
item.SubItems.Add(controller.IsVirtual.ToString());
item.SubItems.Add(controller.SystemName);
item.SubItems.Add(controller.Version.ToString());
item.SubItems.Add(controller.ControllerName);
item.Tag = controller;
this.listControllersView.Items.Add(item);
}
}
private void Form1_Closed(object sender, FormClosedEventArgs e)
{
this.networkwatcher.Lost -= new EventHandler<NetworkWatcherEventArgs>(HandleLostEvent);
this.networkwatcher.Found -= new EventHandler<NetworkWatcherEventArgs>(HandleFoundEvent);
}
private void ListControllersView_DoubleClick(object sender, EventArgs e)
{
ListViewItem itemView = listControllersView.SelectedItems[0];
if(itemView.Tag != null)
{
ControllerInfo controllerInf = (ControllerInfo)itemView.Tag;
if(controllerInf.Availability == ABB.Robotics.Controllers.Availability.Available)
{
if(this.controller != null)
{
this.controller.Logoff();
this.controller.Dispose();
this.controller = null;
}
this.controller = ControllerFactory.CreateFrom(controllerInf);
this.controller.Logon(UserInfo.DefaultUser);
RapidData rd = this.controller.Rapid.GetRapidData("T_ROB1", "RoboDK_Driver", "TESTVAR");
if (rd.Value is Num)
{
rapidNum = (Num)rd.Value;
VarValue = rapidNum.Value;
}
ListViewItem item = new ListViewItem(controller.RobotWare.ToString() + " " + controller.State.ToString() + " " + controller.OperatingMode.ToString() + " " + "VarValue" + " " + VarValue);
this.listOutput.Items.Add(item);
}
else
{
MessageBox.Show("Selected controller not available");
}
}
}
void HandleFoundEvent(object sender, NetworkWatcherEventArgs e)
{
this.Invoke(new
EventHandler<NetworkWatcherEventArgs>(AddControllerToListView),
new Object[] { this, e });
}
void HandleLostEvent(object sender, NetworkWatcherEventArgs e)
{
this.Invoke(new EventHandler<NetworkWatcherEventArgs>(RemoveControllerFromListView),
new Object[] { sender, e });
}
private void AddControllerToListView(object sender, NetworkWatcherEventArgs e)
{
ControllerInfo controllerInfo = e.Controller;
ListViewItem item = new ListViewItem(controllerInfo.IPAddress.ToString());
item.SubItems.Add(controllerInfo.Id);
item.SubItems.Add(controllerInfo.Availability.ToString());
item.SubItems.Add(controllerInfo.IsVirtual.ToString());
item.SubItems.Add(controllerInfo.SystemName);
item.SubItems.Add(controllerInfo.Version.ToString());
item.SubItems.Add(controllerInfo.ControllerName);
item.Tag = controllerInfo;
this.listControllersView.Items.Add(item);
}
private void RemoveControllerFromListView(object sender, NetworkWatcherEventArgs e)
{
foreach(ListViewItem item in this.listControllersView.Items)
{
if((ControllerInfo)item.Tag == e.Controller)
{
this.listControllersView.Items.Remove(item);
break;
}
}
}
}
}

C# - Windows Application - Saving List

I have made a simple TO-DOs program that gets input from a text box then place it in another text box. With tick boxes next to it,
this is all fine except i Cannot save the list eg. the item and if it's finished or not.
Please could anyone help me be able to save this list of items.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TO_DOs
{
public partial class Form1 : Form
{
private bool text1, text2, text3, text4, text5, text6, text7, text8;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (text1 == false)
{
textBox2.Text = textBox1.Text;
}
else if (text2 == false)
{
textBox3.Text = textBox1.Text;
}
else if (text3 == false)
{
textBox4.Text = textBox1.Text;
}
else if (text4 == false)
{
textBox5.Text = textBox1.Text;
}
else if (text5 == false)
{
textBox6.Text = textBox1.Text;
}
else if (text6 == false)
{
textBox7.Text = textBox1.Text;
}
else if (text7 == false)
{
textBox8.Text = textBox1.Text;
}
else if (text8 == false)
{
textBox9.Text = textBox1.Text;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
text1 = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
text2 = true;
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
text3 = true;
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
text4 = true;
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
text5 = true;
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
text6 = true;
}
private void textBox8_TextChanged(object sender, EventArgs e)
{
text7 = true;
}
private void textBox9_TextChanged(object sender, EventArgs e)
{
text8 = true;
}
}
}
I would do it like this:
Create a class to store your values in:
public class ListEntry
{
public string Text { get; set; }
public bool Finished { get; set; }
}
Then I would create 2 Methods:
public List<ListEntry> UI_To_List(); //Create UI from your saved file
public void List_To_UI(List<ListEntry> entries); //Process your UI
Now it's your choice on how to store your list.
You could store it as JSON or XML.
A few recommendations:
I would create a UserControl for your TextBox + CheckBox
Display the 'List of UserControls' in a FlowLayoutPanel
=> then you can process the FlowLayoutPanel.Controls List.
This will make your List dynamically size to an 'unlimited' amount of items.
Short example:
Create a UserControl (Rightclick project for that):
Add these 2 methods to the code of your UserControl (F7 / rightclick => View Code):
public void SetText(string text)
{
//Set the Text of your TextBox in the UserControl:
textBox1.Text = text;
}
public void SetFinished(bool finished)
{
//Set the Checked of your CheckBox in the UserControl:
checkBox1.Checked = finished;
}
In your MainForm add an FlowLayoutPanel (from ToolBox).
Add your Data like this (using class from above):
/// <summary>
///
/// </summary>
/// <param name="entries">You will get them from loading your previously saved file</param>
public void CreateUI(List<ListEntry> entries)
{
foreach (ListEntry entry in entries)
{
//Create new instance of your UserControl
TaskView view = new TaskView();
view.SetFinished(entry.IsFinished);
view.SetText(entry.Text);
//Add that to your UI:
this.flowLayoutPanel1.Controls.Add(view);
}
}
The result will look like this:
I'm not sure what exactly it is that you want to save in a list... but here's just a tip when checking conditions, instead of using if (text1 == false), simply do if (!text1) as this means "is not true" because by default if (text1) will return true.
private void button1_Click(object sender, EventArgs e)
{
if (!text1)
{
textBox2.Text = textBox1.Text;
}
else if (!text2)
{
textBox3.Text = textBox1.Text;
}
// Left out the rest of the else ifs
}
You are casting textboxes wrong. For example when you change textBox4, you gave text3 true.
private void textBox4_TextChanged(object sender, EventArgs e)
{
text3 = true;
}
Then you cast
TextBox4.Text = TextBox1.Text;
It changes TextBox4.Text to TextBox1.Text.
You probably want to save TextBox4.Text here at TextBox1.Text so you sould change all if blocks like that. So you have to give only one "true" function for changed textBox sign and change if blocks
if(text(boolNum))
TextBox1.Text = TextBox(Number).Text;
Just swap them and try like that.
If you want to save another thing by another way. You have to be more spesific.
You can use a CheckedListbox to hold all tot actions.
You can then tick the itemsand for instance in the OK button you include a save action:
foreach(var item in MyCheckedListbox.CheckedItems)
{
Console,WriteLine(item.Text);
}
Lets see the answer from Felix D. He tells you exactly how to create a class and save the items into it. But now you only have a List that will be available as long as your software is running. You still need to save it somewhere on your desktop.
Lucky for you, you got a really simple pattern.
string; boolean
So how about you make it yourself simple? Just create a textfile and write your entries, as example in a csv marked with a ; for every information?
Example:
class Program
{
public class tmpClass
{
public string Text;
public bool tick;
}
public List<tmpClass> tmpList = new List<tmpClass>();
static void Main(string[] args)
{
//Stuff
}
public void WriteToFile()
{
string tmpTextFilePath = #"C:\User\Desktop\SaveText.txt";
using (StreamWriter tmpWriter = new StreamWriter(tmpTextFilePath))
{
string tmpTextToWrite = String.Empty;
for (int i = 0; i < tmpList.Count; i++)
{
tmpClass tmpEntry = tmpList[i];
tmpTextToWrite += tmpEntry.Text + ";" + tmpEntry.tick;
}
tmpWriter.WriteLine(tmpTextToWrite);
}
//Now we wrote a text file to you desktop with all Informations
}
public void ReadFromFile()
{
string tmpTextFilePath = #"C:\User\Desktop\SaveText.txt";
using (StreamReader tmpReader = new StreamReader(tmpTextFilePath))
{
string tmpText = tmpReader.ReadLine();
string tmpInput = String.Empty;
tmpClass tmpClass = new tmpClass();
int i = 0;
foreach (char item in tmpText)
{
if(item.Equals(";".ToCharArray()))
{
if (i == 0)
{
tmpClass.Text = tmpInput;
i = 1;
tmpInput = String.Empty;
}
else
{
if (tmpInput == "True")
tmpClass.tick = true;
else
tmpClass.tick = false;
i = 0;
tmpInput = String.Empty;
tmpList.Add(tmpClass);
}
}
tmpInput += item;
}
}
}
}
This should simply write a txt File to your desktop with your information and read one and save it to your list.

c# multiple lock for multiple events

I'm trying to understand the lock mechanism.
if I have multiple events to lock on different value should I use an object lock for each?
More serious code added:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
namespace ValueChangeOnEventForm
{
public partial class Form1 : Form
{
private Test_Onchange DataSource;
Thread Task1;
private bool Flag_Stop_Task1;
public Form1()
{
InitializeComponent();
graph1.ChartAreas[0].AxisX.ScrollBar.Enabled = true;
graph1.ChartAreas[0].AxisX.IsLabelAutoFit = true;
graph1.ChartAreas[0].AxisX.ScaleView.Size = 100;
graph2.ChartAreas[0].AxisX.ScrollBar.Enabled = true;
graph2.ChartAreas[0].AxisX.IsLabelAutoFit = true;
graph2.ChartAreas[0].AxisX.ScaleView.Size = 100;
DataSource = new Test_Onchange();
DataSource.ValueChanged += new EventHandler(EventValueChange);//Value input info
DataSource.SecondValueChange += new EventHandler(EventSecondValueChange);//second value
Task1 = new Thread(new ThreadStart(Task_1));//create the thread
Task1.Start();//start the thread
}
protected virtual void EventSecondValueChange(object sender, EventArgs e)
{
double valueMAX = 0, size = 0;
if (graph1.InvokeRequired)
{
graph1.Invoke(new MethodInvoker(delegate { graph1.Series["ValueOnGraph"].Points.AddY(DataSource.Value); }));
graph1.Invoke(new MethodInvoker(delegate { valueMAX = graph1.ChartAreas[0].AxisX.Maximum; }));
graph1.Invoke(new MethodInvoker(delegate { size = graph1.ChartAreas[0].AxisX.ScaleView.Size; }));
if (valueMAX - 10 > size)
{
graph1.Invoke(new MethodInvoker(delegate { graph1.ChartAreas[0].AxisX.ScaleView.Scroll(graph1.ChartAreas[0].AxisX.Maximum); }));
graph1.Invoke(new MethodInvoker(delegate { graph1.Series["ValueOnGraph"].Points.RemoveAt(0); }));
}
}
}
protected virtual void EventValueChange(object sender, EventArgs e)
{
double valueMAX=0,size=0;
if (graph2.InvokeRequired)
{
graph2.Invoke(new MethodInvoker(delegate { graph2.Series["ValueOnGraph2"].Points.AddY(DataSource.Secondvalue); }));
graph2.Invoke(new MethodInvoker(delegate { valueMAX = graph2.ChartAreas[0].AxisX.Maximum; }));
graph2.Invoke(new MethodInvoker(delegate { size = graph2.ChartAreas[0].AxisX.ScaleView.Size; }));
if (valueMAX - 10 > size)
{
graph2.Invoke(new MethodInvoker(delegate { graph2.ChartAreas[0].AxisX.ScaleView.Scroll(graph2.ChartAreas[0].AxisX.Maximum); }));
graph2.Invoke(new MethodInvoker(delegate { graph2.Series["ValueOnGraph2"].Points.RemoveAt(0); }));
}
}
}
private void Task_1()
{
while (!Flag_Stop_Task1)
{
Random RandVal = new Random();
Random RandVal2 = new Random();
int Value = RandVal.Next(0, 100);
int SecondValue = RandVal2.Next(50, 200);
DataSource.Value = Value;
DataSource.Secondvalue = SecondValue;
Thread.Sleep(100);
}
Flag_Stop_Task1 = false;
}
private void btn_StopTask_1_Click(object sender, EventArgs e)
{
Flag_Stop_Task1 = true;
}
}
}
And then
namespace ValueChangeOnEventForm
{
class Test_Onchange
{
private int value;
private int secondvalue;
protected object _lock = new object();
public event System.EventHandler ValueChanged;
public event System.EventHandler SecondValueChange;
protected virtual void OnValueChange()
{
lock (this._lock)
{
EventHandler eventvaluechange = ValueChanged;
if (eventvaluechange != null)
eventvaluechange(this, EventArgs.Empty);
}
}
protected virtual void OnSecondValueChange()
{
lock (this._lock)
{
EventHandler eventvaluechange = SecondValueChange;
if (eventvaluechange != null)
eventvaluechange(this, EventArgs.Empty);
}
}
public int Value
{
get { return this.value; }
set
{
if (value != this.value)
{//if value changed enter
this.value = value;
OnValueChange();
}
}
}
public int Secondvalue
{
get { return this.secondvalue; }
set
{
if (value != this.secondvalue)
{//if value changed enter
this.secondvalue = value;
OnSecondValueChange();
}
}
}
}
}
Do I need two lock (lock1 and lock2 object or only one for both value and secondvalue....?
Thanks a lot.
Update
Ok let's do it so.
I'm using beckhoff PLC which are real time Task PLC. and I'm reading two value on it when the value change. like this:
Form1 Class:
namespace RealTimeLock
{
using Beckhoff.App.Ads.Core;
using Beckhoff.App.Ads.Core.Plc;
using TwinCAT.Ads;
using System.IO;
public partial class Form1 : Form
{
private PLC PLCData;
public Form1()
{
InitializeComponent();
}
public Form1(IBAAdsServer _adsServer)
: this()
{
PLCData = new PLC(_adsServer);
PLCData.ErrorBoolChanged += new EventHandler(EventErrorChanged);//error info
PLCData.ForceValChanged += new EventHandler(EventForceChanged);//Force input info
}
protected virtual void EventErrorChanged(object sender, EventArgs e)
{
//state of error PLC
lv_ErrorInfo.Text = "PLC Error num : " + PLCData.i_ErrorID.ToString();
}
protected virtual void EventForceChanged(object sender, EventArgs e)
{//modify graphical data PLC Force data
lv_ForceInfo.Text = PLCData.i_ForceVal.ToString();
c_graphForceIN.Series["ForceData"].Points.AddY(PLCData.i_ForceVal);
if (c_graphForceIN.ChartAreas[0].AxisX.Maximum - 10 > c_graphForceIN.ChartAreas[0].AxisX.ScaleView.Size)
{
c_graphForceIN.ChartAreas[0].AxisX.ScaleView.Scroll(c_graphForceIN.ChartAreas[0].AxisX.Maximum);
c_graphForceIN.Series["ForceData"].Points.RemoveAt(0);
}
}
}
}
Error ID and Force change showed in Form1 label lv_ErrorID and lv_Force and graphForceIN add point.
The events handler on the other side (PLC class) looks like this:
PLC Class:
namespace RealTimeLock
{
using Beckhoff.App.Ads.Core;
using Beckhoff.App.Ads.Core.Plc;
using TwinCAT.Ads;
using System.IO;
public partial class Form1 : Form
{
private PLC PLCData;
public Form1()
{
InitializeComponent();
}
public Form1(IBAAdsServer _adsServer)
: this()
{
PLCData = new PLC(_adsServer);
PLCData.ErrorBoolChanged += new EventHandler(EventErrorChanged);//error info
PLCData.ForceValChanged += new EventHandler(EventForceChanged);//Force input info
}
protected virtual void EventErrorChanged(object sender, EventArgs e)
{
//state of error PLC
lv_ErrorInfo.Text = "PLC Error num : " + PLCData.i_ErrorID.ToString();
}
protected virtual void EventForceChanged(object sender, EventArgs e)
{//modify graphical data PLC Force data
lv_ForceInfo.Text = PLCData.i_ForceVal.ToString();
c_graphForceIN.Series["ForceData"].Points.AddY(PLCData.i_ForceVal);
if (c_graphForceIN.ChartAreas[0].AxisX.Maximum - 10 > c_graphForceIN.ChartAreas[0].AxisX.ScaleView.Size)
{
c_graphForceIN.ChartAreas[0].AxisX.ScaleView.Scroll(c_graphForceIN.ChartAreas[0].AxisX.Maximum);
c_graphForceIN.Series["ForceData"].Points.RemoveAt(0);
}
}
}
}
Does it seem to be correct coding for you guys? and while I have a real time task running there do I need to lock variables and if so, do I need two lock or only one??
Thanks for your remark on this!!

Storing a value to a listbox item C#

I wish to know how to store a VALUE to an item in a listbox. I'm currently working out a worksheet for my studies, and I've been wondering how to do this. Basically I need to store values to the Food (such as broccoli, bread. For example: Broccoli has a value of 20 calories).
The user must not see the value, only the program can store it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MCAST_Calorie_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
lbAvailable.Items.Clear();
if (comboBox1.Text == "Vegetables")
{
lbAvailable.Items.Add("Broccoli");
lbAvailable.Items.Add("Carrots");
lbAvailable.Items.Add("Lettuce");
lbAvailable.Items.Add("Onions");
lbAvailable.Items.Add("Potatoes");
}
if (comboBox1.Text == "Meat")
{
lbAvailable.Items.Add("Chicken");
lbAvailable.Items.Add("Veal");
lbAvailable.Items.Add("Beef");
lbAvailable.Items.Add("Fish");
}
if (comboBox1.Text == "Legumes")
{
lbAvailable.Items.Add("Bread");
lbAvailable.Items.Add("Peanuts");
lbAvailable.Items.Add("Green Peas");
lbAvailable.Items.Add("Lentils");
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
ListBox.SelectedObjectCollection highlightedItems = lbAvailable.SelectedItems;
foreach (var item in highlightedItems)
{
lbChosen.Items.Add(item);
}
if (lbAvailable.SelectedItems.Count > 0)
{
lbAvailable.Items.Remove(lbAvailable.SelectedItems[0]);
}
}
private void btnRemove_Click(object sender, EventArgs e)
{
ListBox.SelectedObjectCollection highlightedItems = lbChosen.SelectedItems;
foreach (var item in highlightedItems)
{
lbAvailable.Items.Add(item);
}
if (lbChosen.SelectedItems.Count > 0)
{
lbChosen.Items.Remove(lbChosen.SelectedItems[0]);
}
}
private void btnClear_Click(object sender, EventArgs e)
{
lbAvailable.Items.Clear();
lbChosen.Items.Clear();
if (comboBox1.Text == "Vegetables")
{
lbAvailable.Items.Add("Broccoli");
lbAvailable.Items.Add("Carrots");
lbAvailable.Items.Add("Lettuce");
lbAvailable.Items.Add("Onions");
lbAvailable.Items.Add("Potatoes");
}
if (comboBox1.Text == "Meat")
{
lbAvailable.Items.Add("Chicken");
lbAvailable.Items.Add("Veal");
lbAvailable.Items.Add("Beef");
lbAvailable.Items.Add("Fish");
}
if (comboBox1.Text == "Legumes")
{
lbAvailable.Items.Add("Bread");
lbAvailable.Items.Add("Peanuts");
lbAvailable.Items.Add("Green Peas");
lbAvailable.Items.Add("Lentils");
}
}
}
}
Thanks alot for your help!
You can always add custom objects that support ToString() to the ListBox.Items collection:
struct Record
{
int value;
string label;
public override string ToString()
{
return label;
}
}
Adding a custom object:
Record record = new Record();
record.value = 1;
record.label = "This text will appear in the ListBox";
listBox.Items.Add(record);
Retrieving it:
Record selectedRecord = (Record)listBox.SelectedItem;
Console.WriteLine(selectedRecord.value); // => 1

parsing data between forms to datagridview

i have a main form name fmMain
black mark is show browse file path to datagridview
and red mark is show form to datagridview.
i try to send path to datagridview and succes. here is the code
namespace tstIniF
{
public partial class fmMain : Form
{
string ConfigFileName = "app.cfg";
CFileConfig cFileConfig;
public fmMain()
{
InitializeComponent();
cFileConfig = new CFileConfig();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Close();
}
private void btnDirectort_Click(object sender, EventArgs e)
{
if (dlgFolder.ShowDialog() != DialogResult.OK) return;
string s = dlgFolder.SelectedPath;
txtDirectory.Text = s;
/*p = (string)dgvConfigFile.Rows[idx++].Cells[1].Value; cFileConfig.cfgContourFile = p;
p = (string)dgvConfigFile.Rows[idx++].Cells[1].Value; cFileConfig.cfgConnectionString = p;*/
}
private void btnDirectBase_Click(object sender, EventArgs e)
{
if (dlgFile.ShowDialog() != DialogResult.OK) return;
string s = dlgFile.FileName;
int idx = 0;
dgvConfigFile.Rows[idx++].Cells[1].Value = cFileConfig.cfgBaseMapFile = s;
}
private void btnDirectCont_Click(object sender, EventArgs e)
{
if (dlgFile.ShowDialog() != DialogResult.OK) return;
string s = dlgFile.FileName;
int idx = 1;
dgvConfigFile.Rows[idx++].Cells[1].Value = cFileConfig.cfgContourFile = s;
}
private void btnDirectConn_Click(object sender, EventArgs e)
{
fConn op = new fConn();
op.ShowDialog();
}
}
}
red mark as btnDirectConn i show new form like this
and here is my form fConn
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace tstIniF
{
public partial class fConn : Form
{
public fConn()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (txtServ.Text.Trim() == "" || txtDb.Text.Trim() == "" || txtUid.Text.Trim() == "" || txtPwd.Text.Trim() == "")
{
MessageBox.Show("Mohon diisi semua field....");
}
else
{
//string textAll = this.txtServ.Text + this.txtDb.Text + this.txtUid.Text + this.txtPwd.Text;
fmMain frm = new fmMain();
frm._textBox = _textBox1;
this.Close();
//Close();
//frm.Show();
}
}
public string _textBox1
{
get { return txtServ.Text + txtDb.Text; }
}
}
}
the question is how to show data in form fConn to fmMain datagridview , i fill the fConn entry and close and back to fmMain so the result is
I would use delegate to handle this,
change fConnform as below
public partial class fConn : Form
{
public SaveDelegate SaveCallback;
public fConn()
{
InitializeComponent();
}
public void btnSave_Click(object sender, EventArgs e)
{
SaveCallback("set text what you need to send to main form here...");
}
}
And fmMain as below
public delegate void SaveDelegate(string text);
public partial class fmMain
{
public fmMain()
{
InitializeComponent();
}
private void btnDirectConn_Click(object sender, EventArgs e)
{
fConn op = new fConn();
op.SaveCallback += new SaveDelegate(this.SavemCallback);
op.ShowDialog();
}
private void SavemCallback(string text)
{
// you have text from fConn here ....
}
In the frmMain declare the fConn form at the class level so that it won't get disposed when the form closes. Now the frmMain can access any public objects in fConn.
Don't re-declare frmMain in fConn. Use _textBox = op._textBox1 right after op.ShowDialog();

Categories

Resources