I have created a class
public class GlobalVariable
{
private Guid _gebruikerID=Guid.Empty;
public Guid GebruikerID
{
get
{
return _gebruikerID;
}
set
{
_gebruikerID = value;
}
}
}
now I create an instance of that class
GlobalVariable gv = new GlobalVariable();
now I assign a value to that instance
foreach (var item in Gebruiker)
{
lblGebruikerID.Text = "GebruikerID: " + Convert.ToString(item.GebruikerId);
gv.GebruikerID = item.GebruikerId;
}
now the last step is that I want to use gv.GebuikerID' value in another event
protected void btnShowIDs_Click(object sender, EventArgs e)
{
lblAdressIDToBeDeleted.Text = gv.GebruikerID.ToString();
}
but unfortunately it shows me 00000000-0000-0000-0000-000000000000 but when I put breakpoint in the foreach loop it does show me the GUID.
Related
I have a Class where there a 2 variables int ID and string name. I made a list of several objects and loaded them onto a listbox. The listbox only show the name. Is there a way to retrieve the ID from the listbox?
class Show
{
private int _Id;
private string _Naam;
private string _Genre;
public override string ToString()
{
return Naam;
}
}
from a database i make a list of objects.
private void bttn_zoek_Click(object sender, EventArgs e)
{
foreach (object a in List<show> List)
{
listbox1.Items.Add(a);
}
}
I hope this is enough
Assuming WinForms, here is a super simple example of overriding ToString() to control how the class is displayed in the ListBox, and also how to cast the selected item in the ListBox back to your class type so you can extract values from it. There are other ways to accomplish this task, but you should understand a bare bones example like this first:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SomeClassName sc1 = new SomeClassName();
sc1.ID = 411;
sc1.Name = "Information";
listBox1.Items.Add(sc1);
SomeClassName sc2 = new SomeClassName();
sc2.ID = 911;
sc2.Name = "Emergency";
listBox1.Items.Add(sc2);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
SomeClassName sc = (SomeClassName)listBox1.Items[listBox1.SelectedIndex];
label1.Text = "ID: " + sc.ID.ToString();
label2.Text = "Name: " + sc.Name;
}
}
}
public class SomeClassName
{
public int ID;
public string Name;
public override string ToString()
{
return ID.ToString() + ": " + Name;
}
}
Posting some of your code would be nice. Have you tried listBox.items[index].ID?
Here I'm assuming that index is whatever index you're currently searching for.
You can also try listBox.SelectedItem[index].ID if you're doing something like an event.
I have a class that has multiple properties. What I want to have is a value set to a particular property if there is no value passed to it. For instance, if txtFather.Text is blank, then the _theFather property of a class should have a default value of "N/A". Here is the code I have so far:
class StudentModel
private string _theFather = "N/A";
public string SetFather
{
get { return _theFather; }
set { _theFather = value; }
}
public void InsertStudent(StudentModel student)
{
MessageBox.Show(_theFather);
}
class AddStudent
private void button1_Click(object sender, EventArgs e)
{
var sm = new StudentModel()
{
SetFather = txtFathersName.Text
};
sm.InsertStudent(sm);
}
If I place a value in the txtFather.Text, I get the its value in the StudentModel Class but if I leave the txtFather.Text blank, I don't get the "N/A" value. I just get a blank or no value at all.
Thanks for your help.
I would encapsulate the logic within the StudentModel class by checking the value being passed to the setter, and only updating your backing field if the string is not null or whitespace.
public string SetFather
{
get { return _theFather; }
set {
if(!string.IsNullOrWhiteSpace(value))
{
_theFather = value;
}
}
}
This way you only have the logic in a single place. If you modify your class' consuming code, then you have to remember to change it everywhere.
You should set the property only if a string is typed, like this:
private void button1_Click(object sender, EventArgs e)
{
var sm = new StudentModel();
if (!string.IsNullOrEmpty(txtFathersName.Text))
sm.SetFather = txtFathersName.Text;
sm.InsertStudent(sm);
}
I am making an online form. I initialise 4 variables in my code at the beginning. When I select a dropdown, an event (DropDownList4_SelectedIndexChanged ) gets fired which in turn call Availability(). Here my boolean variable avail_bus is assigned a value. However, when i click on submit button ( Button1_Click1), the variable avail_bus is reinitialised to false. I debugged this and found out that upon clicking on Submit(Button1_Click1) the control first goes to the top of the code in the page which is
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup = true;
private bool avail_bus ;
private int max_capacity_bus;
private int realAvailability;
}
and then goes to Button1_click1 .
How can I prevent this from happening ? If the state of avail_bus is changed to true while calling availability, it should not get reinitialized to true when i click on submit.
Below is my code :
namespace eTransport
{
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup = true;
private bool avail_bus ;
private int max_capacity_bus;
private int realAvailability;
protected void Page_Load (object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindDropDown();
}
}
//Method called when dropdown is selected in Bus Stop. It helps to populate Bus Number
protected void DropDownList4_SelectedIndexChanged (object sender, EventArgs e)
{
AutoPopulateBusStop();
Availability();
}
//Method to load drop down values in Bus Stop. These are populated from database
protected void BindDropDown ()
{
//some code here
}
//Method to autopopulate Bus Number based on selection of Bus Stop. The mapping is in the database in the table named -> dropdownlist
protected void AutoPopulateBusStop ()
{
//some code here
}
protected void Availability ()
{
string constr5 = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection con5 = new SqlConnection(constr5))
{
try
{
using (SqlCommand cmd5 = new SqlCommand("select count(*) from etms where BusNo='" + TextBox6.Text.ToString() + "'"))
{
cmd5.CommandType = CommandType.Text;
cmd5.Connection = con5;
con5.Open();
int capacity_from_db = Convert.ToInt16(cmd5.ExecuteScalar());
realAvailability = max_capacity_bus - capacity_from_db;
if (realAvailability > 0)
{
avail_bus = true;
TextBox2.Text = realAvailability.ToString() + " seats available ";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
}
else
{
TextBox2.Text = "Seats Not available. Please choose another Stop";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff1919");
}
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
protected void Button1_Click1 (object sender, EventArgs e)
{
if (isNotDup)
{
if (avail_bus)
{
// Submit the Form
}
else
{
Label14.Text = "Bus Seats not available!";
Label15.Text = null;
}
}
}
protected void PhoneNumberValidatation (object source, ServerValidateEventArgs args)
{
//some code here
}
}
}
There are three possible solution for this question.
Static - This will create one instance that accessible to all pages (Global).
private static avail_bus = true;
Session State - This enables you to store and retrieve values for a user as the user navigates.
// Get...
private bool avail_bus = (bool)Session["avail_bus"];
// Set
Session["avail_bus"] = true;
Control.ViewState - Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.
public bool avail_bus
{
get { return ViewState["avail_bus"] == null ? false : (bool)ViewState["avail_bus"]; }
set { ViewState["avail_bus"] = value; }
}
Every time there is a request for your page, a new instance of that page-class is created to handle that request. So any fields are re-initialized.
You can store a value in ViewState to remember a value over various requests:
namespace eTransport
{
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup
{
set { ViewState["isNotDup "] = value; }
get
{
if (ViewState["isNotDup "] == null)
return true;
return (bool )ViewState["isNotDup "];
}
}
private bool avail_bus
{
set { ViewState["avail_bus"] = value; }
get
{
if (ViewState["avail_bus"] == null)
return true;
return (bool )ViewState["avail_bus"];
}
}
private int max_capacity_bus
{
set { ViewState["max_capacity_bus "] = value; }
get
{
if (ViewState["max_capacity_bus "] == null)
return 0;
return (int)ViewState["max_capacity_bus "];
}
}
private int realAvailability
{
set { ViewState["realAvailability"] = value; }
get
{
if (ViewState["realAvailability"] == null)
return 0;
return (int)ViewState["realAvailability"];
}
}
protected void Page_Load (object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindDropDown();
}
}
//Method called when dropdown is selected in Bus Stop. It helps to populate Bus Number
protected void DropDownList4_SelectedIndexChanged (object sender, EventArgs e)
{
AutoPopulateBusStop();
Availability();
}
//Method to load drop down values in Bus Stop. These are populated from database
protected void BindDropDown ()
{
//some code here
}
//Method to autopopulate Bus Number based on selection of Bus Stop. The mapping is in the database in the table named -> dropdownlist
protected void AutoPopulateBusStop ()
{
//some code here
}
protected void Availability ()
{
string constr5 = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection con5 = new SqlConnection(constr5))
{
try
{
using (SqlCommand cmd5 = new SqlCommand("select count(*) from etms where BusNo='" + TextBox6.Text.ToString() + "'"))
{
cmd5.CommandType = CommandType.Text;
cmd5.Connection = con5;
con5.Open();
int capacity_from_db = Convert.ToInt16(cmd5.ExecuteScalar());
realAvailability = max_capacity_bus - capacity_from_db;
if (realAvailability > 0)
{
avail_bus = true;
TextBox2.Text = realAvailability.ToString() + " seats available ";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
}
else
{
TextBox2.Text = "Seats Not available. Please choose another Stop";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff1919");
}
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
protected void Button1_Click1 (object sender, EventArgs e)
{
if (isNotDup)
{
if (avail_bus)
{
// Submit the Form
}
else
{
Label14.Text = "Bus Seats not available!";
Label15.Text = null;
}
}
}
protected void PhoneNumberValidatation (object source, ServerValidateEventArgs args)
{
//some code here
}
}
}
You can store the availability status in a hidden input field which later gets posted on Button1 click event.
And in button1 click event instead of accessing the avail value from variable access it from hiddenField's value
Another option would be calling Availability() again in click event of button1 as a first line so that it sets proper value in the avail_bus variable
I am having this very strange problem where i am creating a list of some objects in one class then trying to access it in another class but it's coming empty in other class:
My first class where i am populating the list:
namespace dragdrop
{
struct BR
{
private string var;
public string Var
{
get { return var; }
set { var = value; }
}
private string equalsTo;
public string EqualsTo
{
get { return equalsTo; }
set { equalsTo = value; }
}
private string output;
public string Output
{
get { return output; }
set { output = value; }
}
private string els;
public string Els
{
get { return els; }
set { els = value; }
}
private string elsOutput;
public string ElsOutput
{
get { return elsOutput; }
set { elsOutput = value; }
}
}
public partial class Form1 : Form
{
//******************
private List<BR> list = new List<BR>(); //This is the list!
//******************
internal List<BR> List
{
get { return list; }
set { list = value; }
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] vars = new string[] { "Name", "Gender", "Age", "Address", "email" };
comboBox1.DataSource = vars;
}
private void button1_Click(object sender, EventArgs e)
{
BR b = new BR();
b.Var = comboBox1.SelectedItem.ToString();
b.EqualsTo = textBox1.Text;
b.Output = textBox2.Text;
list.Add(b);
//*****************
textBox1.Text = List.Count.ToString(); //This gives the correct count value!
//*****************
//this.Close();
}
}
}
I am accessing it in second class like:
namespace dragdrop
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Form1 form = new Form1();
List<BR> l = form.List; ;
//*******************
MessageBox.Show(form.List.Count.ToString()); //This strangely gives count 0!
//*******************
}
}
}
I have even tried making everything public in first class but no matter what i do, im always getting empty list in second class.
The is no relation what-so-ever between Form1 and Ribbon1, how can one then access an instance of the other?
With this:
Form1 form = new Form1(); // new instance of Form1
List<BR> l = form.List; ; // of course the list is empty in a new instance!
you can never access values from another instance of Form1.
Since I have no idea how your classes are connected I cannot give you more advice than have a look at this good overview of OO-relationships. You have to connect them somehow for it to work, I would very much recommend composition // aggregation (same thing, different schools).
All i needed to do was make the list a static member in class one, that solved the issue of having different value when i tried to create a new instance of Form1 in Ribbon1 class.
private static List<BR> list = new List<BR>();
I've been puzzling over this one for a few days now and it's got me pretty beaten, but to be honest I'm not all that experienced yet and I'm having trouble with DataGridView - which seems a common topic.
public partial class frmMain : Form
{
ServerConnection sabCom;
private BindingSource jobSource = new BindingSource();
private void timer1_Tick(object sender, EventArgs e)
{
if (bgUpdateThread.IsBusy == false)
{
bgUpdateThread.RunWorkerAsync(sabCom);
}
}
}
private void frmMain_Load(object sender, EventArgs e)
{
timer1.Interval = 3000;
timer1.Start();
}
private void bgUpdateThread_DoWork(object sender, DoWorkEventArgs e)
{
ServerConnection s = e.Argument as ServerConnection;
s.update();
e.Result = s;
}
private void bgUpdateThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.sabCom = e.Result as ServerConnection;
if (dgvQueueFormatted == false)
{
dgvQueue_Init(); //Applies formatting and loads column width. Inits data sources.
}
else
{
dgvQueue_Update();
}
}
private void dgvQueue_Update()
{
dgvQueue.Refresh();
}
private void dgvQueue_Init()
{
try
{
jobSource.DataSource = sabCom.queue.jobs;
dgvQueue.DataSource = jobSource;
try
{
//Apply saved column spacing to the dgvQueue
//Uses reflection to set dgvQueue to DoubleBuffer
}
catch
{ }
}
catch
{ }
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
//Saves information about the dgvQueue on shutdown.
}
Queue Class:
public class Queue
{
private string _status;
public string status { get { return _status; } set { _status = value; } }
private string _eta;
public string eta { get { return _eta; } set { _eta = value; } }
private List<Job> _jobs;
public List<Job> jobs
{
get
{
return _jobs;
}
set
{
_jobs = value;
}
}
private List<string> _categories;
public List<string> categories { get { return _categories; } set { _categories = value; } }
private XmlDocument xmld;
private ServerConnection m_parent;
private XmlNodeList _xmljobs;
public Queue(ServerConnection srvConn)
{
//fetch the Queue xml
m_parent = srvConn;
xmld = new XmlDocument();
_jobs = new List<Job>();
}
public void update()
{
updateXml();
updateQueue();
updateJobs();
}
private void updateXml()
{
//Loads xml file into xmld
}
private void updateQueue()
{
XmlNodeList elements = xmld.SelectNodes("queue");
foreach (XmlNode element in elements)
{
_status = element.SelectSingleNode("status").InnerText;
_eta = element.SelectSingleNode("eta").InnerText;
}
}
private void updateJobs()
{
_xmljobs = xmld.SelectNodes("queue/job");
jobs.Clear();
foreach (XmlNode xmljob in _xmljobs)
{
Job t_job;
_status = xmljob.SelectSingleNode("status").InnerText;
_eta = xmljob.SelectSingleNode("eta").InnerText;
//Create temp job to match against list.
t_job = new Job(_status, _eta);
jobs.Add(t_job);
}
}
Job class: In reality it holds around 30 values of varying types, but they're all in the same format:
public class Job
{
private int _status;
public int status { get { return _status; } set { _status = value; } }
private string _eta;
public string eta { get { return _eta; } set { _eta = value; } }
public Job(string status, string eta)
{
_status = status;
_eta = eta;
}
}
When interacting with the DataGridView I get the error:
The following exception occured in the DataGridView:
System.IndexOutOfRangeException: Index does not have a value.
at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
at System.Windows.Forms.DataGridViewDataConnection.GetError(Int32 boundColumnIndex, Int32 columnIndex, Int32 rowIndex)
And when entering the debugger it's triggered on the initial Application.Run(new frmMain(). What on earth am I doing wrong? The program still functions and updates normally but I can't even handle the event to suppress the default error message!
Edit - Answer!
Instead of clearing the list and re-creating it, just updating the values within it works better. For the moment I have this code:
t_job = _jobs.FirstOrDefault(c => c.nzo_id == t_nzo_id);
if (t_job == null) //Job not in list, insert
{
t_job = new Job(t_status, i_index, t_eta, i_timeLeft, t_age, i_mbleft, i_mb, t_filename, i_priority, t_category, i_percentage, t_nzo_id, this);
jobs.Add(t_job);
}
else //update object in current list
{
jobs[t_job.Index].status = t_status;
jobs[t_job.Index].priority = i_priority;
jobs[t_job.Index].category = t_category;
jobs[t_job.Index].percentage = i_percentage;
jobs[t_job.Index].timeleft = i_timeLeft;
jobs[t_job.Index].mbleft = i_mbleft;
}
Which prevents it!
The problem seems to be that with a refresh interval of say 1 second, while the user is scrolling or trying to access the fields of the data the data is constantly being removed and readded.
This causes the binding to to call try call a value that it thinks might still be there, but isn't and that is why you are getting the index out of range exception
The first thing I would suggest doing is in your updateJobs method as well as all the other lists that are refreshed like the queue list, instead of clearing the list everytime is first checking to see if the job from the xml exists in the current job list, if it does then you can change the current values if the value has changed otherwise do nothing.
To check if the job exists it is as easy as:
t_job = _jobs.FirstOrDefault(c => c.Filename == t_filename);
This will return a null if the job does not exist, I would assume filename might not be unique, so might want to change it so that it really is unique i.e.
t_job = _jobs.FirstOrDefault(c => c.Filename == t_filename && c.nzo_id == t_nzo_id);
One thing you will now have to cater for is that old jobs won't be automatically removed, so whenever a new history job is added, first check to see if it exists in the queue and then remove it there before adding it to the history list.
so change your properties to be:
public int Index
{
get { return _index; }
set
{
if (_index != value)
_index = value;
}
}
instead of:
public int Index { get { return _index; } set { _index = value; } }
The other thing is that try catch exceptions are expensive, so instead of having:
try { i_percentage = double.Parse(t_percentage); } catch { }
because you know that if there is a value it is going to be a double, you can change it to:
if (!string.IsNullOrEmpty(t_percentage))
i_percentage = double.Parse(t_percentage);
now if you don't know if the value in t_percentage is going to be a double you can use a try-parse:
if (!string.IsNullOrEmpty(t_percentage))
double.TryParse(t_percentage,out i_percentage);
This way you avoid the overhead caused by an exception. This might be micro-optimizing and is not always neccessary if it doesn't actually cause a problem, but given that you can have hundreds of jobs, each with 10 or so properties refreshing everysecond, things can actually get noticeably slower if even 2 of the 10 properties throws an exception.
One more thing, after your backgroundworker is completed, in the method: dgvQueue_Update() you are calling the ResetBindings(true); this causes your whole datagrid to refresh instead of just the individual items.
try changing it to:
for (int i = 0; i < jobSource.List.Count; i++)
jobSource.ResetItem(i);
The difference is this:
this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, itemIndex));
compared to when you say ResetBindings:
this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));