How to read and write objects into SQL Server database? - c#

My first table is Clinics with columns:
ClinicId, ClinicName, ClinicShortName
My second table is Employees with columns:
EmployeeId, EmployeeName, ClinicId, OnJob
I also have a view v_employees defined as:
SELECT
Employees.EmployeeId, Employees.EmployeeName,
Clinics.ClinicShortName,
Employees.OnJob
FROM
Clinics
INNER JOIN
Employees ON Clinics.ClinicId = Employees.ClinicId
And my C# code is:
class Employee
{
public int EmployeeId { get; set; }
public string EmpolyeeName { get; set; }
public int ClinicId { get; set; }
public bool OnJob { get; set; }
}
class Clinic
{
public int ClinicId { get; set; }
public string ClinicName { get; set; }
public string ClinicShortName { get; set; }
}
List<Employee> employeeList = new List<Employee>();
private void InitEmployees()
{
SqlConnection con = new SqlConnection(......);
SqlCommand cmd = new SqlCommand("select * from v_employees", con );
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee employee = new Employee()
{
EmployeeId = Convert.ToInt32(dr["EmployeeId"]),
EmpolyeeName = dr["EmployeeName"].ToString(),
// how to use ClinicShortName field in this position?
// Because I want the data to be displayed into DataGridView control.
OnJob = Convert.ToBoolean(dr["OnJob"])
};
employeeList.Add(employee);
}
dr.Close();
con.Close();
dataGridView1.DataSource = employeeList;
}
How could I import objects into SQL Server?
Should I use the List<T> method?

You have to add a field of ClinicShortName into employee class but why not use sqladapter? it generates columns according to the data returned
SqlConnection con = new SqlConnection(......);
SqlCommand cmd = new SqlCommand("select * from v_employees", con );
con.Open();
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(table);
dr.Close();
con.Close();
dataGridView1.DataSource = table;

Related

How to show all data from c#

I'm kind a new on c#. I have a problem with to store the className to list since i need to display all the class that teacher taught. On result, it turns out just the last class teacher taught. I did use join table between teacher and classes.
Model
public class Teacher
{
public int teacherId { get; set; }
public string teacherfName { get; set; }
public string teacherlName { get; set; }
public string className { get; set; }
public int classId { get; set; }
}
Controller
public Teacher FindTeacher(int id)
{
Teacher newTeacher = new Teacher();
MySqlConnection Conn = school.AccessDatabase();
Conn.Open();
MySqlCommand cmd = Conn.CreateCommand();
//SQL QUERY
cmd.CommandText = "Select * from teachers left join classes on teachers.teacherid=classes.teacherid where teachers.teacherid = " + id;
//Gather Result Set of Query into a variable
MySqlDataReader ResultSet = cmd.ExecuteReader();
while (ResultSet.Read())
{
int teacherId = (int)ResultSet["teacherId"];
string teacherfName=ResultSet["teacherfname"].ToString();
string teacherlName=ResultSet["teacherlname"].ToString();
newTeacher.teacherId = teacherId;
newTeacher.teacherFName = teacherFName;
newTeacher.teacherLName = teacherLName;
newTeacher.className = className;
newTeacher.classId = (int)ResultSet["classid"];
}
return newTeacher;
}
Your only returning one teacher if you want all the teachers your code should be:
public IEnumerable<Teacher> FindTeacher(int id)
{
//Lise here
List<Teacher> teachers = new List<Teacher>();
//note the using
using MySqlConnection Conn = school.AccessDatabase();
Conn.Open();
//note the using
using MySqlCommand cmd = Conn.CreateCommand();
//SQL QUERY
cmd.CommandText = "Select * from teachers left join classes on teachers.teacherid=classes.teacherid where teachers.teacherid = " + id;
//Gather Result Set of Query into a variable
MySqlDataReader ResultSet = cmd.ExecuteReader();
while (ResultSet.Read())
{
//new teacher in the loop
Teacher newTeacher = new Teacher();
int teacherId = (int)ResultSet["teacherId"];
string teacherfName=ResultSet["teacherfname"].ToString();
string teacherlName=ResultSet["teacherlname"].ToString();
newTeacher.teacherId = teacherId;
newTeacher.teacherFName = teacherFName;
newTeacher.teacherLName = teacherLName;
newTeacher.className = className;
newTeacher.classId = (int)ResultSet["classid"];
//add to the collection
teachers.Add(newTeacher);
}
//return the collection
return teachers;
}
If also added using statements. These are important to prevent memory leaks
Modify Teacher Class to be able to carry List of TeacherClass that correspond to one teacher:
Define New Class TeacherClass to Carry a TeacherClass Data
public class TeacherClass
{
public string Name { get; set; }
public int Id { get; set; }
}
Modify Teacher Class To have a List Of TeacherClass
public class Teacher
{
public int teacherId { get; set; }
public string teacherfName { get; set; }
public string teacherlName { get; set; }
public List<TeacherClass> classes { get; set; } = new List<TeacherClass>();
}
Then get your function to set this TeacherClass List in a loop:
public Teacher FindTeacher(int id)
{
Teacher newTeacher = new Teacher();
//note the using
using MySqlConnection Conn = school.AccessDatabase();
Conn.Open();
//note the using
using MySqlCommand cmd = Conn.CreateCommand();
//SQL QUERY
cmd.CommandText = "Select * from teachers left join classes on teachers.teacherid=classes.teacherid where teachers.teacherid = " + id;
//Gather Result Set of Query into a variable
MySqlDataReader ResultSet = cmd.ExecuteReader();
// Check if any rows retrieved
if (reader.HasRows)
{
// Iterate Over Rows
while (ResultSet.Read())
{
// Set Teacher Data Just Once
if(newTeacher.teacherId == 0){
newTeacher.teacherId = (int)ResultSet["teacherId"];;
newTeacher.teacherFName = ResultSet["teacherfname"].ToString();
newTeacher.teacherLName = ResultSet["teacherlname"].ToString();
}
// Add new TeacherClass data for this teacher
newTeacher.classes.Add(
new TeacherClass(){
Name = className, // className Check this variable as it is not declared
Id = (int)ResultSet["classid"]
});
}
}
return newTeacher;
}

How to pass data, select for an array

How to save the select data below into an array.
SqlConnection conConexao1 = clsdb.AbreBanco();
SqlCommand cmd1 = new SqlCommand("select id, tamplete1, tamplete2 from usuarios ", conConexao1);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.HasRows == true)
{
if (dr1.Read())
{
id = int.Parse(dr1[0].ToString());
templete1 = (dr1[1].ToString());
templete2 = (dr1[2].ToString());
}
}
I have already tried using foreach, but always passes the last table data.
As a collection, List provide better flexibility than array.
The collection should be created outside the loop and the element should be added inside the loop.
List<Usuarios> list = new List<Usuarios>();
using (SqlConnection conConexao1 = clsdb.AbreBanco())
using (SqlCommand cmd1 = new SqlCommand(
"select id, tamplete1, tamplete2 from usuarios ", conConexao1))
using (SqlDataReader dr1 = cmd1.ExecuteReader())
{
while (dr1.Read())
{
list.Add(new Usuarios
{
Id = dr1.GetInt32(0),
Templete1 = dr1[1].ToString(),
Templete2 = dr1[2].ToString()
});
}
}
The class to imitate your data structure
public class Usuarios
{
public int Id { get; set; }
public string Templete1 { get; set; }
public string Templete2 { get; set; }
}
if for some reason, you have to use an array as collection
Usuarios[] array = list.ToArray();

Not all paths return a value error c#

I am getting error Not all paths return a value. Its a syntax error how to correct it. here is my code. I am writing this code in class.
public class Employees
{
public String emp_id { get; set; }
public String emp_name { get; set; }
public String u_name { get; set; }
public String pass { get; set; }
public String mail { get; set; }
public String address { get; set; }
public String city { get; set; }
public String dob { get; set; }
public String cnic { get; set; }
public String designation { get; set; }
public String ph_no { get; set; }
}
public class #object
{
public static List<Employees> GetAllEmployees()
{
List<Employee> listemp = new List<Employee>();
string cs = ConfigurationManager.ConnectionStrings[#"Data Source = localhost; Initial Catalog=fms; User=root; Pooling=false; Integrated Security = false"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
MySqlCommand cmd = new MySqlCommand("Select * from emp", con);
con.Open();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employees em = new Employees();
em.emp_id = dr[0].ToString();
em.emp_name = dr[1].ToString();
em.u_name = dr[2].ToString();
em.pass = dr[3].ToString();
em.mail = dr[4].ToString();
em.address = dr[5].ToString();
em.city = dr[6].ToString();
em.dob = dr[7].ToString();
em.cnic = dr[8].ToString();
em.designation = dr[9].ToString();
em.ph_no = dr[10].ToString();
}
listemp.Add(em);
}
}
}
I attached a pic where I am getting this error.
You should return the List listemp . Also consider moving listemp.Add(em) inside while loop, otherwise you wont get a list
public static List<Employees> GetAllEmployees()
{
List<Employee> listemp = new List<Employee>();
string cs = ConfigurationManager.ConnectionStrings[#"Data Source = localhost; Initial Catalog=fms; User=root; Pooling=false; Integrated Security = false"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
MySqlCommand cmd = new MySqlCommand("Select * from emp", con);
con.Open();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employees em = new Employees();
em.emp_id = dr[0].ToString();
em.emp_name = dr[1].ToString();
em.u_name = dr[2].ToString();
em.pass = dr[3].ToString();
em.mail = dr[4].ToString();
em.address = dr[5].ToString();
em.city = dr[6].ToString();
em.dob = dr[7].ToString();
em.cnic = dr[8].ToString();
em.designation = dr[9].ToString();
em.ph_no = dr[10].ToString();
listemp.Add(em);
}
}
return listemp;
}
You have two problems: GetAllEmployees() should return List<Employees> and you add em to the list outside the while scope
public static List<Employees> GetAllEmployees()
{
List<Employee> listemp = new List<Employee>();
string cs = ConfigurationManager.ConnectionStrings[#"Data Source = localhost; Initial Catalog=fms; User=root; Pooling=false; Integrated Security = false"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
MySqlCommand cmd = new MySqlCommand("Select * from emp", con);
con.Open();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employees em = new Employees();
em.emp_id = dr[0].ToString();
em.emp_name = dr[1].ToString();
em.u_name = dr[2].ToString();
em.pass = dr[3].ToString();
em.mail = dr[4].ToString();
em.address = dr[5].ToString();
em.city = dr[6].ToString();
em.dob = dr[7].ToString();
em.cnic = dr[8].ToString();
em.designation = dr[9].ToString();
em.ph_no = dr[10].ToString();
listemp.Add(em);
}
}
return listemp;
}
You need to return the listemp at the end of the method GetAllEmployee()
return listemp
One more thing I noticed, the listemp.Add(em) should be inside the while loop. Since your select statement will yield more than one employee. You need to add the employee object each time to the list.

Display Data to spesific column Grid control devexpress using oracle data reader

I have tried display data from spesific column ListView in C# and it was successfull. But I couldn't display it into spesific column in GridControl DevExpress.
This my code in ListView:
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT * FROM PERMOHONANDETAIL WHERE PERMOHONANFK = '" + buka.txtID.Text + "'";
cmd.Connection = koneksi_manual.con;
dr = cmd.ExecuteReader();
while (dr.Read())
{
ListViewItem list = new ListViewItem(dr["PEKERJAAN"].ToString());
list.SubItems.Add(dr["KODEPEKERJAAN"].ToString());
list.SubItems.Add(dr["PEKERJAAN"].ToString());
list.SubItems.Add(dr["JOBFORM"].ToString());
list.SubItems.Add(dr["QTYORDER"].ToString());
list.SubItems.Add(dr["TARGETPERHARI"].ToString());
list.SubItems.Add(Convert.ToDateTime(dr["TANGGALSTART"]).ToString("dd/MM/yyyy"));
list.SubItems.Add(Convert.ToDateTime(dr["TANGGALEND"]).ToString("dd/MM/yyyy"));
list.SubItems.Add(dr["DURASIHARI"].ToString());
list.SubItems.Add(dr["NOTES"].ToString());
buka.listView1.Items.Add(list);
}
dr.Close();
buka.Focus();
buka.ShowDialog();
How can I do it into spesific column GridControl in DevExpress?
How can I solve this??
You can create a class for your rows and use the List<YourClass> as DataSource for your GridControl.
For example, you can create this class:
public class GridControlItem
{
public string KODEPEKERJAAN { get; set; }
public string PEKERJAAN { get; set; }
public string JOBFORM { get; set; }
public string QTYORDER { get; set; }
public string TARGETPERHARI { get; set; }
public string TANGGALSTART { get; set; }
public string TANGGALEND { get; set; }
public string DURASIHARI { get; set; }
public string NOTES { get; set; }
}
And use it in your GridControl as follows:
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT * FROM PERMOHONANDETAIL WHERE PERMOHONANFK = '" + buka.txtID.Text + "'";
cmd.Connection = koneksi_manual.con;
dr = cmd.ExecuteReader();
var list = new List<GridControlItem>();
while (dr.Read())
{
var item = new GridControlItem();
item.KODEPEKERJAAN = dr["KODEPEKERJAAN"].ToString();
item.PEKERJAAN = dr["PEKERJAAN"].ToString();
item.JOBFORM = dr["JOBFORM"].ToString();
item.QTYORDER = dr["QTYORDER"].ToString();
item.TARGETPERHARI = dr["TARGETPERHARI"].ToString();
item.TANGGALSTART = Convert.ToDateTime(dr["TANGGALSTART"]).ToString("dd/MM/yyyy");
item.TANGGALEND = Convert.ToDateTime(dr["TANGGALEND"]).ToString("dd/MM/yyyy");
item.DURASIHARI = dr["DURASIHARI"].ToString();
item.NOTES = dr["NOTES"].ToString();
list.Add(item)
}
dr.Close();
gridControl1.DataSource = list;

Send a class object returned to an Ajax call

My goal is to send a class object returned to an Ajax call in Default.aspx.
The Default.aspx sends a json string to [WebMethod]: {ID:someid}.
The connectionstring jsonobject defines jsondata.mdf.
jsondata.mdf contains columns: idd, datetime, col1, col2 and col3 with many rows of data.
Having a problem with the return line:
return json2.ToArray();
Default.aspx.cs
[System.Web.Services.WebMethod]
public static string GetJSONdata(string ID)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
string cmdStr = "SELECT ([idd],[datetime],[col1],[col2],[col3]) FROM [jsondata] WHERE [idd]=#idd;";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#idd", ID);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
dt = ds.Tables[0];
}
}
}
}
catch (Exception ex)
{
}
List<dataclass> classdata = new List<dataclass>();
foreach (DataRow dr in dt.Rows)
{
dataclass dc = new dataclass();
dc.idd = Convert.ToString(dr["idd"]);
dc.datetime = Convert.ToString(dr["datetime"]);
dc.col1 = Convert.ToString(dr["col1"]);
dc.col2 = Convert.ToString(dr["col2"]);
dc.col3 = Convert.ToString(dr["col3"]);
classdata.Add(dc);
}
return classdata.ToArray();
}
class1.cs
public class dataclass
{
public string idd { get; set; }
public string datetime { get; set; }
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}

Categories