Passing a null value - c#

Any suggestions would be awesome!
I keep getting a null value for my ClassID. When I add breakpoints, I can see the value ClassID being passed correctly, but when my program goes back to get a list I created, the ClassID returns null after stepping into that particular breakpoint. I believe my issue is in my controller, but I cant seem to find the issue.
Here is my DB file. The first dataset retrieves my ClassID from a stored procedure and my list below that returns the students in a particular ClassID
public DataSet GetClass(string ClassID)
{
ClassModel classes = new ClassModel();
SqlCommand com = new SqlCommand("sp_ABEAttendanceEnrollment", ABEAttendanceDB);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ClassID", ClassID);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds1 = new DataSet();
da.Fill(ds1);
return ds1;
}
public IEnumerable<ClassModel> ClassModel
{
get
{
string connectionString = ConfigurationManager.ConnectionStrings["ABEAttendanceDB"].ConnectionString;
List<ClassModel> students = new List<ClassModel>();
using (SqlConnection con = new SqlConnection(connectionString))
{
ClassModel classes = new ClassModel();
SqlCommand cmd = new SqlCommand("sp_ABEAttendanceEnrollment", ABEAttendanceDB);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ClassID", classes.ClassID);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
ABEAttendanceDB.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ClassModel student = new ClassModel();
student.ClassID = rdr["ClassID"].ToString();
student.SID = rdr["SID"].ToString();
student.FullName = rdr["FullName"].ToString();
students.Add(student);
}
ABEAttendanceDB.Close();
return students;
}
}
}
Here is my controller
public class ClassController : Controller
{
DAL.DB dblayer = new DAL.DB();
public ActionResult Class(ClassModel ClassModel)
{
DataSet ds1 = dblayer.GetClass(ClassModel.ClassID);
ViewBag.general = ds1.Tables;
ViewBag.Message = TempData["Message"];
DB classes = new DB();
List<ClassModel> students = dblayer.ClassModel.ToList();
return View();
}
}

Your DAL code is bit strange. Surely the GetClass method should return the IEnumerable<ClassModel>? Otherwise it just looks like you end up executing sp_ABEAttendanceEnrollment twice for no real reason. Putting a SQL query in a getter is rather unusual, to say the least. It's also not clear why you would need two copies of your data (one as a collection of DataTable via ViewBag.general and one as a List<ClassModel> via the students variable.
I'm not sure you need the ClassModel property on your DAL class at all. Just make the GetClass method read the data into an IEnumerable<Class> directly, and return it to the controller. Then you can return the list of students to the controller as the model for your view, something like this:
DAL:
public List<ClassModel> GetClass(string ClassID)
{
List<ClassModel> students = new List<ClassModel>();
SqlCommand cmd = new SqlCommand("sp_ABEAttendanceEnrollment", ABEAttendanceDB);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ClassID", ClassID);
ABEAttendanceDB.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ClassModel student = new ClassModel();
student.ClassID = rdr["ClassID"].ToString();
student.SID = rdr["SID"].ToString();
student.FullName = rdr["FullName"].ToString();
students.Add(student);
}
ABEAttendanceDB.Close();
return students;
}
Controller:
public class ClassController : Controller
{
DAL.DB dblayer = new DAL.DB();
public ActionResult Class(ClassModel ClassModel)
{
ViewBag.Message = TempData["Message"];
List<ClassModel> students = dblayer.getClass(ClassModel.ClassID);
return View(students);
}
}
The view would then start with:
#model List<ClassModel>

Related

How to convert table values of sql red by using Ado.net to json and display in jqgrid

I have written a piece of code using ado.net the main intention of the code retrieve the data from sql table and display results in html table. I was successful in doing this task. My question is how can I convert red values to jsondata and pass to view to display in JQGrid? I have googled regarding this but I am getting only Entity framework related stuff. Please help
Thanks in advance.
public ActionResult Details1()
{
string ConnectionString = ConfigurationManager.ConnectionStrings["EmployeeContext"].ConnectionString;
SqlDataReader rdr = null;
List<Employee> l = new List<Employee>();
SqlDataAdapter da;
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection("data source=.; database=Srivatsava; integrated security=SSPI"))
{
connection.Open();
da = new SqlDataAdapter("select * from Employee", connection);
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
l.Add(new Employee() { ID = int.Parse(dr[0].ToString()), FirstName = dr[1].ToString(), LastName = dr[2].ToString(), Salary = int.Parse(dr[3].ToString()),Gender=dr[4].ToString() });
}
//Create an instance of SqlCommand class, specifying the T-SQL command that
//we want to execute, and the connection object.
//SqlCommand cmd = new SqlCommand("Select Id,FirstName,LastName,Salary,Gender from tblEm", connection);
//rdr = cmd.ExecuteReader();
/*while (rdr.Read())
{
// get the results of each column
int id = (int)rdr["ID"];
string contact = (string)rdr["FirstName"];
string company = (string)rdr["LastName"];
int city = (int)rdr["Salary"];
string gender = (string)rdr["Gender"];
// print out the results
Console.Write(contact);
Console.Write(city);
Console.Write(company);
Console.WriteLine(gender);
Console.WriteLine(id);
}*/
connection.Close();
}
return View(l);
}
To get json you should return Json() like following.
return Json(l, JsonRequestBehavior.AllowGet);
instead of
return View(l)
Update your Action return type with JsonRrsult like below
public JsonResult Details1()
{
and return
return Json(l, JsonRequestBehavior.AllowGet);
in your HTMLs update Jqgrid usage like below pointing url to your Controller/Action
$("#yourgrid").jqGrid({
datatype: 'json',
url: 'controller/action',
That should work.

Generic data access code to stored procedures to return Enumerable<t>?

Instead of repeating the same ADO.net code with a different Enumerable, I want to make it more generic and reusable.
I have the following ADO.Net code to return a collection of objects:
public static IEnumerable<TasCriteria> GetTasCriterias()
{
using (var conn = new SqlConnection(_connectionString))
{
var com = new SqlCommand();
com.Connection = conn;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "IVOOARINVENTORY_GET_TASCRITERIA";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
var types = (from c in dataset.Tables[0].AsEnumerable()
select new TasCriteria()
{
TasCriteriaId = Convert.ToInt32(c["TasCriteriaId"]),
TasCriteriaDesc= c["CriteriaDesc"].ToString()
}).ToList<TasCriteria>();
return types;
}
}
Model:
public class TasCriteria
{
public int TasCriteriaId { get; set; }
public string TasCriteriaDesc { get; set; }
}
If your stored procedure returns column names matching exactly properties in your class, you can use reflection like this code. I'll leave an exercise to add parameters to the stored procedure for someone else. (by the way, this is untested code, I wrote it off the top of my head)
public static IEnumerable<T> GetStoredProcedure<T>(string procedure) where T : new()
{
var data = new List<T>();
using (var conn = new SqlConnection(_connectionString))
{
var com = new SqlCommand();
com.Connection = conn;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = procedure;
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
//Get each row in the datatable
foreach (DataRow row in dataset.Tables[0].Rows)
{
//Create a new instance of the specified class
var newT = new T();
//Iterate each column
foreach (DataColumn col in dataset.Tables[0].Columns)
{
//Get the property to set
var property = newT.GetType().GetProperty(col.ColumnName);
//Set the value
property.SetValue(newT, row[col.ColumnName]);
}
//Add it to the list
data.Add(newT);
}
return data;
}
}
So lets say you have a class like this:
public class TasCriteria
{
public int TasCriteriaId { get; set; }
public string TasCriteriaDesc { get; set; }
}
You would call the function like this:
IEnumerable<TasCriteria> criteria = GetStoredProcedure<TasCriteria>("IVOOARINVENTORY_GET_TASCRITERIA");
An option would be to extract your specific code outside of your main method.
In example:
public static IEnumerable<T> GetCriterias(
string storedProcedureName,
Func<IEnumerable<T>> enumerateMethod)
{
using (var conn = new SqlConnection(_connectionString))
{
var com = new SqlCommand();
com.Connection = conn;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = storedProcedureName;
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
return enumerateMethod(dataset.Tables[0]);
}
}
If your stored procedure requires parameters, you can overload your function as:
public static IEnumerable<T> GetCriterias(
string storedProcedureName,
Func<IEnumerable<T>> enumerateMethod,
SqlParameter[] parameters)
Using this code, you can define methods that matches de Func<> signature.
public static IEnumerable<TasCriteria> EnumerateTasCriteria(DataTable table)
{
return
(from c in table.AsEnumerable()
select new TasCriteria()
{
TasCriteriaId = Convert.ToInt32(c["TasCriteriaId"]),
TasCriteriaDesc= c["CriteriaDesc"].ToString()
}).ToList<TasCriteria>();
}
public static IEnumerable<DetailCriteria> EnumerateDetailCriteriaCriteria(
DataTable table)
{
return
(from c in table.AsEnumerable()
select new DetailCriteria()
{
DetailCriteriaId = Convert.ToInt32(c["DetailCriteriaId"]),
DetailCriteriaDesc = c["CriteriaDesc"].ToString()
}).ToList<TasCriteria>();
}
Then, you can call your code as:
IEnumerable<TasCriteria> task =
GetCriterias<TasCriteria>("IVOOARINVENTORY_GET_TASCRITERIA", EnumerateTasCriteria);
IEnumerable<DetailCriteria> details =
GetCriterias<DetailCriteria>("IVOOARINVENTORY_GET_DETAILSCRITERIA", EnumerateDetailCriteriaCriteria);

how to convert datatable to list<string> and then compare it with a Textbox value?

I have a DataTable -> "CheckProduct(String id)" where String ID is invoice id which is used fetch product ids of that invoice
Now i want to compare it with a Textbox value.
I have tried a code for it.
My Datalogic :-
public DataTable CheckProduct(String id)
{
DataTable dt = new DataTable();
SqlConnection sqlconnection;
sqlconnection = new SqlConnection(#" Database Connection String");
sqlconnection.Open();
SqlCommand cmd = new SqlCommand("checkproduct", sqlconnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#inv_id", SqlDbType.VarChar).Value = int.Parse(id);
DataSet dtset = new DataSet();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dtset);
dt = dtset.Tables[0];
return dt;
}
My Business logic :-
public List<String> CheckProduct(String id)
{
SPDatalogic sp = new SPDatalogic(); //datalogic class
DataTable dt = new DataTable() ;
dt = sp.CheckProduct(id);
List<String> list = new List<String>();
SPBusinesslogic ab = new SPBusinesslogic(); //businesslogic class
String pro;
pro =ab.CheckProduct(id).ToString();
list.Add(pro);
return list;
}
My Presentation Layer:-
string id = invoice_no_textbox.Text;
SPBusinesslogic ab = new SPBusinesslogic(); //businesslogic class
List<String> id_list = new List<String>();
id_list = ab.CheckProduct(id); //passing invoice_no as string id
if (id_list.Any(x => x.Equals(invoice_no_textbox.Text)))
{
MessageBox.Show("the product already exist");
}
Supposing that the field name for your invoice id is called "invoice_id" I would rewrite the code of CheckProduct to be
public List<String> CheckProduct(String id)
{
SPDatalogic sp = new SPDatalogic(); //datalogic class
DataTable dt = sp.CheckProduct(id);
List<String> list = new List<String>();
foreach (DataRow dr in dt.Rows)
{
list.Add(dr["invoice_id"].ToString());
}
return list;
}
In your code, you call recursively the CheckProduct method passing again the ID of the invoice and doesn't seems to be a way out of that loop. Instead the list of products for the invoice are already known from the previous call to the SPDatalogic class. So you just need to add them to your list
Also in the DataLogic class there is a possible error in the declaration of the parameter. If #inv_id is of type integer, then don't declare the parameter as VarChar
cmd.Parameters.Add("#inv_id", SqlDbType.Int).Value = int.Parse(id);
And as a final note, I don't understand why you want to work with a List<string> when your IDs are clearly numbers. This causes continue conversions of type from string to int and viceversa. You shoud retrive a List<int> and convert just the input of your textbox.

Passing value in IEnumerable method

net mvc c#. I have created model for view. I can receive all rows from the table but when I try to pass value in method which is return list is not working
Here is my code
Controller class
public ActionResult Index()
{
TechnicianDBO db = new TechnicianDBO();
List<Technician> technicians = db.technicians.ToList();
return View(technicians);
}
[HttpPost]
public ActionResult Index(int Postcode)
{
TechnicianDBO db = new TechnicianDBO();
List<Technician> technicians = db.Jobtechnicians(Postcode).ToList();
return View(technicians);
}
Db class
public IEnumerable<Technician> Jobtechnicians(int postcode)
{
string connectionString = ConfigurationManager.ConnectionStrings["testConnect"].ConnectionString;
List<Technician> Jobtechnicians = new List<Technician>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spGetTechnicianByPostcode", con);
con.Open();
SqlParameter paramId = new SqlParameter();
paramId.ParameterName = "#postcode";
paramId.Value = postcode;
cmd.Parameters.Add(paramId);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Technician technician = new Technician();
technician.Id = Convert.ToInt32(dr["techId"]);
// technician.Username = dr["techUsername"].ToString();
technician.Firstname = dr["techFirstname"].ToString();
technician.Lastname = dr["techLastname"].ToString();
technician.LandlineNo = dr["landlineNo"].ToString();
technician.MobileNo = dr["mobileNo"].ToString();
technician.Address1 = dr["address1"].ToString();
technician.Address2 = dr["address2"].ToString();
technician.Postcode = Convert.ToInt32(dr["postcode"]);
technician.Email = dr["email"].ToString();
technician.Fax = dr["fax"].ToString();
technician.Profession = Convert.ToInt32(dr["ProfessionId"]);
Jobtechnicians.Add(technician);
}
return Jobtechnicians;
}
}
you need to give CommandType
SqlCommand cmd = new SqlCommand("spGetTechnicianByPostcode", con);
cmd.CommandType = CommandType.StoredProcedure;
and also when you call .ToString() you better check whether that column value null or not if that column allow null in your table

C#: help return dataset and assign values to controls

I'm not really used to C# sharp but have used VB.NET before.
I'm needing to set the value of text fields, dropdowns etc from data from a query. To enter the data I have been using a class Computer with the method saveComputer() that takes values from user controls. Now I want an edit page that uses the id from url & uses getComputer(id) from Computer class and returns the values to be set to the user controls. I'm unsure about using this method to set the control values.
Edit.aspx.cs
protected void btnSave_Click(object sender, EventArgs e)
{
int id = 3; //will be replaced to GET value
Computer comp = new Computer();
//comp.updateComputer(ref id);
}
My Computer class
public getComputer(ref int id)
{
DataSet data = new DataSet();
using (SqlConnection conn = new SqlConnection(
"Server=JURA;Database=ReadyForSeven;User id=;Password="))
{
String sql = "SELECT * FROM computers WHERE id=#id";
//replace contatenation of variable with parameter name
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql.ToString();
cmd.CommandType = CommandType.Text;
//Define SqlParameter object and assign value to the parameter
cmd.Parameters.Add("#id", SqlDbType.Int);
cmd.Parameters["#id"].Value = id;
try
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(data);
// return data here
}
}
catch (SqlException ex)
{
//send user to error page and log message
}
}
}
So what I'm wanting to achieve is using the getcomputer method of Computer to set the values of the controls on Edit.aspx
Can anyone help me out?
You'll need to modify your getComputer method to return a DataSet like:
public DataSet getComputer(int id) {
Once that's done we can call it and populate the form controls on the page load with something like:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
int id = 3; // get from querystring
DataSet ds = getComputer(id);
DataRow dr = ds.Tables[0].Rows[0]; // get the first row returned
// populate form controls
txtFirstName.Text = dr["FirstName"].ToString();
ddlState.SelectedValue = dr["State"].ToString();
}
}
Below is an updated version of getComputer that will always return a value and is a little tighter:
public DataSet getComputer(int id) // you don't need to pass int by ref unless you're planning on changing it inside this method
{
DataSet data = new DataSet();
using (SqlConnection conn = new SqlConnection("Server=JURA;Database=ReadyForSeven;User id=;Password=")) {
using (SqlCommand cmd = new SqlCommand("SELECT * FROM computers WHERE id = #id", conn)) {
cmd.Parameters.AddWithValue("id", id);
using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
da.Fill(data);
return data;
}
}
}
}
I had to remove the try/catch blog to ensure the method always returned a value. If you absolutely need the try/catch block you'll need to return an empty DataSet at the end of the method to get to compile correctly.

Categories

Resources