I've got a booking system program, and one form lists the bookings already made depending on the date selected. All the times of the bookings made on the selected date were to be shown in the list box. The selected item in the list box would then populate the text boxes below with all the booking data.
However, I'm getting this error:
System.InvalidCastException: 'Specified cast is not valid.'
This is the bookingClass:
public DateTime bookingDate
{
get
{
return myDate;
}
set
{
myDate = value;
}
}
public string bookingTime
{
get
{
return myTime;
}
set
{
myTime = value;
}
}
public int bookingID
{
get
{
return myID;
}
set
{
myID = value;
}
}
public int customerID
{
get
{
return myCust;
}
set
{
myCust = value;
}
}
public string bookingTicket
{
get
{
return myTicket;
}
set
{
myTicket = value;
}
}
public int bookingQuantity
{
get
{
return myNum;
}
set
{
myNum = value;
}
}
public decimal bookingTotal
{
get
{
return myTotal;
}
set
{
myTotal = value;
}
}
//A SortedList of booking times is returned for a given Date
public SortedList GetBookingsByDate(DateTime bookingDate)
{
newCon = new System.Data.SqlClient.SqlConnection();
String firstConStr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=";
String pathToDB = "F:\\Level 5\\Object Oriented Programs\\Programs\\assignmentPractice\\assignmentPractice\\assignmentDB.mdf;";
String lastConStr = "Integrated Security=True;Connect Timeout=30;User Instance=True";
newCon.ConnectionString = firstConStr + pathToDB + lastConStr;
newCon.Open();
SqlCommand cmBookList = new SqlCommand();
cmBookList.Connection = newCon;
cmBookList.CommandType = CommandType.Text;
cmBookList.CommandText = "Select bookingID, bookingTime from Booking where bookingDate = '" + bookingDate.ToLongDateString() + "'";
SqlDataReader drBookList = cmBookList.ExecuteReader();
//This is a sorted list of key/value pairs
SortedList BookList = new SortedList();
//drBookList[0] is the key (Booking ID) and drBookList[1] is the value (Booking Time)
while (drBookList.Read())
{
BookList.Add(drBookList[0], drBookList[1]);
}
drBookList.Close();
newCon.Close();
return BookList;
}
}
This is the form:
public bookingSearch()
{
InitializeComponent();
}
private SortedList BookList;
private bookingClass objBooking;
private void btnList_Click(object sender, EventArgs e)
{
lstBook.Items.Clear();
bookingClass objBooking = new bookingClass();
BookList = objBooking.GetBookingsByDate(DateTime.Parse(dtpDate.Text));
//Populate the ListBox with the Booking times
if (BookList.Count == 0)
{
lstBook.Items.Add("No Records");
return;
}
foreach (DictionaryEntry book in BookList)
{
lstBook.Items.Add(book.Value);
}
lstBook.SelectedIndex = 0;
}
private void lstBook_SelectedIndexChanged(object sender, EventArgs e)
{
if (BookList.Count > 0) //Don't process if 'No Records'
{
//Get the Booking details for a particular selected time in the list
//The SelectedIndex is used to read the Key value from the
//SortedList which holds the bookingID
objBooking.GetBookingsByDate((DateTime)BookList.GetKey(lstBook.SelectedIndex));
txtID.Text = objBooking.bookingID.ToString();
txtCust.Text = objBooking.customerID.ToString();
txtTime.Text = objBooking.bookingTime;
txtTicket.Text = objBooking.bookingTicket;
txtNum.Text = objBooking.bookingQuantity.ToString();
txtTotal.Text = objBooking.bookingTotal.ToString();
}
}
}
It's highlighting this line when I get the error:
objBooking.GetBookingsByDate((DateTime)BookList.GetKey(lstBook.SelectedIndex))
Any help is much appreciated.
Related
I have:
private void Tab2KsiazkiBTSzczegoly_Click(object sender, EventArgs e)
{
string KodKsiazki;
KodKsiazki = DataWyszukajKsiazki.Rows[DataWyszukajKsiazki.CurrentCell.RowIndex].Cells[2].Value.ToString();
TSzczegolyDb _szczegoly = new TSzczegolyDb();
Global.listSzczegoly = _szczegoly.GetSZCZEGOLY(KodKsiazki);
//StringBuilder sb = new StringBuilder();
//foreach (DataGridViewCell cell in DataWyszukajKsiazki.SelectedCells)
//{
// sb.AppendLine(cell.Value.ToString());
//}
//MessageBox.Show(sb.ToString());
//}
MessageBox.Show(_szczegoly.ToString());
}
class like that:
public class TSzczegolyDb : Core.CoreMSSQL
{
static string connectionString = TconStrDb.GetConectionString();
public TSzczegolyDb()
: base(connectionString)
{
}
public List<TSzczegolyDto> GetSZCZEGOLY(string co)
{
List<TSzczegolyDto> list = null;
list = new List<TSzczegolyDto>();
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT Tytul, Autorzy, ISBN10, ISBN13, IlStron, Wydawnictwo, Gatunek, Opis FROM dbo.TKsiazki WHERE dbo.TKsiazki.KodKsiazki = '" + co + "'";
SqlDataReader reader = ExecuteQuery(command);
while (reader.Read())
{
TSzczegolyDto message = new TSzczegolyDto();
if (!reader.IsDBNull(0))
{
message.Tytuł = reader.GetString(0);
}
if (!reader.IsDBNull(1))
{
message.Autorzy = reader.GetString(1);
}
if (!reader.IsDBNull(2))
{
message.ISBN10 = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
message.ISBN13 = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
message.IlStron = reader.GetInt32(4);
}
if (!reader.IsDBNull(5))
{
message.Wydawnictwo = reader.GetString(5);
}
if (!reader.IsDBNull(6))
{
message.Gatunek = reader.GetString(6);
}
if (!reader.IsDBNull(7))
{
message.Opis = reader.GetString(7);
}
list.Add(message);
}
return list;
}
and second:
public class TSzczegolyDto
{
private string _tytul;
public string Tytuł
{
get { return _tytul; }
set { _tytul = value; }
}
private string _autorzy;
public string Autorzy
{
get { return _autorzy; }
set { _autorzy = value; }
}
private string _ISBN10;
public string ISBN10
{
get { return _ISBN10; }
set { _ISBN10 = value; }
}
private string _ISBN13;
public string ISBN13
{
get { return _ISBN13; }
set { _ISBN13 = value; }
}
private long _ilstron;
public long IlStron
{
get { return _ilstron; }
set { _ilstron = value; }
}
private string _wydawnictwo;
public string Wydawnictwo
{
get { return _wydawnictwo; }
set { _wydawnictwo = value; }
}
private string _gatunek;
public string Gatunek
{
get { return _gatunek; }
set { _gatunek = value; }
}
private string _opis;
public string Opis
{
get { return _opis; }
set { _opis = value; }
}
}
I want show _szczegoly on MessageBox but when I try to MessageBox.Show(_szczegoly.ToString()); then is wrong. In _szczegoly I have string and long type data.
How to create messagebox with this data?
I think you are trying to show an Object with a MessageBox, you need to override the ToString() method to show propertly:
class TSzczegolyDb
{
public override string ToString()
{
return this.Property1 + this.Property2 /*....*/;
}
}
I want to load values from database in user control
I could add more user control but I cant't able to load values in user control
Code:
Add.aspx.cs
Below code is for adding more than one user control and retain the previous control values
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
GenerateControls();
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
VisaUserControl ctrl = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");
ctrl.ID = i;
this.rpt1.Controls.Add(ctrl);
}
}
protected void btnAddVisa_Click(object sender, EventArgs e)
{
List<string> temp = null;
var uc = (VisaUserControl)this.LoadControl(#"VisaUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
rpt1.Controls.Add(uc);
}
Edit.aspx.cs
Below code is for loading values from database in user control
using (OleDbCommand cmd = new OleDbCommand("Select * from visa_details where emp_id = '"+ empid +"'", DbConnection))
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
OleDbDataReader DR1 = cmd.ExecuteReader();
while(DR1.Read())
{
//Here I can get values
string visaNumb = DR1[2].ToString();
string visaCountry = DR1[3].ToString();
string visaType = DR1[4].ToString();
string visaEntry = DR1[5].ToString();
string expiryDate = DR1[6].ToString();
for (int i = 0; i < y; i++)
{
VisaUserControl userconrol = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");
userconrol.TextVisaNumber = visaNumb;
userconrol.VisaCountry = visaCountry;
userconrol.VisaType = visaType;
userconrol.VisaEntry = visaEntry;
userconrol.ExpiryDate = expiryDate;
repeater1.Controls.Add(userconrol);
}
}
}
.ascx.cs
Here values are there but when it is loading all values are removed
protected void Page_Load(object sender, EventArgs e)
{
txtUser.Text = Request.Form[txtUser.UniqueID];
dropCountry.SelectedValue = Request.Form[dropCountry.UniqueID];
dropVisa.SelectedValue = Request.Form[dropVisa.UniqueID];
dropEntry.SelectedValue = Request.Form[dropEntry.UniqueID];
txtDate.Text = Request.Form[txtDate.UniqueID];
}
public string TextVisaNumber
{
get { return txtUser.Text; }
set { txtUser.Text = value; }
}
public string VisaCountry
{
get { return dropCountry.SelectedValue; }
set { dropCountry.SelectedValue = value; }
}
public string VisaType
{
get { return dropVisa.SelectedValue; }
set { dropVisa.SelectedValue = value; }
}
public string VisaEntry
{
get { return dropEntry.SelectedValue; }
set { dropEntry.SelectedValue = value; }
}
public string ExpiryDate
{
get
{
return txtDate.Text;
}
set
{
txtDate.Text = value;
}
}
Any ideas? Thanks in advance
Instead of adding the control in the page's controls collection, you should keep an set the data in some existing control's inner HTML.
I am writing code in C# where I want to select data in data-grid from multiple tables with a relation. Here I have a Client & Item_Configuration as parent tables, and Item_Order as child table which has a foreign keys to the Client and Item_Configuration tables. I just want to fetch data from all three tables and display on a datagrid.
My stored procedure is:
ALTER PROC [dbo].[Full_SP]
#clientName varchar(50) = null,
#itemName varchar(50) = null,
#clientId_FK varchar(50) = null,
#operation int
AS
BEGIN
SET NOCOUNT ON;
IF #operation = 2
BEGIN
SELECT
Client.clientName, Item_Configuration.itemName,
Item_Order.orderId, Item_Order.orderDate,
Item_Order.Quantity, Item_Order.status, Item_Order.totalPrice
FROM
Item_Order
INNER JOIN
Client ON Item_Order.clientId_FK = Client.clientId
JOIN
Item_Configuration ON Item_Order.itemId_FK = Item_Configuration.itemId
END
END
and my function of search to data grid is in C# i.e.
private void btnSrchFull_Click(object sender, EventArgs e)
{
SqlConnection conn1 = new SqlConnection();
try
{
conn1.ConnectionString = "server=.\\ms2k5;database=Info_Connect;Trusted_Connection=true";
conn1.Open();
SqlCommand selectFull = new SqlCommand("Full_SP", conn1);
selectFull.CommandType = CommandType.StoredProcedure;
selectFull.Parameters.Add("#operation", SqlDbType.VarChar);
selectFull.Parameters["#operation"].Value = 2;
SqlDataReader myReader = selectFull.ExecuteReader();
List<FullFill> list = new List<FullFill>();
while (myReader.Read())
{
if (myReader.HasRows)
{
FullFill fullfill = new FullFill();
fullfill = MapFullfill(myReader, fullfill);
list.Add(fullfill);
}
}
myReader.NextResult();
foreach (FullFill ffll in list)
{
if (myReader.Read() && myReader.HasRows)
{
MapClint(myReader, ffll);
}
}
myReader.NextResult();
foreach (FullFill ffll1 in list)
{
if (myReader.Read() && myReader.HasRows)
{
MapItem(myReader, ffll1);
}
}
dataGridView1.DataSource = list;
double totPrice = 0;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
totPrice = totPrice +
Convert.ToDouble(dataGridView1.Rows[i].Cells[5].Value);
totCost.Text = totPrice.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace + MessageBoxIcon.Error);
}
finally
{
if (conn1.State != ConnectionState.Closed)
{
conn1.Close();
}
}
}
private FullFill MapItem(SqlDataReader myReader, FullFill itemName)
{
itemName.ItemName =myReader["itemName"].ToString();
return itemName;
}
private FullFill MapClient(SqlDataReader myReader, FullFill clientName)
{
clientName.ClientName = myReader["clientName"].ToString();
return clientName;
}
private FullFill MapFullfill(SqlDataReader myReader, FullFill fullfill)
{
fullfill.OrderNo = myReader["orderId"].ToString();
fullfill.OrderDate = Convert.ToDateTime(myReader["orderDate"]);
fullfill.Quantity = Convert.ToInt32(myReader["Quantity"]);
fullfill.Status = myReader["status"].ToString();
fullfill.TotalPrice = Convert.ToDouble(myReader["totalPrice"]);
return fullfill;
}
and I create a class for property i.e.
class FullFill
{
public string orderNo;
public string clientName;
public DateTime orderDate;
public string itemName;
public int quantity;
public double totCost;
public string status;
public string OrderNo
{
get { return orderNo; }
set { orderNo = value; }
}
public string ClientName
{
get { return clientName; }
set { clientName = value; }
}
public DateTime OrderDate
{
get { return orderDate; }
set { orderDate = value; }
}
public string ItemName
{
get { return itemName; }
set { itemName = value; }
}
public int Quantity
{
get { return quantity; }
set { quantity = value; }
}
public double TotalPrice
{
get { return totCost; }
set { totCost = value; }
}
public string Status
{
get { return status; }
set { status = value; }
}
}
The problem is that I am only able to find data from child table(Item_Order) I am not getting data from parent tables
Maybe it is easier to create a view in SQL and run your stored procedure (select) on that and you can easily display everything.
I just edit some code on the function MapFullFill(). With what code I wrote in MapClint() and MapItem() because there is only one query there which returns all the records so there is no need of nextResult() function.
Below is the class file
public class BillDetails
{
private string chargecategory;
[XmlAttribute("ChargeCategory")]
public string ChargeCategory
{
get { return chargecategory; }
set { chargecategory = value; }
}
private string customername;
[XmlAttribute("CustomerName")]
public string CustomerName
{
get { return customername; }
set { customername = value; }
}
private List<Details> details;
[XmlArray("Details")]
[XmlArrayItem("details")]
// public List<Details> details = new List<Details>();
public List<Details> Details
{
get { return details; }
set { details = value; }
}
now in my code I need to databind only the properties which belong to List
List<BillDetails> billlist = new List<BillDetails>();
public int x;
List<Details> newdetails = new List<Details>();
public void Button1_Click(object sender, EventArgs e)
{
if (IsValidPost())
{
if (Session["BillList"] == null)
{
newdetails.Add(new Details() { ChargeCode = ChargeCode.Text, MaterialCode = MaterialCode.Text, GLAccount = GLAccount.Text, CostCenter = CostCenter.Text, Price = Convert.ToDecimal(Price.Text), Quantity = Convert.ToInt32(Quantity.Text), UOM = UOM.Text, Total = Convert.ToDecimal(Price.Text) * Convert.ToInt32(Quantity.Text) });
billlist.Add(new BillDetails() { ChargeCategory = ChargeCategory.Text, Details = newdetails.ToList(), CustomerName = CustomerName.Text });
GridView1.DataSource = newdetails *---works ...but if I give the datasource as billlist it does not ...but I want get down to newdetails from billlist.
GridView1.DataBind();
//Session["BillList"] = newdetails;
Session["BillList"] = billlist;
cleartextboxes();
serializetoxml(billlist);
}
how do i achieve this...also in the ascx file how do I databind the columns to the properties which are in details
I would assume DataMember = "Details"; would do this (but I don't personally use webforms data-binding, so my apologies if this fails).
After filling the form when i am clicking on submit button...nothing is happening i mean no events are performed. Pls help me... here is my code..
PatientProperty.cs
public class PatientProperty
{
private string Pdisease;
private string Pname;
private string Pcategory;
private string Paddr;
private DateTime Dateofjoining;
private int Page;
public string PNAME
{
get
{
return Pname;
}
set
{
Pname = value;
}
}
public string PADDRESS
{
get
{
return Paddr;
}
set
{
Paddr = value;
}
}
public int PAGE
{
get
{
return Page;
}
set
{
Page = value;
}
}
public string PDISEASE
{
get
{
return Pdisease;
}
set
{
Pdisease = value;
}
}
public string PCATEGORY
{
get
{
return Pcategory;
}
set
{
Pcategory = value;
}
}
public DateTime DATEOFJOINING
{
get
{
return Dateofjoining;
}
set
{
Dateofjoining = value;
}
}
}
PatientRegistration.cs
public class PatientRegistration
{
string str = ConfigurationManager.ConnectionStrings["HealthCare"].ConnectionString.ToString();
public void InsertPatient(PatientProperty obj)
{
using (var con = new SqlConnection(str))
{
using (var com = new SqlCommand("PatientRegister", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("Pname", obj.PNAME);
com.Parameters.AddWithValue("Paddr", obj.PADDRESS);
com.Parameters.AddWithValue("Page", obj.PAGE);
com.Parameters.AddWithValue("Pdisease", obj.PDISEASE);
com.Parameters.AddWithValue("Pcategory", obj.PCATEGORY);
com.Parameters.AddWithValue("Dateofjoining", obj.DATEOFJOINING); con.Open();
com.ExecuteNonQuery();
con.Close();
}
}
}
}
PatientRegistrationBussiness.cs
public class PatientRegistrationBussiness
{
public void AddPatient(PatientProperty obj)
{
PatientRegistration PR = new PatientRegistration();
PR.InsertPatient(obj);
}
}
protected void Button1_Click(object sender, System.EventArgs e)
{
string name = TextBox2.Text;
string address = TextBox3.Text;
string category = RadioButtonList1.Text;
int age =Convert.ToInt32(TextBox4.Text);
string disease = TextBox5.Text;
DateTime date =Convert.ToDateTime(TextBox6.Text);
PatientRegistrationBussiness obj = new PatientRegistrationBussiness();
try
{
PatientProperty PP = new PatientProperty();
PP.PNAME = name;
PP.PADDRESS = address;
PP.PAGE = age;
PP.PDISEASE = disease;
PP.PCATEGORY = category.ToString();
PP.DATEOFJOINING = date;
obj.AddPatient(PP);
Response.Write("Patient details have been successfully added");
TextBox2.Text = string.Empty;
TextBox3.Text = string.Empty;
TextBox4.Text = string.Empty;
TextBox5.Text = string.Empty;
TextBox6.Text = string.Empty;
RadioButtonList1.SelectedIndex = 0;
}
catch (Exception ex)
{
ex.Message.ToString();
}
finally
{
obj = null;
}
}
You have to hook up your events e.g. this.Load += new EventHandler(Page_Load); unless you set the AutoEventWireup="true".
Try putting a breakpoint in the Button1_Click method. In particular, I expect that an exception is being thrown and lost:
catch (Exception ex)
{
ex.Message.ToString();
}
does nothing! Either show the message to the user, or log it somewherre (perhaps Trace.WriteLine(ex)).
Also - don't set obj to null - there is no purpose.