how to call class object to perform search in textbox? - c#

I have text boxes to search for data, and 6 text boxes to display data if the data I am looking for is found. I'm trying to use an object class to make the code in the form look a little neat. the class is named ClsSearch. This is the class code snippet:
public string Name { get; set; }
public string txtCode { get; set; }
public string txtBarcode { get; set; }
public string txtUnit { get; set; }
public string txtQty { get; set; }
public string txtCost_price { get; set; }
public string txtSales_price { get; set; }
string mainconn = ConfigurationManager.ConnectionStrings["DbLearn"].ConnectionString;
public void X001_TextChanged()
{
MySqlConnection mysqlconn = new MySqlConnection(mainconn);
string sqlquery = "SELECT * FROM tb_stock_product WHERE Item_Name='" + Name + "'";
MySqlCommand sqlcmd = new MySqlCommand(sqlquery, mysqlconn);
mysqlconn.Open();
MySqlDataReader sdr;
sdr = sqlcmd.ExecuteReader();
if (sdr.Read())
{
txtCode = sdr.GetString("Code");
txtBarcode = sdr.GetString("Barcode");
txtUnit = sdr.GetString("Unit");
txtQty = sdr.GetDouble("Qty").ToString();
txtCost_price = sdr.GetInt32("Cost_price").ToString();
txtSales_price = sdr.GetInt32("Sales_price").ToString();
}
mysqlconn.Close();
then I tried calling the class in the form, exactly when the button was pressed, and this is the code:
private void X_001_Click(object sender, EventArgs e)
{
Connection_Frm_Ordering load = new Connection_Frm_Ordering();
load.X001_TextChanged();
load.Name = X_001.Text;
load.txtCode = X_002.Text;
load.txtBarcode = X_003.Text;
load.txtUnit = X_004.Text;
load.txtQty = X_005.Text;
load.txtCost_price = X_006.Text;
load.txtSales_price = X_007.Text;
}
but the code i made is not working.. can anyone help me where is the error ? sorry if this code might be messy, I'm still learning :)

Related

The number of values in the VALUES clause must match the number of columns specified in the INSERT statement

This is my models class (ObjektiMeQira.cs):
namespace crud2.Models
{
public class ObjektiMeQira
{
public int ObjektiMeQiraId { get; set; }
public string ObjektiMeQiraEmri { get; set; }
public string LlojiObjektit { get; set; }
public string Siperfaqe { get; set; }
public int NumriIDHomave { get; set; }
public string Kati { get; set; }
public int Cmimi { get; set; }
public string Vendndodhja { get; set; }
public string Qyteti { get; set; }
public string Shteti { get; set; }
}
}
And now this is my Controllers class (ObjektiMeQiraController.cs):
Note: I am only getting this error in Post method, otherwise Get method works fine.
[HttpPost]
public JsonResult Post(ObjektiMeQira omq)
{
string query = #"
insert into dbo.ObjektiMeQira(ObjektiMeQiraEmri,LlojiObjektit,Siperfaqe,
NumriIDHomave, Kati, Cmimi, Vendndodhja, Qyteti, Shteti)
values (#ObjektiMeQiraEmri), (#LLojiObjektit), (#Siperfaqe),
(#NumriIDHomave), (#Kati), (#Cmimi), (#Vendndodhja), (#Qyteti), (#Shteti)
";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand(query, myCon))
{
myCommand.Parameters.AddWithValue("#ObjektiMeQiraEmri", omq.ObjektiMeQiraEmri);
myCommand.Parameters.AddWithValue("#LlojiObjektit", omq.LlojiObjektit);
myCommand.Parameters.AddWithValue("#Siperfaqe", omq.Siperfaqe);
myCommand.Parameters.AddWithValue("#NumriIDHomave", omq.NumriIDHomave);
myCommand.Parameters.AddWithValue("#Kati", omq.Kati);
myCommand.Parameters.AddWithValue("#Cmimi", omq.Cmimi);
myCommand.Parameters.AddWithValue("#Vendndodhja", omq.Vendndodhja);
myCommand.Parameters.AddWithValue("#Qyteti", omq.Qyteti);
myCommand.Parameters.AddWithValue("#Shteti", omq.Shteti);
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
myCon.Close();
}
}
return new JsonResult("Added Successfully");
}
Even though I looked at other posts in stackoverflow I didn't quite find the solution.
Your insert query in C# is just plain wrong - it should be:
string query = #"INSERT INTO dbo.ObjektiMeQira (ObjektiMeQiraEmri, LlojiObjektit, Siperfaqe,
NumriIDHomave, Kati, Cmimi, Vendndodhja, Qyteti, Shteti)
VALUES (#ObjektiMeQiraEmri, #LLojiObjektit, #Siperfaqe,
#NumriIDHomave, #Kati, #Cmimi, #Vendndodhja, #Qyteti, #Shteti);";
You MUST NOT put each parameter into its own round parenthesis!
You need to provide one row of data, with a total of 9 column values - in a single VALUES (.....) statement.

Unable to implicitly convert type cross solution

Hi everyone I am new to programming, I am currently trying to create a web service to retrieve the customer information in my database but currently I am unable to solve this error, someone please help me
CustAccounts.svc.cs
public class CustAcc : ICustAccounts
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<CustAcc> GetCustAccJSON()
{
List<CustomerAccountDAL> abc = new List<CustomerAccountDAL>();
CustomerAccountDAL caDAL = new CustomerAccountDAL();
List<CustAcc> allAcc = new List<CustAcc>();
allAcc = caDAL.retrieveCustAccount();
//caDAL.retrieveCustAccount();
return allAcc;
}
}
CustomerAccountDAL.cs
public List<CustAcc> retrieveCustAccount()
{
List<CustAcc> acc = new List<CustAcc>();
using (SqlConnection myConnection = new SqlConnection(con))
{
string jString = "Select * from CustDB";
SqlCommand jCmd = new SqlCommand(jString, myConnection);
myConnection.Open();
using (SqlDataReader rr = jCmd.ExecuteReader())
{
while (rr.Read())
{
CustAcc accounts = new CustAcc();
custEmail = rr["custEmail"].ToString();
custPassword = rr["custPassword"].ToString();
acc.Add(accounts);
}
myConnection.Close();
}
}
return acc;
}
CustAcc.cs
public class CustAcc
{
public string custFullName { get; set; }
public string custPreferredName { get; set; }
public string custPassword { get; set; }
public string custEmail { get; set; }
public string custPhoneNumber { get; set; }
public string message { get; set; }
public CustAcc(string custName, string custFullName, string custPreferredName, string custPassword, string custEmail, string custPhoneNumber)
{
this.custFullName = custFullName;
this.custPreferredName = custPreferredName;
this.custPassword = custPassword;
this.custEmail = custEmail;
this.custPhoneNumber = custPhoneNumber;
}
public CustAcc()
{
this.custEmail = custEmail;
this.custPassword = custPassword;
}
}
Move your Model classes to their own assembly called Model and reference the assembly in both the WS and website assemblies.
You will also need to setup the Service reference in your website to look for the Service types in the Model assembly (it's an option in the Add Service Reference wizard).

How do I extend a model class to another model?

I am trying to extend a class to another class that will collect them as a list.
model:
public class Brand
{
public int BrandId { get; set; }
public string Name { get; set; }
public string Guid { get; set; }
public float Rating { get; set; }
public string Industry { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string CountryCode { get; set; }
public virtual Snapshot Snapshot { get; set; }
}
public class Snapshot
{
public int ID { get; set; }
public string Guid { get; set; }
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string Email { get; set; }
public DateTime DateTimeSent { get; set; }
public string Subject { get; set; }
public string Html { get; set; }
public string Image { get; set; }
public string Unsubscribe { get; set; }
}
public class BrandSnaphotViewModel
{
public Brand Brand { get; set; }
public List<Snapshot> SnapshotItems { get; set; }
}
controller:
public ActionResult Index(string brandGuid)
{
BrandSnaphotViewModel viewModel = new BrandSnaphotViewModel();
Brand brand = GetBrand(brandGuid);
viewModel.Brand = brand;
List<Snapshot> snapshot = GetBrandSnapshots(brand.BrandId);
viewModel.SnapshotItems = snapshot;
List<BrandSnaphotViewModel> viewModelList = new List<BrandSnaphotViewModel>();
viewModelList.Add(viewModel);
return View(viewModelList.AsEnumerable());
}
private Brand GetBrand(string brandGuid)
{
Brand brand = new Brand();
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
dbCmd.CommandText = "SELECT *, industries.name AS industry_name FROM brands LEFT JOIN industries ON brands.industry_id = industries.industry_id WHERE brand_guid = '" + brandGuid.ToString() + "' AND private = 0 LIMIT 1";
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
if (dbResult.Read())
{
brand.Guid = dbResult["brand_guid"].ToString();
brand.BrandId = Convert.ToInt32(dbResult["brand_id"]);
brand.Industry = dbResult["industry_name"].ToString();
}
dbResult.Close();
dbConn.Close();
return brand;
}
private List<Snapshot> GetBrandSnapshots(int brandId)
{
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
dbCmd.CommandText = "SELECT * FROM snapshots WHERE brand_id = " + brandId + " AND archive = 0 ORDER BY date_sent DESC";
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
List<Snapshot> snapshots = new List<Snapshot>();
while (dbResult.Read())
{
snapshots.Add(new Snapshot
{
SnapshotId = Convert.ToInt32(dbResult["snapshot_id"]),
Subject = dbResult["subject"].ToString(),
DateTimeSent = Convert.ToDateTime(dbResult["date_sent"]),
Image = dbResult["image"].ToString(),
Email = dbResult["email"].ToString(),
ContentType = dbResult["content_type"].ToString(),
Type = dbResult["type"].ToString()
});
}
dbResult.Close();
dbConn.Close();
return snapshots;
}
edit
FIXED
The issue was the VIEW was not referencing the ViewModel as an IENumerable<>. FACEPALM.
#model IEnumerable<projectvia.ViewModels.BrandSnaphotViewModel>
#{
ViewBag.Title = "Index";
}
#foreach(var item in Model)
{
#item.Brand.Guid;
for(int i = 0; i< #item.SnapshotItems.Count; i++)
{
#item.SnapshotItems[i].Subject<br/>
}
}
That resolved the issue.
Thank you both experts for the insights... i took both advice and came to this solution.
you are doing wrong, it is a list.
you cannot add element this way. Create object and add that object in list by calling Add()
do like this to add items in it:
List<BrandEmailList> brandSnapshotsList = new List<BrandEmailList>();
while (dbResult.Read())
{
BrandEmailList brandSnapshots = new BrandEmailList (); // create an object
brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
brandSnapshots.DateTimeSent = dbResult["date_sent"];
brandSnapshots.Subject = dbResult["subject"].ToString();
brandSnapshots.Image = dbResult["image"];
brandSnapshotsList.Add(brandSnapshots); // add it in list
}
EDIT:
List is a generic thing, you don't need to create a class for it. you can just instantiate a list and add items in it.
why are you doing like that you can do it this way simply:
List<Snapshot> brandSnapshotsList = new List<Snapshot>();
while (dbResult.Read())
{
Snapshot brandSnapshots = new Snapshot(); // create an object
brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
brandSnapshots.DateTimeSent = dbResult["date_sent"];
brandSnapshots.Subject = dbResult["subject"].ToString();
brandSnapshots.Image = dbResult["image"];
brandSnapshotsList.Add(brandSnapshots); // add it in list
}
Building on what Ehsan Sajjad did, looking at public IEnumerator<Snapshot> BrandEmails, i believe what you look for looks more like this:
public class Snapshot
{
public int ID { get; set; }
public string Guid { get; set; }
// ...
}
public class BrandEmailList : List<Snapshot>
{
}
You need not even create a new type for your brand email list, you can use List<Snapshot> directly.
public ViewResult Whatever() {
var brand = GetBrand(brandName);
var brandSnapshots = GetBrandSnapshots();
return View(brand, brandSnapshots);
}
private Brand GetBrand(string brandName)
{
try
{
var brand = new Brand();
brand.Name = brandName;
// database stuffs ...
return brand;
}
catch (Exception ex)
{
throw ex;
}
}
private List<Snapshot> GetBrandSnapshots()
{
// ...
// DB stuffs -- that *really* should not be in the controller anyways.
// ...
var snapshots = new List<BrandEmailList>();
while (dbResult.Read())
{
// object initializer syntax
snapshots.Add(new Snapshot {
ID = Convert.ToInt32(dbResult["snapshot_id"]),
Guid = dbResult["snapshot_guid"].ToString(),
DateTimeSent = dbResult["date_sent"],
Subject = dbResult["subject"].ToString(),
Image = dbResult["image"],
});
}
return snapshots
}
As a side note, mixing database access into controller methods can be a bad idea. It does not have to be, but it can be. Generally, fetching data from the database happens at a different "level" than serving a MVC result. MVC controller don't have the "purpose" to talk to a database, that work can/should be delegated to a dedicated type. Compare the single responsibility principle part of the SOLID principles.

Values from textbox is not being passed to SQL using MVC

Form code:
public partial class Customer_Information : Form
{
private Controller controller;
Customer_Information info;
public Customer_Information()
{
InitializeComponent();
controller = new Controller();
}
private void Customer_Information_Load(object sender, EventArgs e)
{
// btnnext.Enabled = false;
info = new Customer_Information();
}
private void btnsave_Click(object sender, EventArgs e)
{
View view = controller.CreateProduct(info);
controller.InsertProduct(view);
}
View.cs:
class View
{
public string BILL_TO { get; set; }
public string SHIP_TO { get; set; }
public string VENDOR { get; set; }
public string BUYER { get; set; }
public string TERMS { get; set; }
public string CONTACTS { get; set; }
public string CURRENCY { get; set; }
public string PONUM { get; set; }
public string ENTRYDATE { get; set; }
public string SHIPDATE { get; set; }
public string CANCELDATE { get; set; }
public string ORDERTYPE { get; set; }
public View(string billto, string shipto, string vendor, string buyer, string terms, string contacts, string currency, string ponum, string entryd, string shipd, string canceld, string ordert)
{
BILL_TO = billto;
SHIP_TO = shipto;
VENDOR = vendor;
BUYER = buyer;
TERMS = terms;
CONTACTS = contacts;
CURRENCY = currency;
PONUM = ponum;
ENTRYDATE = entryd;
SHIPDATE = shipd;
CANCELDATE = canceld;
ORDERTYPE = ordert;
}
Controller.cs:
class Controller
{
private Model model;
public Controller()
{
model = new Model();
}
public View CreateProduct(Customer_Information info)
{
string billto = info.txtbillto.Text;
string shipto = info.txtshipto.Text;
string vendor = info.txtvendor.Text;
string buyer = info.txtbuyer.Text;
string terms = info.txtterms.Text;
string contacts = info.txtcontact.Text;
string currency = info.cmbcurrrecncy.Text;
string ponum = info.txtponum.Text;
string entryd = info.txtentrydate.Text;
string shipd = info.txtshipdate.Text;
string canceld = info.txtcanceldate.Text;
string ordert = info.txtorder.Text;
View view = new View(billto, shipto, vendor, buyer, terms, contacts, currency, ponum, entryd, shipd, canceld, ordert);
return view;
}
public void InsertProduct(View view)
{
model.InsertProduct(view);
}
Model.cs:
class Model{
SqlConnection connect;
SqlDataAdapter data = new SqlDataAdapter();
public Model()
{
connect = new SqlConnection("connection");
}
public void InsertProduct(View view)
{
string billto = view.BILL_TO;
string shipto = view.SHIP_TO;
string vendor = view.VENDOR;
string buyer = view.BUYER;
string terms = view.TERMS;
string contacts = view.CONTACTS;
string currency = view.CURRENCY;
string ponum = view.PONUM;
string entryd = view.ENTRYDATE;
string shipd = view.SHIPDATE;
string canceld = view.CANCELDATE;
string ordert = view.ORDERTYPE;
data.InsertCommand = new SqlCommand("INSERT INTO PURCHASE VALUES(#Bill_to, #Ship_to, #Vendor, #Buyer, #Terms, #Contact, #Currency, #PO_number, #Entry_date, #Ship_date, #Cancel_Date, #Order_type)", connect);
data.InsertCommand.Parameters.Add("#Bill_to", SqlDbType.VarChar).Value = billto;
data.InsertCommand.Parameters.Add("#Ship_to", SqlDbType.VarChar).Value = shipto;
data.InsertCommand.Parameters.Add("#Vendor", SqlDbType.VarChar).Value = vendor;
data.InsertCommand.Parameters.Add("#Buyer", SqlDbType.VarChar).Value = buyer;
data.InsertCommand.Parameters.Add("#Terms", SqlDbType.VarChar).Value = terms;
data.InsertCommand.Parameters.Add("#Contact", SqlDbType.VarChar).Value = contacts;
data.InsertCommand.Parameters.Add("#Currency", SqlDbType.VarChar).Value = currency;
data.InsertCommand.Parameters.Add("#PO_number", SqlDbType.VarChar).Value = ponum;
data.InsertCommand.Parameters.Add("#Entry_date", SqlDbType.VarChar).Value = entryd;
data.InsertCommand.Parameters.Add("#Ship_date", SqlDbType.VarChar).Value = shipd;
data.InsertCommand.Parameters.Add("#Cancel_Date", SqlDbType.VarChar).Value = canceld;
data.InsertCommand.Parameters.Add("#Order_type", SqlDbType.VarChar).Value = ordert;
connect.Open();
data.InsertCommand.ExecuteNonQuery();
connect.Close();
}
The program completes, but upon checking the database, the values passed are empty.
You can use
TableName object=new Tablename();
object.field1=value;
object.field2=value;
db.TableName.AddObject(object);

Incorrect JSON Date

I am having trouble with the representation of a date in JSON. I am using Service Stack as a web service to get the data from. My code on the server side is as follows:
public object Execute(GetNoPatientList request)
{
NoPatientList _noPatientList = new NoPatientList();
List<string> _noMatchPatientList = new List<string>();
List<NoPatientList> _newList = new List<NoPatientList>();
try
{
using (SqlConnection cn = new SqlConnection(Database.WaldenWebConnection))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandText = "select [DateTimeStamp] as DateCreated,[ID],[PatientMRN],[FirstName],[MiddleName]"
+ " ,[LastName],convert(varchar,[DOB],101) as DOB,[Sex],[Note],[Source] as Interface"
+ " from PatientNoMatch"
+ " where FoundMatch = 'F'"
+ " and Show = 'T'"
+ " order by DateTimeStamp desc";
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
NoPatientList _noPatientList1 = new NoPatientList();
_noPatientList1.PatientMRN = dr["PatientMRN"].ToString();
_noPatientList1.FirstName = dr["FirstName"].ToString();
_noPatientList1.MiddleName = dr["MiddleName"].ToString();
_noPatientList1.LastName = dr["LastName"].ToString();
_noPatientList1.DOB = dr["DOB"].ToString();
_noPatientList1.Sex = dr["Sex"].ToString();
_noPatientList1.Note = dr["Note"].ToString();
_noPatientList1.DateCreated = dr.GetDateTime(0);
_noPatientList1.Interface = dr["Interface"].ToString();
_newList.Add(_noPatientList1);
}
return _newList;
}
}
}
catch
{
return _newList;
}
}
The type is represented as follows:
[DataContract]
public class NoPatientList
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string PatientMRN { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string MiddleName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Sex { get; set; }
[DataMember]
public string DOB { get; set; }
[DataMember]
public string Note { get; set; }
[DataMember]
public DateTime DateCreated { get; set; }
[DataMember]
public string Interface { get; set; }
}
The web service is being consumed by a Silverlight application from the following call:
/InterfaceUtility/servicestack/json/syncreply/
The Silverlight application is processing the code into a grid using the following code
private void GetNoPatientMatchData()
{
try
{
gridViewNoMatch.ItemsSource = null;
}
catch { }
_client = new WebClient();
_client.OpenReadCompleted += (a, f) =>
{
if (!f.Cancelled && f.Error == null)
{
_listOfNoPatientsMatches = new List<NoPatientList>();
MemoryStream _memoryStream = new MemoryStream();
f.Result.CopyTo(_memoryStream);
_memoryStream.Position = 0;
StreamReader _streamReader = new StreamReader(_memoryStream);
string _memoryStreamToText = _streamReader.ReadToEnd();
List<NoPatientList> _deserializedNoPatientList = (List<NoPatientList>)Newtonsoft.Json.JsonConvert.DeserializeObject(_memoryStreamToText, typeof(List<NoPatientList>));
gridViewNoMatch.ItemsSource = _deserializedNoPatientList;
}
else
{
MessageBox.Show(f.Error.Message,
"Error", MessageBoxButton.OK);
}
};
_client.OpenReadAsync(new Uri(_serviceUri + "getnopatientlist"));
The issue is that the times on DateTime field appear to always 6 hours off.
Any ideas as to what is going on?
This is probably a time zone issue. Check that:
Your webservice is returning you dates/times in UTC format.
Your code is parsing these dates/times as UTC dates and times.

Categories