Auto refresh value in ListViewItem - c#

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;
}
}
}
}
}

Related

Automatically auto-check every new item in a checkedboxlist in c#

I am trying to auto check every new item in my checkedboxlist I have a button that does that it will auto select all, but we don't want it that way to be controlled by a button. we want it so for every new item we get automatically will get checked.
This is my button that auto select all if there are new 20 items this will auto select all and then submit those new items
Here is the code it works but is not I want I want to auto select for every new items coming in, because I have another process that will keep adding new items to the checkedboxlist, also the lst_BarcodeScanEvents is the checkedboxlist name
private void btn_SelectALLScans_Click(object sender, EventArgs e)
{
for (var i = 0; i < lst_BarcodeScanEvents.Items.Count; i++)
{
lst_BarcodeScanEvents.SetItemChecked(i, true);
}
}
I checked other sources like google and stackoverflow but I could not find anything to my request here.
Here is the main class where I have the logic of buttons, checkedlistbox and more. and the button method btn_ConnectT_Click calls the methods from the second class
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Web;
using BarcodeReceivingApp.Core.Domain;
using BarcodeReceivingApp.Functionality;
namespace BarcodeReceivingApp
{
public partial class BarcodeReceivingForm : Form
{
//GLOBAL VARIABLES
private const string Hostname = "myip";
private const int Port = 23;
private TelnetConnection _connection;
private ParseReceivingBarcode _parseReceivingBarcode;
private ButtonsDisplay _buttonsDisplay;
public BarcodeReceivingForm()
{
InitializeComponent();
//FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
}
private void btn_ConnectT_Click(object sender, EventArgs e)
{
_connection = new TelnetConnection(Hostname, Port);
_connection.ServerSocket(Hostname, Port, this);
}
private void btn_StopConnection_Click(object sender, EventArgs e)
{
_connection.Exit();
}
private void btn_RemoveItemFromListAt_Click(object sender, EventArgs e)
{
if (lst_BarcodeScanEvents.CheckedItems.Count != 0)
for (var i = lst_BarcodeScanEvents.CheckedItems.Count; i > 0; i--)
lst_BarcodeScanEvents.Items.RemoveAt(lst_BarcodeScanEvents.CheckedIndices[i - 1]);
else
MessageBox.Show(#"Element(s) Not Selected...");
}
private void BarcodeReceivingForm_Load(object sender, EventArgs e)
{
_buttonsDisplay = new ButtonsDisplay(this);
_buttonsDisplay.ButtonDisplay();
}
private void btn_ApplicationSettings_Click(object sender, EventArgs e)
{
var bcSettingsForm = new BarcodeReceivingSettingsForm();
bcSettingsForm.Show();
}
private void btn_ClearBarcodeList_Click(object sender, EventArgs e)
{
lst_BarcodeScanEvents.Items.Clear();
}
private void lst_BarcodeScanEvents_ItemAdded(object sender, ListBoxItemEventArgs e)
{
MessageBox.Show(#"Item was added at index " + e.Index + #" and the value is " + lst_BarcodeScanEvents.Items[e.Index].ToString());
}
private void btn_SubmitData_Click(object sender, EventArgs e)
{
var receivingFullBarcode = new List<string>();
_connection.GetBarcodeList();
}
private void btn_SelectALLScans_Click(object sender, EventArgs e)
{
for (var i = 0; i < lst_BarcodeScanEvents.Items.Count; i++)
{
lst_BarcodeScanEvents.SetItemChecked(i, true);
}
}
}
}
Here is the second class where I use a telnet port 23 that scan barcodes where and puts it to the checkedlistbox, now the main emethods here that inserts the data to the checkedlistbox is the method serversocket and the readwrite method
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace BarcodeReceivingApp.Functionality
{
public class TelnetConnection
{
private Thread _readWriteThread;
private TcpClient _client;
private NetworkStream _networkStream;
private string _hostname;
private int _port;
private BarcodeReceivingForm _form;
private bool _isExiting = false;
public TelnetConnection(string hostname, int port)
{
this._hostname = hostname;
this._port = port;
}
public void ServerSocket(string ip, int port, BarcodeReceivingForm f)
{
this._form = f;
try
{
_client = new TcpClient(ip, port);
}
catch (SocketException)
{
MessageBox.Show(#"Failed to connect to server");
return;
}
_networkStream = _client.GetStream();
_readWriteThread = new Thread(ReadWrite);
//_readWriteThread = new Thread(() => ReadWrite(f));
_readWriteThread.Start();
}
public void Exit()
{
_isExiting = true;
}
public void ReadWrite()
{
do
{
var received = Read();
if (received == null)
break;
if (_form.lst_BarcodeScanEvents.InvokeRequired)
{
var received1 = received;
_form.lst_BarcodeScanEvents.Invoke(new MethodInvoker(delegate
{
_form.lst_BarcodeScanEvents.AddItem(received1 + Environment.NewLine);
}));
}
} while (!_isExiting);
//var material = received.Substring(10, 5);
//_form.label5.Text += string.Join(Environment.NewLine, material);
CloseConnection();
}
public List<string> GetBarcodeList()
{
var readData = new List<string>();
foreach (string list in _form.lst_BarcodeScanEvents.Items)
{
readData.Add(list);
MessageBox.Show(list);
}
return readData;
}
public string Read()
{
var data = new byte[1024];
var received = "";
var size = _networkStream.Read(data, 0, data.Length);
if (size == 0)
return null;
received = Encoding.ASCII.GetString(data, 0, size);
return received;
}
public void CloseConnection()
{
MessageBox.Show(#"Closed Connection",#"Important Message");
_networkStream.Close();
_client.Close();
}
}
}
so now like I said before for every new items it gets inserted to the checkedlistbox I want it to be auto selected everytime it adds a new data to the checkedlistbox.
The problem, usually simple, of setting the Checked state of a newly added Item of a CheckedListBox, was somewhat complicated because of the nature of the Listbox in question.
The CheckedListBox is a Custom Control with custom events and properties.
It's actually a relatively common customization (one implementation can be see in this MSDN Forum post:
Have ListBox an event when addid or removing Items?) but it might complicate the interpretation of the events.
The Custom Control, when adding a new Item to the List (from a class other than the Form that hosts the Control), raises the custom ItemAdded event
private void [CheckedListBox]_ItemAdded(object sender, ListBoxItemEventArgs e)
The Index of the Item added is referenced by the e.Index property of the custom ListBoxItemEventArgs object.
With the code provided, it can be determined that this event handler is the natural place where the Checked state of the new Item can be set:
private void lst_BarcodeScanEvents_ItemAdded(object sender, ListBoxItemEventArgs e)
{
lst_BarcodeScanEvents.SetItemChecked(e.Index, true);
}
For that I suggest to create an event that you subscribe after you InitializeComponent() of your form like so :
public Form1()
{
InitializeComponent();
lst_BarcodeScanEvents.ControlAdded += new ControlEventHandler(AddedNewSelect);
}
private void AddedNewSelect(object sender, ControlEventArgs e)
{
lst_BarcodeScanEvents.SetItemChecked(e.Control.TabIndex, true);
}

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!!

Image Gallery on C#

What I have to do is this:
Make an image gallery that has 5 buttons which each one select a folder of images.
Other two buttons for next and previous of the folder you are in. In my line 76, it says
argument 1: cannot convert from 'System.collection.Generic.list' to string
Any ideas?
Here's an image of the console
http://postimg.org/image/nct5pwdit/
Line 76 says:
pictureBox1.Load(semestres[semac].imagen[]);
I have the same command like 6 times.
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;
class semestres
{
public List<string> imagen = new List<string>();
private int _semestre;
public int canti;
public int actual;
public int c;
public semestres(int semestre, List<string> imagenes)
{
_semestre = semestre;
imagen = imagenes;
c = imagen.Count;
actual = 0;
}
public int semestre
{
get
{
return _semestre;
}
set
{
c = imagen.Count;
}
}
public int can
{
get
{
return c;
}
set
{
c = imagen.Count;
}
}
}
namespace Visor
{
public partial class Form1 : Form
{
private int cont;
private int semac;
private int _cant;
private int next;
private List<semestres> semestres = new List<semestres>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
cont = semestres[semac].actual;
cont--;
if (cont >= 0)
{
pictureBox1.Load(semestres[semac].imagen[]);
semestres[semac].actual = cont;
}
else
{
// MessageBox("Esta es la primer imagen");
cont = 0;
semestres[semac].actual = cont;
pictureBox1.Load(semestres[semac].imagen);
}
}
private void button7_Click(object sender, EventArgs e)
{
cont = semestres[semac].actual;
next = semestres[semac].c;
cont++;
if (cont < next)
{
pictureBox1.Load(semestres[semac].imagen);
semestres[semac].actual = cont;
}
else
{
// MessageBox("Esta es la ultima imagen");
cont--;
semestres[semac].actual = cont;
pictureBox1.Load(semestres[semac].imagen(cont));
}
}
private void button2_Click(object sender, EventArgs e)
{
semac = 0;
try
{
if (semestres[0].c > 0)
{
cont = semestres[0].actual;
pictureBox1.Load(semestres[0].imagen(cont));
}
}
catch (Exception)
{
OpenFileDialog file = new OpenFileDialog();
file.InitialDirectory = #"C:\";
file.Filter = "Images (*.BMP; *.JPG; *.GIF)|*.BMP; *.JPG; *.GIF|" + "All files(*.*)|*.*";
file.FilterIndex = 1;
file.Multiselect = true;
file.RestoreDirectory = true;
file.ShowDialog();
string[] imgs = file.FileNames;
List<string> imagenes = new List<string>();
foreach (string imagen in imgs)
{
imagenes.Add(imagen);
}
semestres.Add(new semestres(1, imagenes));
pictureBox1.Load(imagenes[0]);
semestres[0].actual = 0;
cont = 0;
}
}
private void button6_Click(object sender, EventArgs e)
{
}
private void btn_3_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_sal_Click(object sender, EventArgs e)
{
}
private void btn_2_Click(object sender, EventArgs e)
{
}
}
}
So you have this:
pictureBox1.Load(semestres[semac].imagen);
Well the problem is that imagen is a List<string>. Picturebox.Load(string) takes a string, not a List<string>. So you need to get a string from that list instead of passing the whole list. One way would be:
pictureBox1.Load(semestres[semac].imagen[0]);
This would load the first image in that list.
Alternatively, you might be trying to do:
pictureBox1.Load(semestres[semac].imagen[cont]);
You just need to determine what the correct index is that you're trying to specify.

searched items dont be added to list box

items searched in search function: the ALBUMS dont get added to the list box?
the other fields populate
can you please tell me how i can populate the listbox with the searched albums
albums be looked up using a linked list
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 Assignment
{
public partial class frmAddArtist : Form
{
AVLTree<Artist> avltree = new AVLTree<Artist>();
LinkedList<Album> temp = new LinkedList<Album>();
Artist artistinst;
Album albuminst;
string noofmembers, artistname;
int artistcount;
public frmAddArtist()
{
InitializeComponent();
}
private void label5_Click(object sender, EventArgs e)
{
}
private void btnAddArtist_Click(object sender, EventArgs e)
{
string tempalbum, date;
tempalbum = txtAlbumName.Text;
date = dtpReleaseDate.Text.ToString();
albuminst = new Album(tempalbum, date);
temp.AddFirst(albuminst);
lbAlbums.Items.Add(tempalbum);
}
private void btnSave_Click(object sender, EventArgs e)
{
artistname = txtArtistName.Text;
noofmembers = txtNoOfMembers.Text;
artistinst = new Artist(artistname, noofmembers, temp);
avltree.InsertItem(artistinst);
artistcount++;
txtArtistName.Clear();
txtNoOfMembers.Clear();
txtAlbumName.Clear();
lbAlbums.Items.Clear();
temp.Clear();
}
private void btnNoOfArtist_Click(object sender, EventArgs e)
{
MessageBox.Show("The No. Artist: " + Convert.ToString(artistcount));
}
private void btnHeight_Click(object sender, EventArgs e)
{
int heightoftree = avltree.Height();
string height = Convert.ToString(heightoftree);
MessageBox.Show("The Height of the Tree: " + height);
}
private void btnSearch_Click(object sender, EventArgs e)
{
Artist temp = new Artist(txtSearch.Text, " ", null);
Artist result = avltree.Search(temp);
if (result != null)
{
if (result.CompareTo(temp) == 0)
{
txtArtistName.Text = result.artistname;
txtNoOfMembers.Text = result.noofmembers;
foreach (Album p in result.Albumslist)
{
lbAlbums.Items.Add(p.Albumname);
}
}
else if(result.CompareTo(temp) <0)
{
MessageBox .Show("No Match Found");
}
}
}
}
}
Put the items into a LinkedList or a List.
Then set lbAlbums.ItemsSource=;

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