public static IEnumerable<T> ExecuteDataReader<T>(string sql, Func<TdDataReader, T> action)
{
using (var connection = new TdConnection(TDConnstring))
{
connection.Open();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
yield return action.Invoke(dr);
}
}
}
}
*how to use async task> rewirte *
public static async Task<IEnumerable<T>> ExecuteDataReaderAsync<T>(string sql, Func<TdDataReader, T> action)
{
using (var connection = new TdConnection(TDConnstring))
{
await connection.OpenAsync();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
using (var dr = await cmd.ExecuteReaderAsync())
{
while (await dr.ReadAsync())
{
yield return action.Invoke(dr);
}
}
}
}
}
* error
Severity Code Description Project File Line Suppression State
Error CS1624 The body of 'TeraDataHelper.ExecuteDataReaderAsync(string, Func)' cannot be an iterator block because 'Task>' is not an iterator interface type \TeraDataHelper.cs 141 Active
*
got it
public static async Task<IEnumerable<T>> ExecuteDataReaderAsync<T>(string sql, Func<TdDataReader, T> action)
{
using (var connection = new TdConnection(TDConnstring))
{
await connection.OpenAsync();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
using (var dr = await cmd.ExecuteReaderAsync())
{
return dr.Select(r => action(r)).ToList();
}
}
}
}
public static class Extensions
{
public static IEnumerable<T> Select<T>(
this TdDataReader reader, Func<TdDataReader, T> action)
{
while (reader.Read())
{
yield return action(reader);
}
}
}
I have a static class that needs to pass a generic List of strings to a function using an integer as a index to the List in the class. The problem is the static class doesn't have a List collect and I don't have a proper index to access the class in the function it is passed to. The class, the calling code, and the receiving function are below.
My Class:
public class QueryContainer
{
public static QueryContainer Instance = new QueryContainer();
private int _id;
private string _query = "";
private int _searchID;
public QueryContainer() { }
public string Query
{
get
{
if (Instance != null)
return Instance._query;
else
return "";
}
set { _query = value; _id =+ 1; }
}
public int ID { get { return _id; } }
public int SearchID
{
set { _searchID = value; }
get { return _searchID; }
}
}
The calling code:
public int GetAccountSortByAccountCode(int account)
{
int Id = 0;
QueryContainer.Instance.Query = "SELECT ac_sort_order FROM lkup_account_codes where ac_code = " + account.ToString();
return Convert.ToInt32(ExecuteScaler(Id));
}
The function that the static class is passed to:
public int GetAccountSortByAccountCode(int account)
{
int Id = 0;
QueryContainer.Instance.Query = "SELECT ac_sort_order FROM lkup_account_codes where ac_code = " + account.ToString();
return Convert.ToInt32(ExecuteScaler(Id));
}
The Function
protected Object ExecuteScaler(int ID)
{
object returnValue = null;
if (!_iserror)
{
if (_trace)
{ DoTrace("TAMIS.Data.Loader.ExecuteScalar", QueryContainer.Instance.Query); }
if (_connection == null || _connection.State == ConnectionState.Closed)
{
OpenConnection();
}
DbCommand command = _provider.CreateCommand();
command.Connection = _connection;
{
command.CommandText = QueryContainer.Instance.Query;
command.CommandType = CommandType.Text;
if (_useTransaction) { command.Transaction = _transaction; }
try
{
returnValue = command.ExecuteScalar();
}
catch (Exception ex)
{
if (ex is EntryPointNotFoundException)
throw ex;
//if (_useTransaction == true)
//_transaction.Rollback();
RollBack();
LogBLL bll = new LogBLL();
bll.WriteErrorLog(ex);
_iserror = true;
}
finally
{
if ((!KeepAlive && _connection.State == ConnectionState.Open) || _iserror == true)
{
CloseConnection();
}
}
}
}
else
{
returnValue = -1;
}
return returnValue;
}
You are using QueryContainer as a Singleton.
In ASP.Net, you receives multiple requests from different users. It is not a good way to construct dynamic query.
Basically, what you are doing is all requests will use same QueryContainer instance. I don't think it is what you want.
The bottom line is do not use static in your scenario.
I am developing an application in MVC 5 and perform CRUD operations on it.
I have successfully added Northwind database as an Entity Data Model and taking Customer in the Model. Now with the help of Scaffolding I generated the CustomersController.
When I create a new record in a Customer Table. There is no problem.
But when I click on that new record, Edit, Details and Delete are not working. After clicking any of these:
The following page occurs:
My Controller Code:
namespace MvcNorthwindSample.Controllers
{
public class CustomersController : Controller
{
private NORTHWNDEntities db = new NORTHWNDEntities();
// GET: Customers
public ActionResult Index()
{
return View(db.Customers.ToList());
}
// GET: Customers/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// GET: Customers/Create
public ActionResult Create()
{
return View();
}
// POST: Customers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
{
if (ModelState.IsValid)
{
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
// GET: Customers/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// POST: Customers/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
{
if (ModelState.IsValid)
{
db.Entry(customer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
// GET: Customers/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// POST: Customers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
Customer customer = db.Customers.Find(id);
db.Customers.Remove(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
My View Part:
My Create Code Result view while debugging:
EDIT: After you posted your controller:
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
Are you sure that you have a customer with an id of 1994? If not, your logic would return HttpNotFound().
In the screenshot you posted, I can read HTTP 404 error message and the requested URL was /Customer/Edit/1994.
So for that I assume you must be have the following controller/action:
public class CustomerController
{
public ActionResult Edit(int id)
{
return View();
}
}
Now the most common mistake most people make (including me) is properly passing id in the URL. You have id specified as an optional parameter in your route pattern:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
So if you don't want to use id you could pass something else as a key name in the the query component, e.g., /Customer/Edit?year=1994.
The error is a 404 Error.
It is looking in the Controller Customers for an Edit action.
Also pointed out in the comments the Id 1994 has a encoded space character following it. If the id is suppose to be strings, you can change the parameter to type string instead of int
public class CustomersController
{
public ActionResult Edit(int id)
{
return View();
}
}
I solved it. I changed the table at last. There is a problem on the table named Customers of the Northwind database. I download database backup file. The Customer ID column is adding a space as a default with the inserted value.
First create your models and Dbcontext.
public class TaskManagerContext : DbContext
{
public TaskManagerContext()
: base("TaskManagerDB")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Task> Tasks { get; set; }
}
Then allow migrations and update the database from the PM. Create a folder Repositories with a BaseRepo that the rest must inherit.
public class BaseRepository<T> where T:BaseModel, new()
{
protected TaskManagerContext context;
protected DbSet<T> dbSet;
public BaseRepository()
{
this.context = new TaskManagerContext();
this.dbSet = this.context.Set<T>();
}
public void Insert(T item)
{
this.dbSet.Add(item);
this.context.SaveChanges();
}
public void Update(T item)
{
this.context.Entry(item).State = EntityState.Modified;
this.context.SaveChanges();
}
public void Delete(int id)
{
this.dbSet.Remove(this.dbSet.Find(id));
this.context.SaveChanges();
}
public IEnumerable<T> GetAll()
{
return this.dbSet;
}
}
like this:
public class UsersRepository : BaseRepository<User>
{
public UsersRepository()
: base()
{
}
}
Then you create the controllers in which you use the methods from the repos.
public class UsersController : Controller
{
//
// GET: /Users/
public ActionResult List()
{
List<User> users = new List<User>();
users = new UsersRepository().GetAll().ToList();
return View(users);
}
public ActionResult Edit(int id)
{
User user = new UsersRepository().GetAll().FirstOrDefault(u => u.ID == id);
return View(user);
}
[HttpPost]
public ActionResult Edit(User user)
{
UsersRepository repo = new UsersRepository();
repo.Update(user);
return RedirectToAction("List");
}
public ActionResult Delete(int id)
{
UsersRepository repo = new UsersRepository();
repo.Delete(id);
return RedirectToAction("List");
}
public ActionResult Create()
{
User u = new User();
return View(u);
}
[HttpPost]
public ActionResult Create(User user)
{
UsersRepository repo = new UsersRepository();
repo.Insert(user);
return RedirectToAction("List");
}
}
The actions for the TaskContr are simillar exept the List in which you connect the 2 models by ID:
public ActionResult List(int? id)
{
TasksRepository repo = new TasksRepository();
List<Task> tasks = new List<Task>();
tasks = repo.GetAll().Where(t => t.UserID == id).ToList();
return View(tasks);
}
Don't forget to generate views(on the Get methods) and change the List view for the Users:
#Html.ActionLink("Details", "List", "Tasks", new { id=item.ID }, null) |
That way when clicking Details you can see the tasks for that user.
public ActionResult Index()
{
using (DevExam db = new DevExam())
{
var intern = from m in db.Interns
select m;
return View(intern.ToList());
}
/* using (DevExam db = new DevExam())
{
var interns = db.Interns
.Include(s => s.InternID)
.Select(s => new Intern
{
InternID = s.InternID,
lname = s.lname,
fname = s.fname
});
return View(interns);
}
*/
}
// GET: CRUD/Details/5
public ActionResult Details(int id)
{
using (DevExam db = new DevExam())
{
return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
}
}
// GET: CRUD/Create
public ActionResult Create()
{
return View();
}
// POST: CRUD/Create
[HttpPost]
public ActionResult Create(Intern intern)
{
try
{
// TODO: Add insert logic here
using (DevExam db = new DevExam())
{
db.Interns.Add(intern);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: CRUD/Edit/5
public ActionResult Edit(int id)
{
using (DevExam db = new DevExam())
{
return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
}
}
// POST: CRUD/Edit/5
[HttpPost]
public ActionResult Edit(int id,Intern intern)
{
try
{
// TODO: Add update logic here
using (DevExam db = new DevExam())
{
db.Entry(intern).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: CRUD/Delete/5
public ActionResult Delete(int id)
{
using (DevExam db = new DevExam())
{
return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
}
}
// POST: CRUD/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
using (DevExam db = new DevExam())
{
Intern intern = db.Interns.Where(x => x.InternID == id).FirstOrDefault();
db.Interns.Remove(intern);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
create table tblemployee(
EmpId int NOT NULL identity(1,1),
EmpName varchar(100),
PhoneNumber varchar(10),
Country int,
State int,
maritalstetus varchar(50),
isvoting varchar(50),
dob datetime,
doj datetime
primary key (EmpId)
)
create table tblCountry(
Id int NOT NULL identity(1,1),
Name varchar(100),
primary key (Id)
)
insert into tblCountry(Name) values ('India')
insert into tblCountry(Name) values ('US')
insert into tblCountry(Name) values ('UK')
create table tblstate(
Id int NOT NULL identity(1,1),
Name varchar(100),
countryId int,
primary key (Id)
)
insert into tblstate(Name ,countryId) values ('Delhi',1)
insert into tblstate(Name , countryId) values ('Bihar' ,1)
insert into tblstate(Name , countryId) values ('Up',1)
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace webTest.Models
{
public class Employee
{
public int id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string PhoneNumber { get; set; }
[Required]
public int Country { get; set; }
[Required]
public int State { get; set; }
[Required]
public bool MarritalStatus { get; set; }
public bool IsVoting { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime DOJ { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using webTest.Models;
namespace webTest.Controllers
{
public class EmpController : Controller
{
// GET: Emp
public static string constr = "Data Source=DIVYANSHU;Initial Catalog=EmployeeData;Integrated Security=True";
SqlConnection conn = new SqlConnection(constr);
public ActionResult ViewList()
{
List<Employee> employees = new List<Employee>();
try
{
conn.Open();
string sqlquery = "select * from tblEmployee";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee emp = new Employee()
{
id = Convert.ToInt32(dr["Empid"].ToString().Trim()),
Name = dr["EmpName"].ToString(),
PhoneNumber = dr["PhoneNumber"].ToString(),
Country = Convert.ToInt32(dr["Country"].ToString().Trim()),
State = Convert.ToInt32(dr["State"].ToString().Trim()),
MarritalStatus = Convert.ToBoolean(dr["maritalstetus"].ToString().Trim()),
IsVoting = Convert.ToBoolean(dr["isvoting"]),
DOB = Convert.ToDateTime(dr["dob"].ToString().Trim()),
DOJ = Convert.ToDateTime(dr["doj"].ToString().Trim()),
};
employees.Add(emp);
}
conn.Close();
}
catch (Exception ex)
{
}
return View(employees);
}
public ActionResult Create()
{
SqlDataAdapter _da = new SqlDataAdapter("Select * From tblCountry", constr);
DataTable _dt = new DataTable();
_da.Fill(_dt);
ViewBag.Country = ToSelectList(_dt, "Id", "Name");
_da.Dispose();
SqlDataAdapter _da1 = new SqlDataAdapter("Select * From tblState", constr);
DataTable _dt1 = new DataTable();
_da1.Fill(_dt1);
ViewBag.State = ToSelectList(_dt1, "Id", "Name");
_da1.Dispose();
Employee emp = new Employee();
return View(emp);
}
public SelectList ToSelectList(DataTable table, string valueField, string textField)
{
List<SelectListItem> list = new List<SelectListItem>();
foreach (DataRow row in table.Rows)
{
list.Add(new SelectListItem()
{
Text = row[textField].ToString(),
Value = row[valueField].ToString()
});
}
return new SelectList(list, "Value", "Text");
}
[HttpPost]
public ActionResult Create(Employee empmodel)
{
List<Employee> employees = new List<Employee>();
try
{
conn.Open();
string sqlquery = "insert into tblEmployee(EmpName,PhoneNumber,Country,State,maritalstetus,isvoting,dob,doj) values('" + empmodel.Name + "','" + empmodel.PhoneNumber + "'," + empmodel.Country + "," + empmodel.State + ",'" + empmodel.MarritalStatus + "','" + empmodel.IsVoting + "','" + empmodel.DOB + "','" + empmodel.DOJ + "')";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
conn.Close();
employees = listEmployee();
}
catch (Exception ex)
{
}
return View("ViewList", employees);
}
public ActionResult Edit(int id)
{
Employee emp = new Employee();
try
{
SqlDataAdapter _da = new SqlDataAdapter("Select * From tblCountry", constr);
DataTable _dt = new DataTable();
_da.Fill(_dt);
ViewBag.Country = ToSelectList(_dt, "Id", "Name");
_da.Dispose();
SqlDataAdapter _da1 = new SqlDataAdapter("Select * From tblState", constr);
DataTable _dt1 = new DataTable();
_da1.Fill(_dt1);
ViewBag.State = ToSelectList(_dt1, "Id", "Name");
_da1.Dispose();
conn.Open();
string sqlquery = "select * from tblemployee where empid=" + id + "";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
emp = new Employee()
{
id = Convert.ToInt32(dr["Empid"].ToString().Trim()),
Name = dr["EmpName"].ToString(),
PhoneNumber = dr["PhoneNumber"].ToString(),
Country = Convert.ToInt32(dr["Country"].ToString().Trim()),
State = Convert.ToInt32(dr["State"].ToString().Trim()),
MarritalStatus = Convert.ToBoolean(dr["maritalstetus"].ToString().Trim()),
IsVoting = Convert.ToBoolean(dr["isvoting"]),
DOB = Convert.ToDateTime(dr["dob"].ToString().Trim()),
DOJ = Convert.ToDateTime(dr["doj"].ToString().Trim()),
};
}
conn.Close();
}
catch (Exception ex)
{
}
return View(emp);
}
[HttpPost]
public ActionResult Edit(Employee empmodel)
{
try
{
conn.Open();
string sqlquery = "update tblEmployee set EmpName='" + empmodel.Name + "',PhoneNumber='" + empmodel.PhoneNumber + "',Country=" + empmodel.Country + ",State=" + empmodel.State + ",maritalstetus='" + empmodel.MarritalStatus + "',isvoting='" + empmodel.IsVoting + "',dob='" + empmodel.DOB + "',doj='" + empmodel.DOJ + "' where empid=" + empmodel.id + "";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
}
List<Employee> list = listEmployee();
return View("ViewList", list);
}
public ActionResult Delete(int id)
{
try
{
conn.Open();
string sqlquery = "Delete from tblEmployee where empid=" + id + "";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
}
List<Employee> list = listEmployee();
return View("ViewList", list);
}
public List<Employee> listEmployee()
{
List<Employee> employees = new List<Employee>();
conn.Open();
string sqlquery = "select * from tblEmployee";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee emp = new Employee()
{
id = Convert.ToInt32(dr["Empid"].ToString().Trim()),
Name = dr["EmpName"].ToString(),
PhoneNumber = dr["PhoneNumber"].ToString(),
Country = Convert.ToInt32(dr["Country"].ToString().Trim()),
State = Convert.ToInt32(dr["State"].ToString().Trim()),
MarritalStatus = Convert.ToBoolean(dr["maritalstetus"].ToString().Trim()),
IsVoting = Convert.ToBoolean(dr["isvoting"]),
DOB = Convert.ToDateTime(dr["dob"].ToString().Trim()),
DOJ = Convert.ToDateTime(dr["doj"].ToString().Trim()),
};
employees.Add(emp);
}
conn.Close();
return employees;
}
}
}
//in Edit view and in create view replace edit for to
#Html.DropDownListFor(model => model.Country, ViewBag.Country as SelectList, new { #class = "form-control" })
#Html.DropDownListFor(model => model.State, ViewBag.State as SelectList, new { #class = "form-control" })
error :: The parameterized query '(#CustomerName
varchar(50),#CustomerGender varchar(50),#Customer' expects the
parameter '#CustomerName', which was not supplied. Statement(s) could
not be prepared.
my code of .cs file is:
public class CustomerCls
{
private int custid;
public int CustomerId
{
set { custid = value; }
get { return custid; }
}
private string custname;
public string CustomerName
{
set { custname = value; }
get { return custname; }
}
private string gender;
public string CustomerGender
{
set { gender = value; }
get { return gender; }
}
private string city;
public string CustomerCity
{
set { city = value; }
get { return city; }
}
private string strcon;
public CustomerCls()
{
strcon = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;
}
public void InsertCustomer()
{
string sql = "Insert Into Customer(Cust_Name,Cust_Gender,Cust_City) " + " VALUES(#CustomerName,#CustomerGender,#CustomerCity)";
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#CustomerName", SqlDbType.VarChar,50).Value = CustomerName;
cmd.Parameters.Add("#CustomerGender", SqlDbType.VarChar,50).Value = CustomerGender;
cmd.Parameters.Add("#CustomerCity", SqlDbType.VarChar,50).Value = CustomerCity;
cmd.Prepare();
cmd.ExecuteNonQuery();
con.Close();
}
}
Make sure the CustomerCls object calling the InsertCustomer() method has the necessary properties set in code before the call to the method is made:
CustomerCls oCustomerCls = new CustomerCls();
oCustomerCls.CustomerName = "John Doe";
// etc...
oCustomerCls.InsertCustomer();
Try changing these lines to
cmd.Parameters.Add("#CustomerName", SqlDbType.VarChar,50).Value = CustomerName;
cmd.Parameters.Add("#CustomerGender", SqlDbType.VarChar,50).Value = CustomerGender;
cmd.Parameters.Add("#CustomerCity", SqlDbType.VarChar,50).Value = CustomerCity;
to
cmd.Parameters.Add("#CustomerName", SqlDbType.VarChar,50).Value = custname;
cmd.Parameters.Add("#CustomerGender", SqlDbType.VarChar,50).Value = gender;
cmd.Parameters.Add("#CustomerCity", SqlDbType.VarChar,50).Value = city;
I have a list which is defined as
List<SoftwareTitles> softwareTitlesList = new List<SoftwareTitles>();
and the SoftwareTitles is a class which is defines as follows:
public class SoftwareTitles
{
string softwareTitle;
string invoiceNumber;
public SoftwareTitles(string softwareTitle, string invoiceNumber)
{
this.softwareTitle = softwareTitle;
this.invoiceNumber = invoiceNumber;
}
string InvoiceNumber
{
get
{
return this.invoiceNumber;
}
}
string SoftwareTitle
{
get
{
return this.softwareTitle;
}
}
}
And now I'm adding the values from the sql server database to the list defines as follows:
public List<SoftwareTitles> SoftwareListRetrieve()
{
ConnectionToSql con1 = new ConnectionToSql();
string connectionString = con1.ConnectionStringMethod();
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd2 = new SqlCommand("SelectionOfSoftwareTitles", sqlConnection);
cmd2.CommandType = CommandType.StoredProcedure;
sqlConnection.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.HasRows)
{
while (dr2.Read())
{
String softwareTitle = (String)dr2[0];
String invoiceNumber = (String)dr2[1];
SoftwareTitles s1 = new SoftwareTitles(softwareTitle, invoiceNumber);
softwareTitlesList.Add(s1);
}
}
sqlConnection.Close();
dr2.Close();
return softwareTitlesList;
}
I want to find out the software title for every occurence of invoice number by looping through List<>. And I don't know how ? I have tried to loop through the List<> by the following code. I wanted to use something like contains i.e., softwareTitlesList[i].contains but seems like there is no such property or method
for(int i=0; i<softwareTitlesList.Count;i++)
{
softwareTitlesList[i]. [BUT IT IS NOT SUGGESTING ME ANYTHING]
}
I'm stuck with this from morning. I don't how to solve this dilemma.
Please help me
Thanks in anticipation
search for an invoice number
string invoiceNumber = "111111111";
using linq
IList<string> titles = softwareTitlesList
.Where(st => st.InvoiceNumber == invoiceNumber)
.Select(st => st.SoftwareTitle);
or
IList<string> titles = softwareTitlesList
.Where(st => st.InvoiceNumber.Contains(invoiceNumber))
.Select(st => st.SoftwareTitle);
w/o using linq, it's still pretty basic
IList<string> titles = new List<string>();
foreach(var softwareTitle in softwareTitlesList)
{
if (softwareTitle.InvoiceNumber.Contains(invoiceNumber))
titles.Add(softwareTitle.SoftwareTitle);
}
you could also rewrite your class like this:
public class SoftwareTitles
{
public SoftwareTitles(string softwareTitle, string invoiceNumber)
{
SoftwareTitle = softwareTitle;
InvoiceNumber = invoiceNumber;
}
public string InvoiceNumber { get; private set; }
public string SoftwareTitle { get; private set; }
}