In my table, I have a field of firstname and lastname, now what I want is to set firstname and lastname as displaymember in a combobox, but I don't know how to do it.
Something like this
cmbEmployees.DataSource = GetEmployees();
//something like below line which doesn't work
cmbEmployees.DisplayMember = "lastname, first_name";
cmbEmployees.ValueMember = "id";
How can I achieve this? So that both lastname and firstname will be displayed in the combobox
This example will guide you how to do that without modifying your base class.
First, you can leave your DisplayMember with one property, let's say:
cmbEmployees.DisplayMember = "lastname";
Now, go to your form in a [Design] mode,
right click on the ComboBox -> Properties.
In the top of the Properties window, click on Events (lightning icon),
look for Format in the events list below (under Property Changed) and type there some event name, let's say: ComboBoxFormat , and press Enter. You will see this:
private void ComboBoxFormat(object sender, ListControlConvertEventArgs e)
{
}
And now write these following lines inside:
private void ComboBoxFormat(object sender, ListControlConvertEventArgs e)
{
// Assuming your class called Employee , and Firstname & Lastname are the fields
string lastname = ((Employee)e.ListItem).Firstname;
string firstname = ((Employee)e.ListItem).Lastname;
e.Value = lastname + " " + firstname;
}
That's it ;)
Let's say you had a class like this:
class Person
{
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public string FullName
{
get
{
return LastName + ", " + FirstName;
}
}
public Person(string firstname, string lastname)
{
FirstName = firstname;
LastName = lastname;
}
}
If you don't have a FullName property, just create one in the format you wish to display the name. Then set the DisplayMember equal to FullName.
Your query should be like this in GetEmployees() function.
"SELECT id,(lastname + ' ' + first_name) AS NAME FROM TABLE"
cmbEmployees.DataSource = GetEmployees();
cmbEmployees.DisplayMember = "NAME";
cmbEmployees.ValueMember = "id";
in C# 6 create readonly property in your Employee class
public string FullName=>$"{lastname} {firstname}";
then
cmbEmployees.DataSource = GetEmployees();
//something like below line which doesn't work
cmbEmployees.DisplayMember = "FullName";
cmbEmployees.ValueMember = "id";
Try one of those approaches:
new Dictionary with concatenated fields as value - https://stackoverflow.com/a/1006588/1816426
calculated column - https://stackoverflow.com/a/1006546/1816426
CREATE VIEW [dbo].[get_view]
AS
SELECT CONCAT(sell_tb.Name,extra_tb.Name,purchase_tb.Name) AS Name FROM sell_tb FULL JOIN extra_tb ON extra_tb.E_ID = sell_tb.E_ID
FULL JOIN purchase_tb ON purchase_tb.S_ID = sell_tb.S_ID;
private void alldata1()
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [get_view]";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Name";
conn.Close();
}
// Declare a class
private class ComboRec
{
public string ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get; set; }
public string Department { get; set; }
}
// Fill the Combo Items
private void FillMyComboList()
{
EmployeesCombo.Items.Clear();
EmployeesCombo.ValueMember = "ID";
EmployeesCombo.DisplayMember = "FullName";
MySqlCommand cmd = new MySqlCommand("select id, firstname, lastname, department from employees order by lastname, firstname", MyConnection);
cmd.Transaction = myTransaction;
MySqlDataReader rdr = cmd.ExecuteReader();
ComboRec comborec;
while (rdr.Read())
{
comborec = new ComboRec();
comborec.ID = rdr["id"].ToString();
comborec.FirstName = rdr["firstname"].ToString();
comborec.LastName = rdr["lastname"].ToString();
comborec.FullName = rdr["lastname"].ToString() + ", " + rdr["firstname"].ToString();
comborec.Department = rdr["department"].ToString();
EmployeesCombo.Items.Add(comborec);
}
rdr.Close();
}
// Get the values from combo
string id = ((ComboRec)EmployeesCombo.SelectedItem).ID);
string firstname = ((ComboRec)EmployeesCombo.SelectedItem).FirstName);
string lastname = ((ComboRec)EmployeesCombo.SelectedItem).LastName);
string fullname = ((ComboRec)EmployeesCombo.SelectedItem).FullName);
string department = ((ComboRec)EmployeesCombo.SelectedItem).Department);
public void alldata1()
{
var Person= context.Person.Select(s => new {
display = s.surName+" "+s.name,
value = s.studentID
});
comboBoxStudentNom.DataSource = Person.ToList();
comboBoxStudentNom.ValueMember = "value";
comboBoxStudentNom.DisplayMember = "display";
}
Related
[edit:I added the data visualizer]
I have a teacher's registration where records are being input using an insert button in a SQL database as such
private void insertdata(object sender, RoutedEventArgs e)
{
try
{
string name = name_field.Text;
string email = email_field.Text;
string id = id_field.Text;
string gender;
if (male.IsChecked == true)
{
gender = "M";
}
else
gender = "F";
if (String.IsNullOrEmpty(dob.Text))
{
string fe = "01/01/1900 12:00:00 AM";
dt = Convert.ToDateTime(fe);
}
else
{
dt = Convert.ToDateTime(dob.Text);
}
var rich1 = new TextRange(this.history.Document.ContentStart, this.history.Document.ContentEnd);
string teach_history = rich1.Text;
var rich2 = new TextRange(this.achievement.Document.ContentStart, this.achievement.Document.ContentEnd);
string teach_achievement = rich2.Text;
connect();
con.Open();
string saved = "insert into teacher_details ([Teacher ID],Name,Gender,Email,[Date of Birth],Employment History,Achievements)values('" + id + "', '" + name + "','" + gender + "','" + email + "','" + dt + "','" + teach_history + "','" + teach_achievement + "')";
SqlCommand cmd = new SqlCommand(saved, con);
cmd.ExecuteReader();
con.Close();
MessageBox.Show("record is added");
}
catch(Exception ex)
{
MessageBox.Show("error occured " + ex);
}
I have id,gender,name,email,history,achievements,date of birth as my fields. I made a class for this as follows:
class Teacherdetail
{
public string id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string gender { get; set; }
public string history { get; set; }
public string acheive { get; set; }
public DateTime dob { get; set; }
}
in my rdlc report i used object as my dataset and selected Teacherdetail. Then I made a table as follow:
i then have a button view report where I call details into the reportviewer that is called teacherreport
ReportDataSource reportDataSource = new ReportDataSource();
connect();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("select [Teacher ID],Name,Gender,email,[Date of Birth],[Employment History],Achievements from teacher_details", con);
DataTable newtab = new DataTable();
adp.Fill(newtab);
reportDataSource.Name = "DataSet1";
reportDataSource.Value = newtab;
teacherreport.LocalReport.ReportPath = "C:\\Users\\Preeti Rawat\\Documents\\Visual Studio 2012\\Projects\\STDNT\\STDNT\\teacherreport.rdlc";
teacherreport.LocalReport.DataSources.Add(reportDataSource);
teacherreport.LocalReport.Refresh();
teacherreport.RefreshReport();
My problem is that id, history, name and achieve are missing.
When I debug the program, in my data visualizer it does show that the information is passing through.
but it is still not appearing when in the program. What can the problem be and how can I fix it? Thank you ^^
For your specific question, in your insertdata, you are calling ExecuteReader to insert a new record, and it's wrong. You need to call ExecuteNonQuery to INSERT, UPDATE, DELETE actions.
Also, in :
string saved = "insert into teacher_details ([Teacher ID],Name,Gender,Email,[Date of Birth],Employment History,Achievements)values('" + id + "', '" + name + "','" + gender + "','" + email + "','" + dt + "','" + teach_history + "','" + teach_achievement + "')";
this should return a SQL error, since Employment History not contained by brackets [].
Here is a revised version of your method. (I've tried to kept the same work).
var name = name_field.Text;
var name = name_field.Text;
var email = email_field.Text;
var id = id_field.Text;
var gender = male.IsChecked ? "M" : "F";
var dt = DateTime.TryParse(dob.Text, out DateTime result) ? result : new DateTime(1900,1,1);
var teach_history = new TextRange(this.history.Document.ContentStart, this.history.Document.ContentEnd).Text;
var teach_achievement = new TextRange(this.achievement.Document.ContentStart, this.achievement.Document.ContentEnd).Text;
const string query = "INSERT INTO teacher_details([Teacher ID],Name,Gender,Email,[Date of Birth],[Employment History],Achievements) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}'); ";
var saved = string.Format(query, id, name, gender, email, dt.ToString("yyyy-MM-ddThh:mm:ss"), teach_history, teach_achievement)
connect();
con.Open();
using(var cmd = new SqlCommand(saved, con))
{
cmd.ExcuteNonQuery();
}
con.Close();
MessageBox.Show("record is added");
you should use using blocks on SqlConnection or Dispose your connection manually. Also, I suggest you start using Entity Framework instead for database operations.
For the report part, you need to do this :
var table = new DataTable();
const string query = "SELECT [Teacher ID],Name,Gender,email,[Date of Birth],[Employment History],Achievements from teacher_details";
connect();
con.Open();
var adapter = new SqlDataAdapter(query, con);
adapter.Fill(table);
var reportDataSource = new ReportDataSource("Dataset1", table);
teacherreport.LocalReport.ReportPath = "C:\\Users\\Preeti Rawat\\Documents\\Visual Studio 2012\\Projects\\STDNT\\STDNT\\teacherreport.rdlc";
teacherreport.LocalReport.DataSources.Clear();
teacherreport.LocalReport.DataSources.Add(reportDataSource);
teacherreport.LocalReport.Refresh();
teacherreport.RefreshReport();
The reason this was not working was that the class names were different from the table's field name. They have to be the same. So I changed column names of my database table so that it looks like this:
Teacher_ID,Name,Gender,Email,Date_of_Birth,Employment_History,Achievements
and my class looks like this:
public int Teacher_ID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string email { get; set; }
public DateTime Date_of_Birth { get; set; }
public string Employment_History { get; set; }
public string Achievements { get; set; }
With a list of struct as the Datasource for a Listbox, I am getting the Object.ToString() rather than the expected field value from the struct
This was working OK when I assigned a DataTable as the DataSource after setting the DisplayMember.
However, I wanted to try using a list of struct (int ID, String Name) instead and despite having set DisplayMember to "Name" before assigning the Datasource to the List I get the row object.toString().
Any help would be fantastic.
On Form Load:
private void frmTestProof_Load(object sender, EventArgs e)
{
TestMaker tm = new TestMaker();
tm.LoadMakersToListbox(ref lstboxMaker);
}
class TestMaker
{
public struct MakerRecord
{
public int MakerID;
public String MakerName;
public MakerRecord(int ID, String Name)
{
MakerID = ID;
MakerName = Name;
}
}
public SQLiteConnection DBconn;
public String thisPath = "";
public SQLiteCommand sqlCommand = new SQLiteCommand();
public DataSet dsMaker = new DataSet();
public SQLiteDataAdapter daMaker = new SQLiteDataAdapter();
public TestMaker()
{
thisPath = "c:\\sqlite\\abc.db";
DBconn = new SQLiteConnection(String.Format("Data Source={0};Version=3;", thisPath));
DBconn.Open();
sqlCommand.Connection = DBconn;
sqlCommand.CommandType = CommandType.Text;
}
public List<MakerRecord> GetListOfMakers()
{
List<MakerRecord> makerList = new List<MakerRecord>();
String sqlMaker = "SELECT ID, VehicleMakerName FROM VehicleMakers WHERE VehicleMakerName IS NOT NULL"
;
sqlCommand.CommandText = sqlMaker;
daMaker.SelectCommand = sqlCommand;
try
{
daMaker.Fill(dsMaker, "Makers");
makerList = (from item in dsMaker.Tables["Makers"].AsEnumerable()
select new MakerRecord()
{
MakerID = Convert.ToInt32(item["ID"]),
MakerName = item["VehicleMakerName"].ToString()
}).ToList();
}
catch (Exception ex)
{
MessageBox.Show(String.Format("List of Makers - Error ({0})", ex.Message));
}
return makerList;
}
public void LoadMakersToListbox(ref ListBox lb)
{
lb.Items.Clear();
lb.ValueMember = "MakerID";
lb.DisplayMember = "MakerName";
lb.DataSource = GetListOfMakers();
}
}
Change public String MakerName; to public string MakerName {get;set;} and public int MakerID; to public int MakerID {get;set;}
I'm relatively new in C# and in this website.
I'm currently trying to make this application that stores employees' data (e.g. name, surname, id number, salary) and shows the selected employee's data upon command.
My problem is that I do not know what kind of class to create and how to build it as well as how to call it each time I click the "save button" to create a new instance of that class which will save the data drawn from the Form's textboxes.
I have searched in forums and have managed to write this inside the Form:
private void button1_Click(object sender, EventArgs e) {
Employee newemployee = new Employee();
{
string fname = textBox1.Text;
string sname = textBox2.Text;
string id = textBox3.Text;
string sal = textBox4.Text;
label5.Text = fname;
label6.Text = sname;
label7.Text = id;
label8.Text = sal;
}
}
and this inside the class:
public class Employee {
public string fname { get; set; }
public string sname { get; set; }
public string id { get; set; }
public string sal { get; set; }
}
but as a result ofcourse, the class is not used at all (obviously because its not completed) and labels are printed straight through the textboxes.
Note: I put the labels there in order to test the class during the process.
In your class, you have already created string values, which will be created when you create the instance of your class:
Employee newemployee = new Employee();
This creates memory space for all the variables declared in your class
public class Employee
{
public string fname { get; set; }
public string sname { get; set; }
public string id { get; set; }
public string sal { get; set; }
}
What you are doing is then creating additional strings by saying:
string fname = textBox1.Text;
string sname = textBox2.Text;
string id = textBox3.Text;
string sal = textBox4.Text;
So to when you initialize the class it created the variables which you should use for that instance of the class. The following code represents the initializing of the class and using its variables from your example code:
Employee newemployee = new Employee();
newemployee.fname = textBox1.Text;
newemployee.sname = textBox2.Text;
newemployee.id = textBox3.Text;
newemployee.sal = textBox4.Text;
label5.Text = newemployee.fname;
label6.Text = newemployee.sname;
label7.Text = newemployee.id;
label8.Text = newemployee.sal;
Hope that helps and it explains where you went wrong.
You're not initialising your class in your calling script, so it can't see it. I suggest having a read of the MS Docs:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes
It has an example that does pretty much what you need it to do.
You would instantiate your class like this:
Employee newEmployee = new Employee()
{
fname = textBox1.Text,
sname = textBox2.Text,
id = textBox3.Text,
sal = textBox4.Text
};
and then write a method to save your Employee in a database/file which you call after instantiating in the click event.
you can create instance and from the class and set the properties
Employee newEmp = new Employee();
newEmp.fname = textBox1.Text;
newEmp.sname = textBox2.Text;
newEmp.id = textBox3.Text;
newEmp.sal = textBox4.Text;
I want to take a list of employees with 3 parts, employee id, last name and first name and add them to a drop down list showing last name, first name.
What I have so far is that I created a class for the employees:
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
and created a list to populate:
private List<Employee> employeeList = new List<Employee>();
this list is populated from a sql query and then sorted by last name.
foreach (DataRow row in ds.Tables["EMPLOYEE_TABLE"].Rows)
{
employeeList.Add(new Employee(int.Parse(row["EMP_ID"].ToString()),
row["LAST_NAME"].ToString(), row["FIRST_NAME"].ToString()));
}
employeeList.Sort(delegate(Employee E1, Employee E2) { return E1.lastName.CompareTo(E2.lastName); });
and everything up to that point worked exactly as I wanted it to but I cannot figure out how I populate a dropdownlist with the last name and first name values contained in the list.
code has been edited for readability
See code below:
DropDownList ddl = new DropDownList();
ddl.DataSource = employeeList;
ddl.DataTextField = "fullName";
ddl.DataValueField = "emp_Id";
I would also modify your class to include a full name field:
public class Employee
{
public int emp_Id { get; set; }
public string lastName { get; set; }
public string firstName { get; set; }
public string fullName
{
get
{
return String.Format("{0} {1}", this.firstName, this.LastName);
}
}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
You could add an extra property to your class that will hold the 3 values, and use this as your DataTextField when binding the DropDownList:
Class Code
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public string Text
{
get { return this.ToString(); }
}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
public override string ToString()
{
return lastName + " " + firstName + " " + emp_Id;
}
}
HTML:
List<Employee> employees = new List<Employee>();
ddl.DataSource = employees;
ddl.DataValueField = "emp_Id";
ddl.DataTextField = "Text";
ddl.DataBind();
Good luck!
Example with existing properties:
<asp:DropDownList id="bla" runat="server" />
bla.DataSource = employeeList;
bla.DataTextField = "firstName";
bla.DataValueField = "emp_Id"
bla.DataBind();
I recommend this:
<asp:DropDownList id="bla" runat="server" />
bla.DataSource = employeeList;
bla.DataTextField = "fullName";
bla.DataValueField = "emp_Id"
bla.DataBind();
public class Employee
{
public int emp_Id;
public string lastName;
public string firstName;
public string fullName get{ return firstName + " " + lastName;}
public Employee(int id, string last, string first)
{
this.emp_Id = id;
this.lastName = last;
this.firstName = first;
}
}
Why don't you create a property called FullName to gets "FirstName + ' ' + LastName"? That would give you one field to deal with instead of two.
If you don't want or can't modify Employee, you may also try something along those lines:
var data = employee.Select (x =>
new KeyValuePair<int, string>(
x.emp_Id,
string.Format("{0}, {1}", x.lastName, x.firstName)
));
ddl.DataSource = data.ToList();
ddl.DataValueField = "Key";
ddl.DataTextField = "Value";
ddl.DataBind();
This may also be useful if you have different pages with different dropdowns for employees, sometimes with Lastname first, sometimes with Firstname first, and maybe with and without a colon in between ...
How can i show Data from a class into a gridview?
MY Class is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class EmployeeDetails
{
private int employeeID;
public int EmployeeID
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
private string firstName;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
private string lastName;
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
private string titleOfCourtesy;
public string TitleOfCourtesy
{
get
{
return titleOfCourtesy;
}
set
{
titleOfCourtesy = value;
}
}
public EmployeeDetails(int employeeID, string firstName, string lastName, string titleOfCourtesy)
{
EmployeeID = employeeID;
FirstName = firstName;
LastName = lastName;
TitleOfCourtesy = titleOfCourtesy;
}
}
I`ve done this:
protected void Page_Load(object sender, EventArgs e)
{
int id = 15;
string f_name = "asd";
string l_name = "asd";
string title = "asd";
EmployeeDetails emp = new EmployeeDetails(id,f_name,l_name,title);
emp.EmployeeID = id;
emp.FirstName = f_name;
emp.LastName = l_name;
emp.TitleOfCourtesy = title;
}
List<EmployeeDetails> lst = new List<EmployeeDetails>() ;
GridView1.DataSource = lst ;
GrdiView1.DataBind();
you may populate the list with your EmployeeDetails Objects
A GridView is generally used to display multiple objects/rows. To get it to display your class you need to make a collection containing your class, such as a List<EmployeeDetails>. Then bind that to your gridview.
You could use another control more suited to displaying a single object such as a DetailsView.
I assume you are looking for an answer to show multiple item instead of just 1.
C#
var myList = List<EmploymentDetails>();
foreach (var employee in SomeOtherDataSource)
{
EmployeeDetails emp = new EmployeeDetails{EmployeeID = id, FirstName = f_name, LastName = l_name, TitleOfCourtesy = title};
myList.Add(emp);
}
var EmployeeDS = from eds in myList select new { ID = EmployeeID, FName = FirstName, LName = LastName, Title = TitleofCourtest };
MyGridview.DataSource = EmployeeDS;
MyGridView.DataBind();
By doing this: var EmployeeDS = from eds in myList select new { ID = EmployeeID, FName = FirstName, LName = LastName, Title = TitleofCourtest }; it makes it possible to just use <%# Eval('ID/FName/LName/Title'%> in the GridView's boundfields instead of those long variable names you've made in your entity class.