Why is this ignoring the where clause? - c#

Why is the where clause being ignored in this code? It seems to be ignoring the where clause on the update which means every records has been written over. How can i fix this? Any help would be greatly appreciated.
namespace ResitAssignment2
{
public partial class HomeCareVisitEddit : Form
{
public HomeCareVisitEddit()
{
InitializeComponent();
}
private void SubmitHCVA_Click(object sender, EventArgs e)
{
SqlConnection a = Database.GetConnection();
a.Open();
string sqltext;
sqltext = #"update HomeCareVisit set
PatientNo=#PatientNo,
FurtherVisitRequired=#FurtherVisitRequired,
AdvisoryNotes=#AdvisoryNotes,
Prescription=#Prescription,
TreatmentProvided=#TreatmentProvided,
ActualVisitDateTime=#ActualVisitDateTime,
Priority=#Priority,
ScheduledDateTime=#ScheduledDateTime,
TreatmentInstructions=#TreatmentInstructions,
MedicalStaffID=#MedicalStaffID
WHERE
VisitRefNo=VisitRefNo";
SqlCommand command = new SqlCommand(sqltext, a);
try
{
using (a)
{
command.Parameters.AddWithValue("#PatientNo", PatientNo.Text);
command.Parameters.AddWithValue("#FurtherVisitRequired", FurtherVisitRequired.Text);
command.Parameters.AddWithValue("#AdvisoryNotes", AdvisoryNotes.Text);
command.Parameters.AddWithValue("#Prescription", Prescription.Text);
command.Parameters.AddWithValue("#TreatmentProvided", TreatmentProvided.Text);
command.Parameters.AddWithValue("#ActualVisitDateTime",SqlDbType.DateTime );
{
DateTime.Parse(ActualVisitDateTime.Text);
};
command.Parameters.AddWithValue("#Priority", Priority.Text);
command.Parameters.AddWithValue("#ScheduledDateTime",SqlDbType.DateTime );
{
DateTime.Parse(ScheduledDateTime.Text);
};
command.Parameters.AddWithValue("#TreatmentInstructions", TreatmentInstructions.Text);
command.Parameters.AddWithValue("#MedicalStaffID", MedicalStaffID.Text);
command.Parameters.AddWithValue("#VisitRefNo", VisitRefNo.Text);
command.ExecuteNonQuery();
MessageBox.Show("Record altered");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
a.Close();
}
private void HomeCareVisitEddit_Load(object sender, EventArgs e)
{
SqlConnection a = Database.GetConnection();
a.Open();
string sqlText = "select * from HomeCareVisit where VisitRefNo =" + VisitRefNo;
SqlCommand command = new SqlCommand(sqlText, a);
SqlDataReader HomeCareVisitData = command.ExecuteReader();
while (HomeCareVisitData.Read())
{
//DateTime actual = DateTime.Parse("ActualVisitDateTime");
//DateTime scheduled = DateTime.Parse("ActualVisitDateTieme");
PatientNo.Text = HomeCareVisitData["PatientNo"].ToString();
FurtherVisitRequired.Text = HomeCareVisitData["FurtherVisitRequired"].ToString();
AdvisoryNotes.Text = HomeCareVisitData["AdvisoryNotes"].ToString();
Prescription.Text = HomeCareVisitData["Prescription"].ToString();
TreatmentProvided.Text = HomeCareVisitData["TreatmentProvided"].ToString();
ActualVisitDateTime.Text = HomeCareVisitData["ActualVisitDateTime"].ToString();
Priority.Text = HomeCareVisitData["Priority"].ToString();
ScheduledDateTime.Text = HomeCareVisitData["ScheduledDateTime"].ToString();
TreatmentInstructions.Text = HomeCareVisitData["TreatmentInstructions"].ToString();
MedicalStaffID.Text = HomeCareVisitData["MedicalStaffID"].ToString();
}
a.Close();
}
}
}

WHERE VisitRefNo=VisitRefNo"; should be WHERE VisitRefNo=#VisitRefNo";.

WHERE VisitRefNo=VisitRefNo
Should be
WHERE VisitRefNo=#VisitRefNo

Related

I'm having a problem with MySql in C# .Net Framework

I'm migrating from Access to MySql. When "btn_Ekle" is clicked, the shelf is added to the database, but the codes written afterwards do not work.
Also, RafListesi() works at first, but when we close the Add Shelves window after adding a shelf and then open it again, the shelfs are not listed. It is listed after reopening the program.
public static ClassRaf RafEkle(string ad)
{
ClassRaf result;
try
{
if (ClassData.RafSec(ad) != null)
{
MessageBox.Show("Eklemek İstediğiniz Raf Zaten Kayıtlarda Mevcut.", "Kütüphane Sistemi | Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
result = null;
}
else
{
MySqlCommand sqlCommand = new MySqlCommand("INSERT INTO bookrack (shelf_name) VALUES (#shelf_name)", ClassData.connectSql);
sqlCommand.Parameters.Add("#shelf_name", MySqlDbType.VarChar).Value = ad;
if (sqlCommand.ExecuteNonQuery() > 0)
{
MySqlCommand sqlCommand1 = new MySqlCommand("SELECT * FROM bookrack ORDER BY id DESC", ClassData.connectSql);
MySqlDataReader sqlDataReader = sqlCommand1.ExecuteReader();
if (sqlDataReader.Read())
{
result = ClassData.RafSec((int)sqlDataReader["id"]);
}
else
{
result = null;
}
}
else
{
result = null;
}
}
}
catch
{ result = null; }
return result;
}
private void btnEkle_Click(object sender, EventArgs e)
{
ClassRaf classRaf = ClassData.RafEkle(txtEkle.Text);
if (classRaf != null)
{
txtEkle.Text = "";
liste.Items.Add(classRaf.Ad);
ClassLog.Log(string.Concat(new object[]
{
classRaf.Ad,
" adlı raf eklendi. ID=[",
classRaf.ID,
"]"
}));
ShelfValid();
txtEkle.Select();
}
}
public static List<ClassRaf> RafListesi()
{
List<ClassRaf> result;
try
{
List<ClassRaf> list = new List<ClassRaf>();
MySqlCommand sqlCommand = new MySqlCommand("SELECT * FROM bookrack", ClassData.connectSql);
MySqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
list.Add(new ClassRaf
{
ID = Convert.ToInt32(sqlDataReader["id"]),
Ad = sqlDataReader["shelf_name"].ToString()
});
}
result = list;
sqlDataReader.Close();
sqlDataReader.Dispose();
}
catch
{ result = new List<ClassRaf>(); }
return result;
}
public static ClassRaf RafEkle(string ad) - (Add Shelf)
private void btnEkle_Click
private void btnEkle_Click(object sender, EventArgs e)

No value given for one or more required parameters - C#/Access

This is my first time attempting to read an Access database and write each row to the console. When I execute the application I get thrown an exception that says, "No value given for one or more required parameters" on the following statement:
OleDbDataReader reader = cmd.ExecuteReader();
I'm relatively new to c# programming and after hours of research, I can't figure out what I'm doing wrong. Here's my code:
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
In response to the commenters, I'm posting a larger piece of code to eliminate any assumptions and give a better overall picture of what I'm trying to do:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace AzFloodSquad
{
public partial class frm1DefaultScreen : Form
{
//Initialize the application
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Databases\\AzFloodSquad\\AzFloodSquad.accdb;Persist Security Info=False;";
OleDbConnection conn = null;
String error_message = "";
String q = "";
string varReportId = "";
public frm1DefaultScreen()
{
InitializeComponent();
}
//Load the default form
private void frm1DefaultScreen_Load(object sender, EventArgs e)
{
connectToolStripMenuItem.PerformClick();
contactsToolStripMenuItem.PerformClick();
}
//Exit the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
//Start the database
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection(conn_string);
conn.Open();
disconnectToolStripMenuItem.Enabled = true;
connectToolStripMenuItem.Enabled = false;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Stop the database
private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn.Close();
disconnectToolStripMenuItem.Enabled = false;
connectToolStripMenuItem.Enabled = true;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Clean up database whem form close button clicked
private void frm1DefaultScreen_FormClosing(object sender, FormClosingEventArgs e)
{
disconnectToolStripMenuItem.PerformClick();
}
private void contactsToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "Contacts";
q = "SELECT * " +
"FROM CONTACTS WHERE CONTACTS.CONTACT_TYPE = 'CUSTOMER' " +
"OR CONTACTS.CONTACT_TYPE = 'HOMEOWNER' OR CONTACTS.CONTACT_TYPE = 'HOME OWNER' " +
"OR CONTACTS.CONTACT_TYPE = 'TENANT'" +
"ORDER BY FULL_NAME";
this.Cursor = Cursors.WaitCursor;
run_Query_Parm(q);
this.Cursor = Cursors.Default;
}
//Pull data from the database using the parameter field
private void run_Query_Parm(String q)
{
error_message = "";
try
{
OleDbCommand cmd = new OleDbCommand(q, conn);
OleDbDataAdapter a = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
a.SelectCommand = cmd;
a.Fill(dt);
results.DataSource = dt;
results.AutoResizeColumns();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
//Clear all data from the screen
private void clearFormToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "";
if (this.results.DataSource != null)
{
this.results.DataSource = null;
}
else
{
this.results.Rows.Clear();
}
}
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
Any help provided would be greatly appreciated. Thanks in advance.
I found the problem. Apparently, I had improper syntax on my SELECT statement. When I replaced my SELECT, (shown in the first code example I posted), with the following, it worked fine:
string inputString = "SELECT Contacts.[Account_Number], " +
"Contacts.[Full_Name], Contacts.[ID], Contacts.[Street], " +
"Contacts.[City], Contacts.[State], Contacts.[Zip] FROM Contacts";

The connection is open

A few months ago I made a test program for a project and everything worked fine there.
Now I am working on the program itself, so I copied the code from the test program and
changed the the names of the columns,buttons etc. so it would fit the current program.
When I try to add something into the database it does nothing on the first click, on the
second pops up an error which says that the connection is open.. I really got no idea what's
the problem. I tried to check again if I made a mistake in a column name or the database name
but everything seems to be correct.
Note: I also have a function that show data from the database and it works without any problem.
private void InsertData()
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
Connection.Open();
DataAdd.ExecuteNonQuery();
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
string NewRowNum()
{
string Row = RowFind();
int CalcRow = int.Parse(Row) + 1;
Row = CalcRow.ToString();
return Row;
}
The connection that appears to be open is the one in the string RowFind().
Here are the other related things to the database:
public partial class frmShop : Form
{
System.Data.SqlClient.SqlConnection Connection;
public frmShop()
{
string DatabaseConnection = WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1;
Connection = new System.Data.SqlClient.SqlConnection();
Connection.ConnectionString = DatabaseConnection;
InitializeComponent();
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
Connection.Open();
SqlDataReader ReadSentence = null;
Int32 BinaryInt = Int32.Parse(txtBinaryString.Text);
string CommandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
SqlCommand Command = new SqlCommand(CommandString, Connection);
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
ReadSentence = Command.ExecuteReader();
while (ReadSentence.Read())
{
txtSentence.Text = (ReadSentence["Sentence"].ToString());
Fit = 1;
}
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You are getting errors because you are reusing the same connection Connection.Open(); several times.
Your method InsertData() is doing this 3 times in the same method.
You should create a new instance of the connection object and dispose it on your methods.
Using Statement are the way to go.
private void InsertData()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
Connection.Open();
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
DataAdd.ExecuteNonQuery();
//Connection.Close(); no need to close
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You can save one more connection if you store the row returned by RowFind()
string RowFind()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
//Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
So you would connect once instead of twice:
var Row = RowFind();
string NewCode = GenerateCode(Row);
string NewRow = NewRowNum(Row);
string NewSentence = txtSentence.Text;
Declare your connection string variable to a property so you can reuse it:
private string DatabaseConnection {get; set;}
Instead using an instance level SqlConnection you should only provide a common factory for creating a connection:
public partial class frmShop : Form
{
private string ConnectionString
{
get { return WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1; }
}
public frmShop()
{
InitializeComponent();
}
private SqlConnection CreateConnection()
{
var conn = new SqlConnection(ConnectionString);
conn.Open();
return conn;
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
using (var conn = CreateConnection())
{
var BinaryInt = int.Parse(txtBinaryString.Text);
var commandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
using (var Command = new SqlCommand(commandString, conn))
{
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
using (var readSentence = Command.ExecuteReader())
{
while (readSentence.Read())
{
txtSentence.Text = (readSentence["Sentence"].ToString());
Fit = 1;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void InsertData()
{
try
{
using (var conn = CreateConnection())
{
var commandString = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
using (var comm = new SqlCommand(commandString, conn))
{
comm.Parameters.AddWithValue("#NewBinaryString", GenerateCode());
comm.Parameters.AddWithValue("#NewNewSentence", txtSentence.Text);
comm.Parameters.AddWithValue("#NewRowNumber", NewRowNum());
comm.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
using (var conn = CreateConnection())
{
var commandString = "SELECT * FROM ShopSentences";
using (var comm = new SqlCommand(commandString, conn))
{
using (var sda = new SqlDataAdapter(queryString, Connection))
{
using (DataTable dt = new DataTable("ShopSentences"))
{
sda.Fill(dt);
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
}
}
}
string NewRowNum()
{
var Row = RowFind();
var CalcRow = int.Parse(Row) + 1;
return CalcRow.ToString();
}
}
But this is just the beginning you should not have any hard SQL dependency in your Form classes.
When sharing same SqlConnection instance several times in your code, instead of directly opening the you can rather check the connection state first and then open it if not already opened. For example:
if(Connection.State!= ConnectionState.Open)
Connection.Open();

Use ContentEditable to Save Into DB With ASP.NET?

I'm trying to create a web page where a user can edit the text and when they are done, they hit save and the new text entered is saved into the database.
I'm not getting any errors in my code, but for some reason, the old text is just being rewritten into the db instead of the new text.
Here is my code-behind:
protected void saveBtn_Click(object sender, EventArgs e)
{
string newName;
string newIntro;
string newEduc;
string newWork;
h1New.Text = h1.Text;
newName = h1New.Text;
newIntro = intro.Text;
newEduc = educ.Text;
newWork = employ.Text;
string connectionInfo = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionInfo))
{
connection.Open();
SqlCommand myCommand = new SqlCommand("UPDATE simpleContent SET userName = #newName, infoContent = #newIntro, educContent = #newEduc, workContent = #newWork WHERE userID = #userName", connection);
try
{
string username = HttpContext.Current.User.Identity.Name;
myCommand.Parameters.AddWithValue("#userName", username.ToString());
myCommand.Parameters.AddWithValue("#newName", newName.ToString());
myCommand.Parameters.AddWithValue("#newIntro", newIntro.ToString());
myCommand.Parameters.AddWithValue("#newEduc", newEduc.ToString());
myCommand.Parameters.AddWithValue("#newWork", newWork.ToString());
myCommand.ExecuteNonQuery();
connection.Close();
}
catch
{
Response.Redirect("http://www.google.co.uk");
}
}
}
I would appreciate any pointers that you may have.
try to put you code in format:
protected void saveBtn_Click(object sender, EventArgs e)
{
// add variables
string connectionInfo = (...)
string commandText = (...)
using (...){
SqlCommand myCommand = (...)
// add parameters
try
{
connection.Open();
myCommand.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
(...)
}
}

How to retrieve the value of first index through ComboBox in C#.Net?

I kept getting "FormatException was unhandled by user Code"
Following is the Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Eventmanagement
{
public partial class Registration : Form
{
SqlConnection aConnection;
string firstname= string.Empty;
string lastname= string.Empty;
int aid;
string date = DateTime.Now.ToShortDateString();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dta;
public Registration(string fname, string lname, int attID)
{
this.firstname = fname;
this.lastname = lname;
this.aid = attID;
InitializeComponent();
}
//--------------------------------------------//
private void Registration_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'insertEventDataSet.Events' table. You can move, or remove it, as needed.
populateEventSalesPersonList();
populateEventNameIdTypeList();
//+++++++++++++++++++++++++++++++++++++++++++//
txtSalesTaxRate_Registration.Text = Convert.ToString( SalesTaxRate());
txtRegistrationID_Registration.Text = regID().ToString();
//+++++++++++++++++++++++++++++++++++++++++++//
//+++++++++++++++++++++++++++++++++++++++++++//
txtAttendee_Registration.Text = (this.firstname+" "+this.lastname);
txtRegistrationDate_Registration.Text = date.ToString();
}
//--------------------------------------------//
public string getConnectionString()
{
try
{
string sConnection = "";
// Get the mapped configuration file.
System.Configuration.ConnectionStringSettingsCollection ConnSettings = ConfigurationManager.ConnectionStrings;
sConnection = ConnSettings["DBConnectionString"].ToString();
return sConnection;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return "";
}
}
//--------------------------------------------//
public void populateEventNameIdTypeList()
{
try
{
cmbEvent_Registration.DataSource = getDataTable4();
//----------------------------
cmbEvent_Registration.ValueMember = "EventID";
cmbEvent_Registration.DisplayMember = "EventName";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//--------------------------------------------//
public void populateEventSalesPersonList()
{
try
{
cmbSalesPerson_Registration.DataSource = getDataTable5();
cmbSalesPerson_Registration.ValueMember = "EmployeeID";
cmbSalesPerson_Registration.DisplayMember = "SalesPerson";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//-------------------------------------------//
public void populateFeeScheduleByEventList()
{
try
{
cmbFeeSchedule_Registration.DataSource = getDataTable6();
cmbFeeSchedule_Registration.ValueMember = "FeeScheduleID";
cmbFeeSchedule_Registration.DisplayMember = "Fee";
//--------------------------------------------------//
//saleTax();
//txtSalesTax_Registration.Text = Convert.ToString(saleTax());
//txtTotalCharges_Registration.Text = Convert.ToString(totalCharges());
//txtAmountDue_Registration.Text = Convert.ToString(amountDue());
//--------------------------------------------------//
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//------------------------------------------//
//------------------------------------------//
private void btnclose_Registration_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnInsert_Registration_Click(object sender, EventArgs e)
{
try
{
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
//Calling the Stored Procedure
da.InsertCommand = new SqlCommand("RegistrationInsert", aConnection);
da.InsertCommand.CommandType = CommandType.StoredProcedure;
//da.InsertCommand.Parameters.Add(#"RegistrationID", SqlDbType.Int).Value = Convert.ToInt16( txtRegistrationID_Registration.Text);
da.InsertCommand.Parameters.Add(#"AttendeeID", SqlDbType.Int).Value = Convert.ToInt16( aid);
da.InsertCommand.Parameters.Add(#"RegistrationDate", SqlDbType.SmallDateTime).Value = Convert.ToDateTime(txtRegistrationDate_Registration.Text=date.ToString());
da.InsertCommand.Parameters.Add(#"PurchaseOrderNumber", SqlDbType.VarChar).Value = txtPoNumber_Registration.Text;
// da.InsertCommand.Parameters.Add(#"SalesPerson", SqlDbType.Int).Value = Convert.ToInt64(cmbSalesPerson_Registration.SelectedValue.ToString());
da.InsertCommand.Parameters.Add(#"EventID", SqlDbType.Int).Value = cmbEvent_Registration.SelectedValue.ToString();
da.InsertCommand.Parameters.Add(#"FeeScheduleID", SqlDbType.Int).Value = cmbFeeSchedule_Registration.SelectedValue.ToString();
da.InsertCommand.Parameters.Add(#"RegistrationFee", SqlDbType.Money).Value = txtRegistrationFee_Registration.Text;
da.InsertCommand.Parameters.Add(#"EmployeeID", SqlDbType.Int).Value = Convert.ToInt16(cmbSalesPerson_Registration.SelectedValue.ToString());
da.InsertCommand.Parameters.Add(#"SalesTaxRate", SqlDbType.Float).Value = txtSalesTaxRate_Registration.Text;
//da.InsertCommand.Parameters.Add(#"EndTime", SqlDbType.SmallDateTime).Value = Convert.ToDateTime(txtEndTime.Text.ToString());
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Inserted successfully!!!");
aConnection.Close();
da.InsertCommand.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//-------------------------------------------//
public DataTable getDataTable4()
{
try
{
dta = new DataTable();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("EventsSelectAll", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
public DataTable getDataTable5()
{
try
{
dta = new DataTable();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("sp_RegistrationSalesPerson", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
dta.Clear();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
public DataTable getDataTable6()
{
try
{
dta = new DataTable();
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da.SelectCommand = new SqlCommand("sp_FeeScheduleSelectAllByEventID", aConnection);
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
private void cmbEvent_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
populateFeeScheduleByEventList();
txtRemainingSeats_Registration.Text = Convert.ToString(spaces());
}
public double saleTax()
{
double regFee = Convert.ToDouble(cmbFeeSchedule_Registration.SelectedText);
double sTR = Convert.ToDouble(SalesTaxRate());
double sr = regFee * (sTR / 100);
return sr;
}
public int totalRegisteredAttendees()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("RegistrationSelectAllByEventID", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
aConnection.Open();
int val = (int)da.SelectCommand.ExecuteScalar();
aConnection.Close();
return val;
}
public int spaces()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("EventsSelect", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
aConnection.Open();
int spaces = Convert.ToInt16(da.SelectCommand.ExecuteScalar());
aConnection.Close();
int value = totalRegisteredAttendees();
int totalspaces = spaces - value;
return totalspaces;
}
public double SalesTaxRate()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("CompanyInfo", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
aConnection.Open();
double sale = Convert.ToDouble(da.SelectCommand.ExecuteScalar());
aConnection.Close();
return sale;
}
public double totalCharges()
{
double tc = Convert.ToDouble(txtRegistrationFee_Registration.Text) + (saleTax());
return tc;
}
public double amountDue()
{
double aD;
if (txtTotalPaid_Registration.Text == string.Empty)
{
aD = Convert.ToDouble(txtTotalCharges_Registration.Text.ToString());
}
else
{
double a = Convert.ToDouble(txtTotalPaid_Registration.Text.ToString());
double b= (Convert.ToDouble(txtTotalCharges_Registration.Text.ToString()));
aD = b-a;
}
return aD;
}
public int regID()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("RegistrationID", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
aConnection.Open();
int id = ((int)da.SelectCommand.ExecuteScalar())+1;
aConnection.Close();
return id;
}
private void cmbFeeSchedule_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
saleTax();
}
//------------------------------------------//
}
}
When I call SaleTax() Method in following
private void cmbFeeSchedule_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
saleTax();
}
I get "FormatException was unhandled by user Code" Error
I debugged the Code and find out that it is happening because cmbFeeSchedule_Registration is not selecting the first index, hence it is giving the error. I am confused what to do?
How I get around this Problem?
Edit:
Well I resolved the issue. It was the problem of in ` public void populateFeeScheduleByEventList()
{
try
{
cmbFeeSchedule_Registration.DataSource = getDataTable6();
cmbFeeSchedule_Registration.ValueMember = "FeeScheduleID";
cmbFeeSchedule_Registration.DisplayMember = "Fee";
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}`
When SaleTax() was called, pointer leaves the DisplayMember and ValueMember. Hence I readjusted the code little bit and placed cmbFeeSchedule_Registration.ValueMember = "FeeScheduleID"; cmbFeeSchedule_Registration.DisplayMember = "Fee"; before
cmbFeeSchedule_Registration.DataSource = getDataTable6(); and it resolved the Problem. :)
If it is required that index 0 be selected in your ComboBox then you need to do some basic checking. In your SelectedIndexChanged EventHandler wire-up, you need to add:
if (cmbFeeSchedule_Registration.SelectedIndex == 0) {
salesTax();
}
Also if the user is able to change the text in the ComboBox, you are not doing any error handling to handle the FormatException that will be caused by Convert.ToDouble when trying to convert a non-double value that is not parsable.
double regFee = Convert.ToDouble(cmbFeeSchedule_Registration.SelectedText);
double sTR = Convert.ToDouble(SalesTaxRate());
Furthermore, you could actually use double.Parse or double.TryParse instead of ConvertTo, which seems more proper. On another note, if the user cannot edit the text in the ComboBox (say you have it set to DropDownList), you should use the SelectedObject or SelectedValue property instead of SelectedText depending if it is DataBound or not.
Bottom line is you need to make sure you are checking that the correct index is selected before calling salesTax() or any operation that will potentially throw an exception, and do error checking to ensure that your values are what they should be. If regFee is anything but a double, because the correct index is not selected, ConvertTo will fail. (Use double.Parse/TryParse instead, anyway)
A tip of advice when posting questions is to only post the affected segment of code, and provide a StackTrace when one is available. It's too difficult to navigate all of your code on here, and using a StackTrace it is easy to break down.
you have to make selectedindex = 0 in your form
Just do this:
if(((ComboBox)sender).SelectedIndex > -1) saleTax();
instead. If you want to select the first item when the form loads, set SelectedIndex in the Load event.

Categories

Resources