Oracle Query is not being executed - c#

I'm trying to retrieve values from an Oracle database using C# WebMethod, ajax and JavaScript, I have another page with exactly all the same functions and methods (using MSSQL Database) and work fine, but now I want to do it with Oracle. This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Oracle.DataAccess.Client;
using System.Data;
using System.Configuration;
/// <summary>
/// Summary description for OracleConexion
/// </summary>
public class OracleConexion
{
OracleConnection conn;
DataTable dt;
OracleDataAdapter da;
OracleDataReader dr;
DataSet ds;
OracleCommand cmd;
public OracleConexion()
{
conn = new OracleConnection("Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = ***.**.**.***)(PORT = ****)))(CONNECT_DATA = (SERVER = DEDICATED)(SID = *****))); User Id = *****; Password = ****;");
}
private void Open()
{
string canConnect;
try
{
conn.Open();
canConnect = "Nice";
}
catch (Exception ex)
{
//Code Updated
canConnect = ex.Message.ToString();
}
Console.Write(canConnect);
}
private void Close()
{
try
{
conn.Close();
}
catch (Exception ex)
{
}
}
public DataTable ConsultarTablas(string opcion)
{
dt = new DataTable();
ds = new DataSet();
string sql = "";
switch (opcion)
{
case "Datos":
sql = "Select Component as Result from BOM_Explosion where TOP_MATERIAL = '-FHN7092A-EF' and ROWNUM <= 5;";
break;
}
try
{
Open();
OracleDataAdapter da = new OracleDataAdapter(sql, conn);
da.Fill(ds);
dt = ds.Tables[0];
}
catch (Exception ex)
{
}
finally
{
Close();
}
return dt;
}
}
And this is my WebMethod
[WebMethod]
public string ObtenerDatosNumeroParte()
{
DataTable dt = new DataTable();
dt = conn.ConsultarTablas("Datos");
Ticket ti;
List<Ticket> lista = new List<Ticket>();
for (int i = 0; i < dt.Rows.Count; i++)
{
ti = new Ticket();
ti.Vs = dt.Rows[i]["Result"].ToString();
lista.Add(ti);
ti = null;
}
JavaScriptSerializer js = new JavaScriptSerializer();
string lineas = js.Serialize(lista);
return lineas;
}
Testing it seems like my code do not execute my query and my List always is null, what I'm doing wrong and what can I do to solve it?
Update
Using my string canConnect I get ORA-6413: Connection not open.

Related

Load data from database to string

I'm trying at the moment to get an information from a database and want to save it in a string, but yeah not sure about how really to do it right.
This is my code, where I open the LoadSql function:
public void LoadData(string KNR, string WNR, String filter)
{
// WHERE
const string sqlTemplate = "SELECT KUNDENAUFTRAGSNR FROM MESSFELD.AUSSTANDSDATEN WHERE FTNR = '" + txt_Barcode_read.Text + "'";
string sql = string.Format(sqlTemplate, filter);
Database cdb = new Database();
// try to connect and cancel on error
if (!cdb.Open("**********", "*********"))
{
SetStatusText("Datenbank ist nicht verfügbar.");
return;
}
WNR = cdb.LoadSql(sql);
cdb.Close();
}
And here is the LoadSQL function:
public DataTable LoadSql(string sql)
{
try
{
OracleCommand command = new OracleCommand(sql, _con);
command.InitialLONGFetchSize = -1;
OracleDataReader rdr = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
return dt;
}
catch
{
return null;
}
}
For the moment the LoadSQL is saving in datatable, how to change for saving the number in the string WNR?
You can re-write your LoadSQL function to something like this :
public string LoadSql(string sql)
{
try
{
OracleCommand command = new OracleCommand(sql, _con);
command.InitialLONGFetchSize = -1;
OracleDataReader rdr = command.ExecuteReader();
rdr.Read();
if(rdr.HasRows)
return rdr.GetString(0);
else
return "";
}
catch
{
return null;
}
}

System index out range exception C#

I have the following code:
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimeClock
{
class Company
{
DataTable rows = new DataTable();
public Company()
{
MySqlConnection connection = null;
try
{
string connectionString = TimeClock.Properties.Settings.Default.timeclockConnectionString;
connection = new MySqlConnection(connectionString);
connection.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM companies WHERE ID = #ID LIMIT 1", connection);
command.Parameters.AddWithValue("#ID", TimeClock.Properties.Settings.Default.CompanyID);
MySqlDataAdapter da = new MySqlDataAdapter(command);
da.Fill(rows);
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
Console.WriteLine(ex);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
public String getName()
{
DataRow row = rows.Rows[0];
return row["company_name"].ToString();
}
}
}
I know why I'm getting this error: say that no records were found in the database, the of course row[0] will no exist, hence the exception. But how do I deal with when there are no records to store in the Datatable? By the way, I'm quite new to C# and any input would be great; feel free to criticize.
Before you access a collection
DataRow row = rows.Rows[0];
you'll have to make sure that the item exists:
if(rows.Count > 0)
DataRow row = rows.Rows[0];
always
You must change getName function.
public String getName()
{
if (rows.Rows != null && rows.Rows.Count > 0)
{
DataRow row = rows.Rows[0];
return row["company_name"].ToString();
}
return string.Empty;
}
To read data from SQL I'm doing it like so:
using (SqlCommand SelectCommand = new SqlCommand(strbSelect.ToString()))
{
SelectCommand.Parameters.AddWithValue("Asset", AssetNumber);
SelectCommand.Parameters.AddWithValue("Subnumber", Subnumber);
SelectCommand.Connection = new SqlConnection(GetConnectionString());
SelectCommand.Connection.Open();
using (SqlDataReader Reader = SelectCommand.ExecuteReader())
{
if (Reader.HasRows)
{
while (Reader.Read())
{
if (Reader[0] != DBNull.Value)
{
ReturnValue = Reader.GetBoolean(0);
}
}
}
else
return false;
}
SelectCommand.Connection.Close();
}
StrbSelect is a StringBuilder.

I have aproblem with windows service

i have a problem with my windows service program
i try to create a windows service to read data from a database and insert them into an other database but when i read data from first db and copy it into a dataset i have a problem, i can't read those data from data set and insert it into an other dataset to insert it into the other database
here's my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Data.SqlClient;
using System.Collections;
using System.Data.Sql;
namespace WindowSeriveDemo
{
public partial class Service1 : ServiceBase
{
string connection = #"Data Source=DEVELOPER-PC\DEVELOPER;Initial Catalog=NMSys;User ID=sa;Password=2649940931";
string connection2 = #"Data Source=DEVELOPER-PC\DEVELOPER;Initial Catalog=Dpardazesh;User ID=sa;Password=2649940931";
private Timer ServiceTimer = new Timer();
private int inProcess = 0;
public const string SP_dataRead = "usp_Read_Data_From_DpardazeshDB";
public const string SP_insertData = "usp_Write_Data_Into_NMSysDB";
private IEnumerable<DataRow> item;
//Timer timer1 = new Timer();
public Service1()
{
InitializeComponent();
setupTimer();
}
protected override void OnStart(string[] args)
{
//ServiceTimer.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
}
private void setupTimer()
{
ServiceTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
ServiceTimer.Interval = 10000;
ServiceTimer.Enabled = true;
ServiceTimer.Start();
}
protected override void OnStop()
{
//timer1.Enabled = false;
}
private void SyncDatabases()
{
inProcess = 1;
SqlConnection conn2 = new SqlConnection(connection2);
try
{
conn2.Open();
SqlCommand cmd = new SqlCommand(SP_dataRead);
winservDS dataSet = new winservDS();
cmd.CommandType = CommandType.StoredProcedure;
//AddParameter(cmd);
SqlDataAdapter adapter = new SqlDataAdapter(SP_dataRead, conn2);
adapter.Fill(dataSet, dataSet.usp_Read_Data_From_DpardazeshDB.TableName);
dataSet.AcceptChanges();
return ;
}
catch (Exception ex)
{
string text = ex.Message;
}
inProcess = 0;
}
private static SqlCommand cmdGetIdentity;
public winservDS InsertUsers(IDictionary ids)
{
inProcess = 1;
SqlConnection conn = new SqlConnection(connection);
SqlConnection conn2 = new SqlConnection(connection2);
conn.Open();
conn2.Open();
winservDS updates = new winservDS();
DataRow dr;
dr = updates.usp_Read_Data_From_DpardazeshDB.NewRow();
foreach (DictionaryEntry i in ids)
{
if (i.Value == null)
dr[i.Key.ToString()] = DBNull.Value;
else
dr[i.Key.ToString()] = i.Value;
}
updates.usp_Read_Data_From_DpardazeshDB.Rows.Add(dr);
try
{
winservDS.usp_Read_Data_From_DpardazeshDBDataTable tbl = updates.usp_Read_Data_From_DpardazeshDB;
//Create the adapter initial
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.InsertCommand = WriteDatabase(conn);
//Roll Back the changes if some one error have
dataAdapter.ContinueUpdateOnError = false;
cmdGetIdentity = new SqlCommand("SELECT ##IDENTITY", conn);
dataAdapter.RowUpdated += new SqlRowUpdatedEventHandler(HandleRowUpdated);
dataAdapter.Update(tbl.Select("", "", DataViewRowState.Added));
return updates;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
inProcess = 0;
}
private static void HandleRowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
if ((e.Status == UpdateStatus.Continue) && (e.StatementType == StatementType.Insert))
{
e.Row["id"] = Convert.ToInt32 (cmdGetIdentity.ExecuteScalar());
e.Row.AcceptChanges();
}
}
private static SqlCommand WriteDatabase(SqlConnection conn)
{
SqlCommand cmd = new SqlCommand(SP_insertData);
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
SqlParameterCollection pc = cmd.Parameters;
pc.Add(CreateParameter("#fHitType", System.Data.SqlDbType.Int));
pc.Add(CreateParameter("#DateOfHit", System.Data.SqlDbType.DateTime));
pc.Add(CreateParameter("#TimeOfHit", System.Data.SqlDbType.Int));
pc.Add(CreateParameter("#fEmpid", System.Data.SqlDbType.Int));
cmd.ExecuteNonQuery();
return cmd;
}
private static SqlParameter CreateParameter(string p, SqlDbType sqlDbType)
{
SqlParameter parameter = new SqlParameter("#" + p, sqlDbType);
parameter.SourceColumn = p;
return parameter;
}
private void ServiceTimer_Tick(object sender, EventArgs e)
{
if (inProcess == 0)
{
ServiceTimer.Stop();
SyncDatabases();
CopyData();
//InsertUsers(ids);
ServiceTimer.Start();
}
}
private void CopyData()
{
DataSet ds1 = new winservDS();
DataSet ds2 = new In_Out_RecordsDS();
foreach (DataRow item in ds1.Tables[0].Rows)
{
ds2.Tables[0].Rows.Add(item);
}
} here
Try to use a DataReader for the source recordsets, read all columns into variables and then insert them into second database with an INSERT Statement. Be avoid of your transaction log when copying thousands of records...

How to call Java stored procedure with C# in CUBRID database

I am using the following code to consume a CUBRID database java stored procedure.
string ConnectionString = "server=localhost;database=demodb;port=30000;user=dba;password=123456";
DataTable dt = new DataTable();
DataSet ds = new DataSet();
CUBRIDConnection con = new CUBRIDConnection(ConnectionString);
CUBRIDCommand com = new CUBRIDCommand();
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.CommandText = "select rset()";
CUBRIDParameter pan = new CUBRIDParameter();
pan.Direction = ParameterDirection.Output;
pan.CUBRIDDataType = CUBRIDDataType.CCI_U_TYPE_RESULTSET;
pan.ParameterName = "?p1";
CUBRIDDataAdapter dap = new CUBRIDDataAdapter(com);
con.Open();
int val = dap.Fill(ds);
con.Close();
and in the server use the next function and stored procedure in the server
public class JavaSP3 {
public static ResultSet TResultSet(){
try {
Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
Connection con = DriverManager.getConnection("jdbc:default:connection:");
String sql = "select * from athlete";
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
((CUBRIDResultSet)rs).setReturnable();
return rs;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
and the function code is this
CREATE FUNCTION "rset"() RETURN CURSOR
AS LANGUAGE JAVA
NAME 'JavaSP3.TResultSet() return cubrid.jdbc.driver.CUBRIDResultSet'
I run this with a function that result a string and return the value, but when I change to CUBRIDResultSet value dont work and CUBRID says>
execute error:-911
line 1 is not executed (error)
Error description:
Invalid call: it can not return ResultSet.
Please, I have 3 days trying to solve this any one can help me?
ADO.NET dont provide support for ResultSet.
http://www.cubrid.org/?mid=forum&category=195532&document_srl=358924
using System.Data;
using CUBRID.Data.CUBRIDClient;
using System.Data.Common;
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string ConnectionString = "server=localhost;database=demodb;port=30000;user=dba;password=123456";
DataTable dt = new DataTable();
DataSet ds = new DataSet();
CUBRIDConnection con = new CUBRIDConnection(ConnectionString);
CUBRIDCommand com = new CUBRIDCommand();
com.CommandType = CommandType.Text; //Important ADO.NET driver crash using call convention
com.Connection = con;
com.CommandText = "select rset();";
CUBRIDParameter pan = new CUBRIDParameter();
con.Open();
DbDataReader reader = com.ExecuteReader();
CustomAdapter da = new CustomAdapter();
da.FillFromReader(dt, reader);
con.Close();
DataRow fila = dt.Rows[0];
Console.WriteLine(fila[0].ToString());
Console.ReadKey();
}
}
public class CustomAdapter : System.Data.Common.DbDataAdapter
{
public int FillFromReader(DataTable dataTable, IDataReader dataReader)
{
return this.Fill(dataTable, dataReader);
}
protected override System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow a, IDbCommand b, StatementType c, System.Data.Common.DataTableMapping d)
{
return (System.Data.Common.RowUpdatedEventArgs)new EventArgs();
}
protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow a, IDbCommand b, StatementType c, System.Data.Common.DataTableMapping d)
{
return (System.Data.Common.RowUpdatingEventArgs)new EventArgs();
}
protected override void OnRowUpdated(System.Data.Common.RowUpdatedEventArgs value)
{
}
protected override void OnRowUpdating(System.Data.Common.RowUpdatingEventArgs value)
{
}
}
java class
import java.sql.*;
import cubrid.jdbc.driver.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class JavaSP3 {
public static String TResultSet(){
ResultSet rs = null;
Statement stmt = null;
String sql;
try {
Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
Connection con = DriverManager.getConnection("jdbc:default:connection:");
((CUBRIDConnection)con).setCharset("euc_kr");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder =factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
sql = "select * from athlete";
stmt=con.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
while (rs.next()) {
Element row = doc.createElement("Row");
results.appendChild(row);
for (int ii = 1; ii <= colCount; ii++) {
String columnName = rsmd.getColumnName(ii);
Object value = rs.getObject(ii);
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(value.toString()));
row.appendChild(node);
}
}
String valor = getDocumentAsXml(doc);
return valor;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static String getDocumentAsXml(Document doc)
throws TransformerConfigurationException, TransformerException {
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
transformer.setOutputProperty
("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
java.io.StringWriter sw = new java.io.StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}
}
Cubrid function
CREATE FUNCTION "rset"() RETURN STRING
AS LANGUAGE JAVA
NAME 'JavaSP3.TResultSet() return java.lang.String'
This allow you get data from Java stored procedures in CUBRID using ADO.NET

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