button send parameter to the method - c#

Hi I have some method which send me data from sql table and I want that - when I click button in datagridview - that send parameter to the method and parameter will have ID value(like on picture 107 or 106). Below on the picture is datagridview with 2 buttons and ID column.
public ObservableCollection<MyClass> ReadUpdate(int id_update)
{
ObservableCollection<MyClass> result = new ObservableCollection<MyClass>();
string nwConn = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlDataReader dr;
SqlConnection conn = new SqlConnection(nwConn);
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.CommandText = "Insert_Update";
cmd.Parameters.AddWithValue("#id_update", id_update);
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
MyClass lin = new MyClass();
lin.id = dr.GetInt32(1);
if (!dr.IsDBNull(2)) lin.other = dr.GetString(2);
if (!dr.IsDBNull(3)) lin.barkod = dr.GetString(3);
if (!dr.IsDBNull(4)) lin.pw = dr.GetInt32(4);
result.Add(lin);
}
dr.Close();
return result;
}
catch (SqlException e)
{
MyClass lin = new MyClass();
lin.other = e.Message;
result.Add(lin);
return result;
}
finally
{
conn.Close();
};
}
My class:
public class PIS
{
public int ID { get; set; }
}
And my button:
private void btnUpdate_Click(object sender, System.Windows.RoutedEventArgs e)
{
pis_update = (PIS)((Button)sender).DataContext;
ChildWindow_Update childWindow_update = new ChildWindow_Update();
childWindow_update.DataContext = ((Pismo)((Button)sender).DataContext).Id_Pismo;
childWindow_update.Closed += ChildWindow_Update_Closed;
childWindow_update.Show();
}
public ChildWindow_Update()
{
InitializeComponent();
ServiceReference1.Service1Client webService = new ServiceReference1.Service1Client();
webService.ReadUpdateAsync((int)this.DataContext);
webService.ReadUpdateCompleted += WebService_ReadUpdateCompleted;
private void WebService_ReadUpdateCompleted(object sender, ServiceReference1.ReadUpdateCompletedEventArgs e)
{
if (e.Result != null)
{
//do something
}
}
I have error in webService.ReadUpdateAsync((int)this.DataContext);
"Null REference Exception".

At the time of your constructor call, your DataContext has not been set yet. You should make the id a constructor parameter if you need it in the constructor.
Generally speaking, you should use MVVM and the command pattern, where you can specify your id data as the command parameter in your XAML.

Related

Fill List box with result from stored procedure C#

I have search a bunch for this and as you can tell I'm very new to C#, I I'm trying to learn this language.
So please forgive me if one of the 100 forms that I have looked at says the same thing that you post here.
I am trying to populate a list box with a the results from a stored procedure called LookupInvoices, this requires a parameter #InvoiceNumber that is an int.
I have a WPF that I would like to populate a listbox called lstResults with the results from this stored procedure.
Please look at my code and tell me where I have made an error, thanks so much for your time!
private void btnFill_Click(object sender, RoutedEventArgs e)
{
if (cmbInvoiceNumbers.SelectedItem == null)
{
System.Windows.MessageBox.Show("Please Choose A Invoice Number!");
return;
}
SqlConnection cs = new SqlConnection("Data Source=JAMES-DESKTOP\\SQLEXPRESS;Initial Catalog=contacts;Integrated Security=True");
int cboItemNumber = cmbInvoiceNumbers.SelectedIndex;
int invNumber = Convert.ToInt32(cmbInvoiceNumbers.Items[cboItemNumber].ToString());
cs.Open();
SqlCommand cmd = new SqlCommand("LookupInvoices", cs);
using (SqlDataReader reader = cmd.ExecuteReader())
{
SqlParameter pram = new SqlParameter("#invoiceNumber", invNumber);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(pram);
cmd.Connection = cs;
reader.Read();
}
cs.Close();
}
Please not that when I click the button it crashes. This doesn't run all the way through.
You should put your all disposable elements (SqlConnection, SqlCommand, SqlDataReader) into using (....) { ...... } blocks, and you need to add the parameter before calling .ExecuteReader() - try this code:
public class InvoiceDto
{
public string Description { get; set; }
public int Hours { get; set; }
public decimal Amount { get; set; }
}
public void List<InvoiceDto> GetInvoiceData(int invoiceNumber)
{
List<InvoiceDto> data = new List<InvoiceData>();
using (SqlConnection cs = new SqlConnection("Data Source=JAMES-DESKTOP\\SQLEXPRESS;Initial Catalog=contacts;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand("dbo.LookupInvoices", cs))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#invoiceNumber", SqlDbType.Int).Value = invoiceNumber;
cs.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
InvoiceDto dto = new InvoiceDto();
dto.Description = reader.GetFieldValue<string>(0);
dto.Hours = reader.GetFieldValue<int>(1);
dto.Amount = reader.GetFieldValue<decimal>(2);
data.Add(dto);
}
}
cs.Close();
}
return data;
}
and in your code-behind, you should call this method in your event handler
private void btnFill_Click(object sender, RoutedEventArgs e)
{
// get selected invoice number
int cboItemNumber = cmbInvoiceNumbers.SelectedIndex;
int invNumber = Convert.ToInt32(cmbInvoiceNumbers.Items[cboItemNumber].ToString());
// call method to get the data from the stored procedure
List<InvoiceDto> data = GetInvoiceData(invNumber);
// loop over the data and fill your listbox
foreach(InvoiceDto dto in data)
{
listbox.Items.Add(dto.Description);
}
}

BeginExecuteReader, EndExecuteReader and multiple results

I have method that is asynchronously getting results form my database:
internal class CommandAndCallback<TCallback, TError>
{
public SqlCommand Sql { get; set; }
public TCallback Callback { get; set; }
public TError Error { get; set; }
}
public void GetResults(string param, Action<DataTable,DataTable> callback, Action<string> error, Action<string> info)
{
var conn = new SqlConnection(_connString);
conn.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e)
{
if (e.Errors.Count <= 0) return;
foreach (SqlError message in e.Errors)
{
info(message.State + " " + message.Message);
}
};
SqlCommand cmd = conn.CreateCommand();
cmd.CommandTimeout = 0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = #"GetData";
cmd.Parameters.Add("#param", SqlDbType.NVarChar).Value = param;
try
{
cmd.Connection.Open();
}
catch (Exception ex)
{
error(ex.ToString());
return;
}
var ar = new CommandAndCallback<Action<DataTable,DataTable>, Action<string>> { Callback = callback, Error = error, Sql = cmd };
cmd.BeginExecuteReader(Krok2_Handler, ar, CommandBehavior.CloseConnection);
}
private static void Krok2_Handler(IAsyncResult result)
{
var ar = (CommandAndCallback<Action<DataTable,DataTable>, Action<string>>)result.AsyncState;
if (result.IsCompleted)
{
try
{
SqlDataReader dr = ar.Sql.EndExecuteReader(result);
var dt1 = new DataTable();
var dt2 = new DataTable();
dt1.Load(dr);
if (dr.NextResult())//I can't access second table in results
{
dt2.Load(dr);
}
dr.Close();
ar.Callback(dt1,dt2);
}
catch (Exception ex)
{
ar.Error(ex.Message);
}
}
else
{
ar.Error("Error calling SQL");
}
}
And I call it like this:
GetResults("Param value, Success, Error, Info);
Everything works fine when my procedure is returning single results, but when I add second select my data reader isn't getting them, probably because when I call EndExecuteReader connection is closing.
How can I modify my code to support multiple results so I can pass them to my callback method?
I have tested this and I think the problem is here:
dt1.Load(dr);
if (dr.NextResult())//I can't access second table in results
{
dt2.Load(dr);
}
From what I can see the the call to Load automatically advances the SqlDataReader to the next record set, so your call to dr.NextResult() will return false.
If you just do this, I think you'll find it works, it did for me:
dt1.Load(dr);
dt2.Load(dr);
EDIT:
I just checked the source of DataTable.Load and it does call the NextResult method for you:
if (!reader.IsClosed && !reader.NextResult())
{
reader.Close();
}
EDIT2
When looping SqlDataReader you should use this:
if (result.IsCompleted)
{
try
{
List<string> table1 = new List<string>();
List<string> table2 = new List<string>();
SqlDataReader dr = ar.Sql.EndExecuteReader(result);
while (dr.Read())
{
table1.Add(dr[0].ToString());//get data from first table
}
if (dr.NextResult())//second table
{
while (dr.Read())
{
table2.Add(dr[0].ToString()); //get data from second table
}
}
dr.Close();
ar.Callback(table1 ,table2);
}
catch (Exception ex)
{
ar.Error(ex.Message);
}
}

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();

Why is this ignoring the where clause?

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

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