Login.aspx
protected void btnLogin_Click(object sender, EventArgs e)
{
String tbNRIC = txtLogUsername.Text.ToString();
String tbPassword = txtLogPassword.Text.ToString();
PatientDAO fmTd = new PatientDAO();
fmTd.getPatientByNricPassword(tbNRIC, tbPassword);
if(?? > 0)
{
Response.Redirect("Home.aspx");
}
else
{
}
}
How to i response.redirect after checking if username and password match?
PatientDAO.cs
public int getPatientByNricPassword(String tbNRIC, String tbPassword)
{
string DBConnect = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlDataAdapter da;
DataSet ds = new DataSet();
Patient mypatient = new Patient();
StringBuilder sqlStr = new StringBuilder();
int result = 0;
sqlStr.AppendLine("Select * from Login where");
sqlStr.AppendLine("tbNRIC = #paratbNRIC AND tbPassword = #paratbPassword");
try
{
SqlConnection myConn = new SqlConnection(DBConnect);
da = new SqlDataAdapter(sqlStr.ToString(), myConn);
da.SelectCommand.Parameters.AddWithValue("#paratbNRIC", tbNRIC);
da.SelectCommand.Parameters.AddWithValue("#paratbPassword", tbPassword);
DataTable dt = new DataTable();
da.Fill(dt);
}
catch (SqlException ex)
{
logManager log = new logManager();
log.addLog("PatientDAO.getPatientByNricPassword", sqlStr.ToString(), ex);
mypatient = null;
}
return result;
}
How do i pass the result to Login.aspx?
Patient.cs
public class Patient
{
public string tbNRIC { get; set; }
public string tbPassword { get; set; }
}
How to check from PatientDAO to see if Username and Password Match and Login.aspx Response.Redirect.
There are some issues with the code I can see.
First in method getPatientByNricPassword it seems you are returning result variable, but this has not been assigned. Probably you want to return the count of records in that case.
Second, you have not initialized PatientDAO fmTd = new PatientDAO(); with the credential details.
Initialize the values appropriately -
PatientDAO fmTd = new PatientDAO();
fmTd.tbNRIC = tbNRIC; // which is txtLogUsername.Text
fmTd.tbPassword = tbPassword ; //which is txtLogPassword.Text
Note that you do not need to put ToString() as text property is already string.
Third, you should have variable for example recordCount to store result of dal method, which you can further check in if condition like this -
var recordCount = fmTd.getPatientByNricPassword(tbNRIC, tbPassword);
if(recordCount > 0)
{
Response.Redirect("Home.aspx");
}
Related
I'm trying to get all data from an SQL table and store it in a List using the C# programming language.
the SQL statement I'm using is:
private string cmdShowEmployees = "SELECT * FROM Employees;";
This is being used in the same class as a function
public List<string> showAllIdData()
{
List<string> id = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
id.Add(reader[0].ToString());
}
return id;
}
}
and here
public List<string> showAllActiveData()
{
List<string> active = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
active.Add(reader[1].ToString());
}
return active;
}
I would have to create 9 more functions this way in order to get all the data out of the Employees table. This seems very inefficient and I was wondering if there was a more elegant way to do this.
I know using an adapter is one way to do it but I don't think it is possible to convert a filled adapter to a list, list list etc.
SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";
Any ideas?
If you must use the reader in this way, why not create an object which holds the table row data.
public class SomeComplexItem
{
public string SomeColumnValue { get; set;}
public string SomeColumnValue2 { get; set;}
public string SomeColumnValue3 { get; set;}
public string SomeColumnValue4 { get; set;}
}
That way you can loop through with your reader as follows:
public List<SomeComplexItem> showAllActiveData()
{
List<SomeComplexItem> active = new List<SomeComplexItem>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
var someComplexItem = new SomeComplexItem();
someComplexItem.SomeColumnValue = reader[1].ToString();
someComplexItem.SomeColumnValue2 = reader[2].ToString();
someComplexItem.SomeColumnValue3 = reader[3].ToString();
active.Add(someComplexItem);
}
return active;
}
You could use two select statements to populate two List<string> as shown in the example below where the key between reads is reader.NextResult();.
The database used is the standard Microsoft NorthWind database.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace SQL_Server_TwoList
{
public class DataOperations
{
public List<string> Titles { get; set; }
public List<string> Names { get; set; }
/// <summary>
/// Trigger code to load two list above
/// </summary>
public DataOperations()
{
Titles = new List<string>();
Names = new List<string>();
}
public bool LoadData()
{
try
{
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
string commandText = #"
SELECT [TitleOfCourtesy] + ' ' + [LastName] + ' ' + [FirstName] As FullName FROM [NORTHWND.MDF].[dbo].[Employees];
SELECT DISTINCT [Title] FROM [NORTHWND.MDF].[dbo].[Employees];";
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Names.Add(reader.GetString(0));
}
// move on to second select
reader.NextResult();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Titles.Add(reader.GetString(0));
}
}
}
}
}
return true;
}
catch (Exception)
{
return false;
}
}
}
}
Form code
namespace SQL_Server_TwoList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataOperations dataOps = new DataOperations();
if (dataOps.LoadData())
{
listBox1.DataSource = dataOps.Names;
listBox2.DataSource = dataOps.Titles;
}
}
}
}
You could always add it all to a dataset or datatable instead of looping through using datareader to add to an array, dataset allows you to access data in similar way to array anyway.
Connstr = "Data Source = " + SelectedIP + "; Initial Catalog = " + dbName + "; User ID = " + txtUsername.Text +"; Password = "+ txtPassword.Text +"";
conn = new SqlConnection(Connstr);
try
{
string contents = "SELECT * FROM ..."
conn.Open();
SqlDataAdapter da_1 = new SqlDataAdapter(contents, conn); //create command using contents of sql file
da_1.SelectCommand.CommandTimeout = 120; //set timeout in seconds
DataSet ds_1 = new DataSet(); //create dataset to hold any errors that are rturned from the database
try
{
//manipulate database
da_1.Fill(ds_1);
if (ds_1.Tables[0].Rows.Count > 0) //loop through all rows of dataset
{
for (int i = 0; i < ds_1.Tables[0].Rows.Count; i++)
{
//rows[rownumber][column number/ "columnName"]
Console.Write(ds_1.Tables[0].Rows[i][0].ToString() + " ");
}
}
}
catch(Exception err)
{}
conn.Close();
}
catch(Exception ex)
{}
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();
Im trying to create a login form for a website using ms access database. I'm using visual studio 2010 c# and access 2013. For some reason I can't get it to log in. I'm really new to this so any help is appreciated.
DataLayer:
public class DataConnector
{
protected OleDbDataAdapter DataAdapter1 = new OleDbDataAdapter();
public string ErrorMessage = "";
public DataConnector(string ConnectionString)
{
OleDbConnection Connection1 = new OleDbConnection(ConnectionString);
this.DataAdapter1.SelectCommand = new OleDbCommand("", Connection1);
this.DataAdapter1.InsertCommand = new OleDbCommand("", Connection1);
}
public DataTable DataSelect(string query)
{
DataTable dt = new DataTable();
try
{
DataAdapter1.SelectCommand.CommandText = query;
DataAdapter1.SelectCommand.Connection.Open();
DataAdapter1.Fill(dt);
DataAdapter1.SelectCommand.Connection.Close();
ErrorMessage = "";
}
catch(Exception err)
{
ErrorMessage = err.Message;
DataAdapter1.SelectCommand.Connection.Close();
}
return dt;
}
public int DataInsert(string query)
{
int Result = 0;
try
{
DataAdapter1.InsertCommand.CommandText = query;
DataAdapter1.InsertCommand.Connection.Open();
Result = DataAdapter1.InsertCommand.ExecuteNonQuery();
DataAdapter1.InsertCommand.Connection.Close();
ErrorMessage = "";
return Result;
}
catch (Exception err)
{
ErrorMessage = err.Message;
DataAdapter1.InsertCommand.Connection.Close();
return 0;
}
}
public int DataUpdate(string query)
{
return DataInsert(query);
}
public int DataDelete(string query)
{
return DataInsert(query);
}
}
Default.aspx.cs:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
DataLayer.DataConnector dat = new DataLayer.DataConnector("Provider=Microsoft.ACE.OLEDB.12.O;"+"Data Source='"+Server.MapPath("site_database.accdb")+"'; Persist Security Info=False;");
DataTable dt = dat.DataSelect("select UserID from tbl_login where Username = '" + txtUsername.Text + "' and Password = '"+ txtPassword.Text +"' ");
if (dt.Rows.Count > 0)
{
Response.Redirect("members_area.aspx");
}
else
lblerror.Text = "Login failed";
}
}
I'm not getting any errors and I just can't figure it out. When I try to log in it just stays on the default.aspx page.
Part of the problem could very well be that PASSWORD is a reserved word in Access SQL, so if you want to use it as a field name in a query you should surround it in square brackets, e.g.
... WHERE Username = ... AND [Password] = ...
Note also that you really should be using a parameterized query in case Little Bobby Tables tries to log in.
So I've been working on learning LINQ, and I think I'm doing this correctly, but when I spit out the value of the DropDownList's DataValueField property, it comes back as the string "mId" rather than the actual value (the menu_id). Even more strange, the DataTextField is being populated correctly, using the same syntax. Anyone have any ideas?
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
List<RobDAL.Menu.menuObj> menuInfo = new List<RobDAL.Menu.menuObj>();
menuInfo = RobDAL.Menu.GetMenuText();
menu.DataSource = from myMenu in menuInfo
select new { Text = myMenu.menuText,
mId = myMenu.menuId };
menu.DataValueField = "mId";
menu.DataTextField = "Text";
menu.DataBind();
}
Here's my Menu class:
public class Menu
{
public static int GetMainMenuByContentId(int contentid)
{
//SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo);
Content myContent = new Content();
int menuid;
string queryString = "SELECT menu_id FROM menu_to_item_tbl where content_id = " + contentid + ";";
using (SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
try
{
menuid = (int)command.ExecuteScalar();
}
finally
{
// Always call Close when done reading.
connection.Close();
}
return menuid;
}
}
public static List<menuObj> GetMenuText()
{
//SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo);
List<menuObj> allMenus = new List<menuObj>();
string queryString = "SELECT DISTINCT menu_id, menu_title FROM menu_to_item_tbl;";
using (SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
menuObj myMenu = new menuObj();
myMenu.menuId = Convert.ToInt16(reader[0]);
myMenu.menuText = reader[1].ToString();
allMenus.Add(myMenu);
}
}
finally
{
reader.Close();
}
return allMenus;
}
}
public class menuObj
{
public string menuText { get; set; }
public int menuId { get; set; }
}
}
Thanks!
Change
menu.DataSource = from myMenu in menuInfo
select new { Text = myMenu.menuText,
mId = myMenu.menuId };
to
menu.DataSource = (from myMenu in menuInfo
select new { Text = myMenu.menuText,
mId = myMenu.menuId }).ToList();;
That is because you have assigned a string to the DataValue property of your drop down list.
menu.DataValueField = "mId".
You might also want to check to see what your linq query is returning for mId.
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.