C# - How to list listbox objects by name - c#

I have an Employee class that populates a listbox when I fill in text fields and click an add button. When the item gets added to the list it displays the object property and I need to figure out how to store the object in the list, but also list it by name.
Here's my Employee class:
class Employee
{
public string Name;
public string Position;
public DateTime BirthDate;
public DateTime StartDate;
public decimal Wage;
public Employee(string name, string position, DateTime birthDate, DateTime startDate, decimal wage)
{
Name = name;
Position = position;
BirthDate = birthDate;
StartDate = startDate;
Wage = wage;
}
}
Here is my button click event: (Where I populate the list)
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
var employees = new List<Employee>();
var name = txtName.Text;
var position = txtPosition.Text;
DateTime birthDate = dpBirthDate.Date.DateTime;
DateTime startDate = dpStartDate.Date.DateTime;
var wageValue = txtWage.Text;
decimal wage = Decimal.Parse(wageValue);
employees.Add(new Employee(name, position, birthDate, startDate, wage));
foreach(Employee employee in employees)
{
lbEmployee.Items.Add(employee);
}
}
For the button click event in my for each loop I tried to list the object by doing this
foreach(Employee employee in employees)
{
lbEmployee.Items.Add(employee.Name);
}
This lists it by name but doesn't add the entire object so it breaks the function below
private void lbEmployee_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
{
Employee employee = (Employee)lbEmployee.SelectedItem;
if (employee != null)
{
txtName.Text = employee.Name;
txtPosition.Text = employee.Position;
dpBirthDate.Date = employee.BirthDate;
dpStartDate.Date = employee.StartDate;
txtWage.Text = Convert.ToString(employee.Wage);
}
}

You have to set
lbEmployee.DisplayMember = "Name";
in the designer and then you can add the employee in the items avoiding to break your function

Related

How do I make it so that the values from the 'combobox' can be selected?

I work in Windows Forms. I have a combobox ('Departments' name) it contains a list of departments. By selecting a department in comboBox1(Staff), employees working in this department appear. But I can't select an employee, because they are not displayed
Code, filling in comboBox1(Staff). dataNames - dictionary(department name - array of employees)
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (Departaments.SelectedItem != null)
{
this.Staff.Items.Clear();
var dataNames = DataForComdodox.ArrNames(Departaments.SelectedItem.ToString());
this.Staff.Items.AddRange(dataNames);
}
}
Code in Form1.Designer - comboBox1(Staff)
this.Staff.DrawMode = System.Windows.Forms.DrawMode.Normal;
this.Staff.FormattingEnabled = true;
this.Staff.Items.AddRange(new object[] {
});
this.Staff.Location = new System.Drawing.Point(374, 84);
this.Staff.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Staff.Name = "Staff";
this.Staff.Size = new System.Drawing.Size(158, 21);
this.Staff.TabIndex = 0;
this.Staff.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
I tried to change Staff.SelectedIndex = 0, after I fill comboBox1(Staff) with values, but in the end, when choosing a department, an employee was selected automatically with an index of 0
If var dataNames = DataForComdodox.ArrNames(xx) returns a list or array of class employees, you could override the ToString() in the employee class.
public class Employee
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public string DeptName { get; set; }
public override string ToString()
{
return $"{this.EmpId}: {this.EmpName}";
}
}

SelectedValue then get data from database

ConfigurationDAL dAL = new ConfigurationDAL();
DataTable dt = new DataTable();
if(drp_Volunteeer.SelectedValue !=null)
{
dt = dAL.FetchVolunteerDetails(volunteerID: drp_Volunteeer.SelectedIndex).Tables[0];
foreach (DataRow dr in dt.Rows)
{
txt_FirstName.Text = dr["firstname"].ToString();
txt_fatherName.Text = dr["fathername"].ToString();
}
}
SelectedValue count shows 32:
SelectedIndex works fine:
Filling the TextBox is not working.
User Not Selected
User Selected
When I User Select Data Can't Revtive Data From DataBase:
I don't know how you can fill (add) data to SelectedBox. But you maybe know, SelectedBox's Items supports any object, you can add any objects to items. I usually create my custom class for filling SelectedBoxs. For Example, you can create Volunteeer class for adding, and viewing data on the SelectedBox. Example:
public class Volunteeer
{
private int id;
private string firstname;
private string lastname;
public Volunteeer(int pid, string fname, string lname)
{
id = pid;
firstname = fname;
lastname = lname;
}
public string GetFirstName()
{
return firstname;
}
public string GetLastName()
{
return lastname;
}
public int GetId()
{
return id;
}
public override string ToString()
{
return firstname + ' ' + lastname;
}
}
Method ToString() are for viewing text data format on the SelectedBox. After then you can very easily get selected items. Example:
private void SelectedText_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (SelectedText.SelectedIndex >= 0)
{
txtFirstName.Text = (SelectedText.SelectedValue as Volunteeer).GetFirstName();
txtLastName.Text = (SelectedText.SelectedValue as Volunteeer).GetLastName();
}
}
And this is a sample how you can fill data to SelectedBox:
SelectedText.Items.Add(new Volunteeer(1, "Sara", "Montano"));
SelectedText.Items.Add(new Volunteeer(2, "Jon", "Smith"));
SelectedText.Items.Add(new Volunteeer(3, "Tom", "Serato"));

Comparing a Date from an SQLite Database to the current DateTime in C#, Xamarin Forms

So I have generated a SQLite database in Xamarin Forms. Each item has a Name and Date. I'm trying to extract the date and set it to a variable so that when each item is loaded, it will convert its date integer to DateTime and compare it to DateTime.Now.
I'm not sure how to do this, and I might be missing something very elementary- I'm a complete beginner.
public LivePage()
{
InitializeComponent();
LiveService.AddLive("2022年3月19日(土): ILLUSION FORCE presents「ILLUSION FORCE×GAUNTLET LONGSTAGE 'GACHINKO'2MAN GIG」", 20220319);
LiveService.AddLive("2022年3月20日(日)Phantom Excaliver presents 聖剣フェス」", 202203020);
LiveService.AddLive("2022年4月2日(土)Bad Company vol.17」", 20220402);
LiveService.AddLive("2022年4月10日(日)VELL'z FIRE presents", 20220410);
LiveService.AddLive("2022年4月10日(日)ILLUSION FORCE presents「ILLUSION FORCE×Amiliyah LONG STAGE 2MAN GIG」", 20220410);
LiveService.AddLive("2022年4月29日(金・祝)渋谷メタル会 presents 渋谷メタル会フェス 2022」", 20220429);
var Lists = LiveService.db.Table<Live>().ToList();
MainListView.ItemsSource = Lists;
int dateInt = Lists[2];
DateTime dater = Convert.ToDateTime(dateInt);
int result = DateTime.Compare(dater, DateTime.Now);
if (result < 0)
{
Label.TextDecorations = TextDecorations.Strikethrough;
}
How I created the Table
namespace IF2.Models
{
public class Live
{
public string Name { get; set; }
public string Date { get; set; }
public string Place { get; set; }
public string Time { get; set; }
}
}
Service File
public static SQLiteConnection db;
static void Init()
{
if (db != null)
return;
// Get an absolute path to the database file
var databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Lives.db3");
db = new SQLiteConnection(databasePath);
db.DropTable<Live>();
db.CreateTable<Live>();
}
public static void AddLive(string name, string date)
{
Init();
var live = new Live
{
Name = name,
Date = date,
};
var id = db.Insert(live);
}
public static void GetProperties()
{
Init();
var Lists = db.Table<Live>().ToList();
}
}
}
In your code public static void AddLive(string name, string date), you set the type of the date as string.
At first, try to get the data list, because there isn't only one line data in the table.
var stringlist = new List<string>()
// var intlist = new List<int>()
foreach(item in Lists)
{
var live = item as Live()
list.Add(live.Date)
//intlist.Add(int.Parse(live.Date))
}
Get the date time now:
string nowTime = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
// and the value of the string will be like "20220322"
And then you can compare them with the "==" such as:
var value = (nowTime == stringlist[i])
You can also compare them in the foreach(item in Lists) and needn't to get the list of the date.
Create a model class as a table. You need to give it a primary key and the attribute named table.
[Table("Live")]
public class Live
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public string Date { get; set; }
public string Place { get; set; }
public string Time { get; set; }
}
Sorry I had to delete my previous comments. I was mistaken about SQLite being able to cast the date data as a DateTime object. Therefore, I can throw out a simple parser that will convert the string value of the date data.
If the data is bad then today’s date is returned, however you could return any date. You could use it like…
DateTime dater = GetDTFromString(dateInt.ToString());
The parser...
private DateTime GetDTFromString(string dateString) {
if (dateString.Length >= 8) {
string year = dateString.Substring(0, 4);
string month = dateString.Substring(4, 2);
string day = dateString.Substring(6, 2);
if (DateTime.TryParse(year + "," + month + "," + day, out DateTime targetDate)) {
return targetDate;
}
}
return DateTime.Now;
}

C# Better implementation of JSON file

This is homework so if you can help thank you, if not I understand.
Everything work as intended. But I feel like I could implement things better or have cleaner code. I would like the button to just call a method that reads the JSON file, runs the inquiry and puts out the correct display without duplicating the code like I have.
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace EmployeePayDataWk4
{
public partial class Employee_Pay_Form : Form
{
public Employee_Pay_Form()
{
InitializeComponent();
}
private void Employee_Pay_Form_Load(object sender, EventArgs e)
{
EmployeeDataGridView.ColumnCount = 8;
EmployeeDataGridView.Columns[0].Name = "Employee Name";
EmployeeDataGridView.Columns[1].Name = "Zip Code";
EmployeeDataGridView.Columns[2].Name = "Age";
EmployeeDataGridView.Columns[3].Name = "Monthly Gross Pay";
EmployeeDataGridView.Columns[4].Name = "Department ID";
EmployeeDataGridView.Columns[5].Name = "Developer Type";
EmployeeDataGridView.Columns[6].Name = "Annual Taxes";
EmployeeDataGridView.Columns[7].Name = "Annual Net Pay";
}
private void LoadAllButton_Click(object sender, EventArgs e)
{
EmployeeDataGridView.Rows.Clear();
//Read from JSON file
string JSONstring = File.ReadAllText("JSON.json");
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
//Display into DataGridView
foreach (Employee emp in employees)
{
string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
EmployeeDataGridView.Rows.Add(row);
}
}
private void FTEmployeeButton_Click(object sender, EventArgs e)
{
EmployeeDataGridView.Rows.Clear();
//Read from JSON file
string JSONstring = File.ReadAllText("JSON.json");
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
//LINQ Query for FT Employees
var FTEmp = from emp in employees
where emp.GetTaxForm == "W2"
select emp;
//Display into DataGridView
foreach (Employee emp in FTEmp)
{
string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
EmployeeDataGridView.Rows.Add(row);
}
}
private void ContractEmployeeButton_Click(object sender, EventArgs e)
{
EmployeeDataGridView.Rows.Clear();
//Read from JSON file
string JSONstring = File.ReadAllText("JSON.json");
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
//LINQ Query for Contract Employees
var contractEmp = from emp in employees
where emp.GetTaxForm == "1099"
select emp;
//Display into DataGridView
foreach (Employee emp in contractEmp)
{
string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
EmployeeDataGridView.Rows.Add(row);
}
}
//Method to determine developer type
string typeName;
public string SetDevType(int id)
{
if (id == 1)
{
typeName = "Object-Oriented";
}
else if (id == 2)
{
typeName = "Scripts";
}
else { typeName = "Unknown"; }
return typeName;
}
public double AnnualPay(double amount) => 12 * amount;
}
class Employee : IFilingStatus
{
public Employee() { }
public string Name { get; set; }
public string Zip { get; set; }
public int Age { get; set; }
public double Pay { get; set; }
public int DepartmentId { get; set; }
public string GetTaxForm { get; set; }
public double CalculateTax(double basis)
{
double monthlyTax;
if ((GetTaxForm == "W2") || (GetTaxForm == "w2"))
{
monthlyTax = .07 * basis;
}
else
{
monthlyTax = 0;
}
return 12 * monthlyTax;
}
public double AnnualPay(double amount) => 12 * amount;
}
public interface IFilingStatus
{
double CalculateTax(double basis);
}
}
I would say this line:
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
should be
IList<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
for this reason.
local variables, private fields and parameters should be lowercase camel case, according to StyleCop:
string jsonString = File.ReadAllText("JSON.json");
The other thing is don't repeat yourself (DRY). These few lines can be refactored to be a separate method:
string JSONstring = File.ReadAllText("JSON.json");
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
//LINQ Query for Contract Employees
var contractEmp = from emp in employees
where emp.GetTaxForm == "1099"
select emp;
In SetDevType you can totally use switch/case, which performs better.
string typeName; // why do we need this?
private string SetDevType(int id)
{
string typeName = string.Empty;
switch(id){
case 1: typeName = "Something"; break;
default: typeName = "Unknown";
}
return typeName;
}
some members of the class don't need to be public, such as
public double AnnualPay(double amount) => 12 * amount;
can be
private double AnnualPay(double amount) => 12 * amount;
and this method is somehow also in the Employee class, which is a Model class/POCO. POCO classes usually don't contain non-properties (although sometimes ToString and an empty constructor are included).
As I can see your Click event handlers are very similar.
I see only one change:
In your FTEmployeeButton_Click event handler you filter data like that:
var contractEmp = from emp in employees
where emp.GetTaxForm == "1099"
select emp;
And in ContractEmployeeButton_Click event handler you filter data like that:
var FTEmp = from emp in employees
where emp.GetTaxForm == "W2"
select emp;
Other code looks very similar. So we can define your code to one separate method...
But we need understand how filter your data.
For this purpose I suggest to use Tag property of Button class.
In this property you can save any object. In your case you can save GetTaxForm value.
So you can use only one event handler for all your buttons.
Please look next realization:
private void OnButton_Click(object sender, EventArgs e)
{
EmployeeDataGridView.Rows.Clear();
//Read from JSON file
string JSONstring = File.ReadAllText("JSON.json");
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
object filter = ((Control)sender).Tag;
List<Employee> FTEmp;
if (filter != null) {
//LINQ Query for FT Employees
FTEmp = from emp in employees
where emp.GetTaxForm == filter.ToString()
select emp;
}
else
{
FTEmp = employees.ToList();
}
//Display into DataGridView
foreach (Employee emp in FTEmp)
{
string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
EmployeeDataGridView.Rows.Add(row);
}
}

Fill DropDownList inside Gridview with corresponding items using Entity Framework

protected void GridViewTicketHistory_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow )
{
DropDownList drpnop = (DropDownList)e.Row.FindControl("DropDownList1");
if (drpnop != null)
{
foreach (Ticket ticket in entities.Tickets)
{
foreach (State state in entities.States)
{
if (ticket.StateID == state.StateID)
{
drpnop.DataTextField = state.StateName;
drpnop.DataValueField = state.StateID.ToString();
}
}
}
drpnop.DataBind();
}
}
}
DataBind
protected void editCustomerTicket()
{
GridViewTicketHistory.AutoGenerateEditButton = true;
DataTable dat = new DataTable();
int ticketno = Convert.ToInt32(Session["TicketNo"]);
var a = from employee in entities.Employees
from ticket in employee.EmployeeTicket
select new
{
employee.ID,
employee.Name,
ticket.TicketNo,
ticket.Subject,
ticket.Date,
ticket.State.StateName
};
GridViewTicketHistory.DataSource = a;
GridViewTicketHistory.DataBind();
}
Problem
I use entity framework I have State and Tickets tables.Tickets has navigation property to State.(tickets.StateID).In
this code i tried to see each drop down list with corresponding states
if i use Command.Writeline i can see that state.StateName and
state.StateID are not empty and right values.However i see empty
values when i fill dropdownlist.
My Goal
My main goal is to see corresponding value on
Dropdownlist but also be able to choose fix items from these drop
downlist. Let say StateID=0 StateName=Started StateID=1 StateName=%25
progress StateID=2 StateName=finished Each individual ticket has state
Id and name and want to show it in all rows according to that
ticket.Also choose from the fixed list that has StateID= 0,1,2.
The first thing you need to do is avoid using anonymous type when getting the data for GridViewTicketHistory, because you'll need to convert e.Row.DataItem back to a predefined type to set the selected item of the dropdownlist. I would suggest the following class
public class TicketHistory
{
public int ID { get; set; }
public string Name { get; set; }
public string TicketNo { get; set; }
public string Subject { get; set; }
public string Date { get; set; }
public int? StateID { get; set; }
public string StateName { get; set; }
}
Change editCustomerTicket method as below so the type of a would be a List<TicketHistory> instead of an anonymous type.
protected void editCustomerTicket()
{
GridViewTicketHistory.AutoGenerateEditButton = true;
var a = (from employee in entities.Employees
from ticket in employee.EmployeeTicket
select new TicketHistory
{
ID = employee.ID,
Name = employee.Name,
TicketNo = ticket.TicketNo,
Subject = ticket.Subject,
Date = ticket.Date,
StateID = ticket.StateID,
StateName = ticket.State.StateName
}).ToList();
GridViewTicketHistory.DataSource = a;
GridViewTicketHistory.DataBind();
}
When binding the dropdownlist, you have to set the DataSource property before calling .DataBind() or add the Items element using a loop. The code below populates the dropdownlist items using a loop and sets the selected value of the dropdownlist according to the StateID of the ticket.
protected void GridViewTicketHistory_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drpnop = (DropDownList)e.Row.FindControl("DropDownList1");
if (drpnop != null)
{
// populate drpnop items
foreach (State state in entities.States)
{
drpnop.Items.Add(new ListItem(state.StateName, state.StateID.ToString()));
}
// set the selected value of drpnop according to StateID of the ticket
TicketHistory data = (TicketHistory)e.Row.DataItem;
if (drpnop.Items.FindByValue(data.StateID.ToString()) != null)
{
drpnop.Items.FindByValue(data.StateID.ToString()).Selected = true;
}
}
}
}

Categories

Resources