I'm working on a quote manager for my boss at work and I'm having some issues. This is a WPF C# application and it's the first time I've ever built anything that works with a SQL Server database. I'm currently having three issues.
Background:
When the user opens the application they're greeted with a DataGrid, a new quote button and several other controls that I haven't yet created. When they press the new quote button a new window pops up with a form that will have text boxes for things like Customer Name, quantity, etc. At the bottom of that form is a submit button, at which point the window will close and the information they added will be inserted into the DataGrid as a new row.
Problem One:
One of the fields in my database is called Open_Quote and it is supposed to be hold the date we received the order. This is handled programmatically and is what my first question involves. I'll include all of the code at the bottom of this post, but when the user hits submit I receive the following error: "Conversion failed when converting date and/or time from character string."
Problem Two:
In an attempt to test the rest of my code and go back later to fix the date issue, I commented that code out and tried running my program again. This time I get a different error: "Incorrect syntax around 'newQuote.Qty'."
Problem Three:
Again, commenting that code out in order to finally test the rest of my code, I received a third error: "string or binary data would be truncated. This process has been terminated."
My hope is that there's one piece of code that's causing all three of these issues, but I could be completely off there. I've been pulling my hair out for over a day trying to figure this out. Anyway, here's the code:
newQuote.xaml.cs:
private void SubmitQuotebtn_Click(object sender, RoutedEventArgs e)
{
CustomerData newQuote = new CustomerData();
int quantity;
quantity = Convert.ToInt32(Qtytxt.Text);
string theDate = System.DateTime.Today.Date.ToString("d");
newQuote.OpenQuote = theDate;
newQuote.CustomerName = CustNametxt.Text;
newQuote.OEMName = OemNametxt.Text;
newQuote.Qty = quantity;
newQuote.QuoteNumber = QuoteNumtxt.Text;
newQuote.FdNumber = FabDrawingNumtxt.Text;
newQuote.RfqNumber = RfqNumtxt.Text;
newQuote.RevNumber = RevNumtxt.Text;
try
{
string insertConString = Sqtm.Properties.Settings.Default.SqtmDbConnectionString;
using (SqlConnection insertConnection = new SqlConnection(insertConString))
{
insertConnection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO General_Info(Open_Quote, Customer_Name, OEM_Name, Qty, Quote_Num, Fab_Drawing_Num, "
+ "Rfq_Num, Rev_Num) values('newQuote.OpenQuote', 'newQuote.CustomerName', 'newQuote.OemName', 'newQuote.Qty' "
+ "'newQuote.QuoteNumber', 'newQuote.FdNumber', 'newQuote.RfqNumber', 'newQuote.RevNumber')", insertConnection);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
CustomerData.cs:
class CustomerData
{
private string _CustomerName;
private string _OEMName;
private string _OpenQuote;
private int _Qty;
private string _QuoteNumber;
private string _FdNumber;
private string _RfqNumber;
private string _RevNumber;
public CustomerData()
{
// empty constructor
}
public string CustomerName
{
get { return _CustomerName; }
set { _CustomerName = value; }
}
public string OpenQuote
{
get { return _OpenQuote; }
set { _OpenQuote = value; }
}
public string OEMName
{
get { return _OEMName; }
set { _OEMName = value; }
}
public int Qty
{
get { return _Qty; }
set { _Qty = value; }
}
public string QuoteNumber
{
get { return _QuoteNumber; }
set { _QuoteNumber = value; }
}
public string FdNumber
{
get { return _FdNumber; }
set { _FdNumber = value; }
}
public string RfqNumber
{
get { return _RfqNumber; }
set { _RfqNumber = value; }
}
public string RevNumber
{
get { return _RevNumber; }
set { _RevNumber = value; }
}
}
And as a reference, here's how I set up this table in SQLServer:
Open_Quote, date, not null
Customer_Name, varchar(25), not null
OEM_Name, varchar(25), null
Qty, int, not null
Qute_Num, varchar(20), null
Fab_Drawing_Num, varchar(20), not null
Rfq_Num, varchar(10), null
Rev_Num, varchar(10), null
Thanks in advance to anyone who helps me out,
Andrew
Try again with parameters and let us know how it goes.
http://www.dotnetperls.com/sqlparameter
Edit: Or what Tieson T. said. That'd be even better just a little more involved.
To get the data to show in the datagrid, after you do the insert, you can rebind the grid. Make sure your update the datasource so it repulls the data you just inserted. If you have problems, show where/how you are setting the datasource for the grid.
Try this:
SqlCommand cmd = new SqlCommand("INSERT INTO General_Info(Open_Quote, Customer_Name, OEM_Name, Qty, Quote_Num, Fab_Drawing_Num, "
+ "Rfq_Num, Rev_Num) values('" + newQuote.OpenQuote + "','" + newQuote.CustomerName + "','" + newQuote.OemName + "','" + newQuote.Qty + "','" + newQuote.QuoteNumber + "','" + newQuote.FdNumber + "', '" + newQuote.RfqNumber + "','" + newQuote.RevNumber + "' "
+ " )", insertConnection);
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I have a strange issue where a piece of code that I run all the time is suddenly throwing a "System.NullReferenceException: Object reference not set to an instance of an object." error.
The error occurs on a line involving a custom class that I made to simplify running TSQL action queries with parameters. With the class, I just have to use the naming convention #Param0, #Param1, etc, and pass an array of this type:
public struct SQLParam
{
private SqlDbType m_Type;
private dynamic m_Value;
public SqlDbType Type
{
get { return m_Type; }
set { m_Type = value; }
}
public dynamic Value
{
get { return m_Value; }
set { m_Value = value; }
}
public SQLParam (SqlDbType ValType, dynamic val)
{
m_Value = val;
m_Type = ValType;
}
public SQLParam(SqlParameter sqlParameter)
{
m_Value = sqlParameter.Value;
m_Type = sqlParameter.SqlDbType;
}
}
...into a method of an object of the class GCDB, called "ActionQueryWithParams", and it works. Except this one time.
Here's the code that's having trouble. I'm including various examples of code that DOES work, and marking the code that DOESN'T in comments:
GCDB GeekConn = new GCDB();
string sID = "";
string sRecurrenceID = JobRecurrenceID.Text.ToString();
if (string.IsNullOrEmpty(JobID.Text.ToString())) //added record
{
//insert job --- THIS WORKS
SQLParam[] paramslist = new SQLParam[6];
string sSQL = "INSERT INTO [dbo].[Jobs] ([CustomerID], [JobName], [JobDescription], [IsRecurringJob], [JobStatusID], [LastModifiedByStaffID]) " +
"OUTPUT INSERTED.JobID " +
"VALUES(#Param0, #Param1, #Param2, #Param3, #Param4, #Param5)";
paramslist[0] = new SQLParam(SqlDbType.Int, Convert.ToInt32(cboCustomerID.SelectedValue));
paramslist[1] = new SQLParam(SqlDbType.VarChar, JobName.Text);
paramslist[2] = new SQLParam(SqlDbType.VarChar, JobDescription.Text);
paramslist[3] = new SQLParam(SqlDbType.Bit, Convert.ToBoolean(IsRecurringJob.Checked));
paramslist[4] = new SQLParam(SqlDbType.Int, Convert.ToInt32(cboJobStatusID.SelectedValue));
paramslist[5] = new SQLParam(SqlDbType.Int, System.Web.HttpContext.Current.Session["StaffID"]);
GeekConn.ActionQueryWithParams(sSQL, paramslist);
if (GeekConn.InsertedID != null)
{
sID = GeekConn.InsertedID.ToString();
}
paramslist = null;
//insert new assignment (if applicable - if adding a job to a staff person's list) -- THIS WORKS
if (!string.IsNullOrEmpty(AssignedToStaffID.Text.ToString()))
{
paramslist = new SQLParam[2];
sSQL = "INSERT INTO [dbo].[JobAssignments] ([JobID], [StaffID]) " +
"SELECT #Param0 AS JobID, #Param1 AS StaffID " +
"WHERE NOT EXISTS(SELECT * FROM[dbo].[JobAssignments] WHERE JobID = #Param0 AND StaffID = #Param1)";
paramslist[0] = new SQLParam(SqlDbType.Int, Convert.ToInt32(sID));
paramslist[1] = new SQLParam(SqlDbType.Int, Convert.ToInt32(AssignedToStaffID.Text.ToString()));
GeekConn.ActionQueryWithParams(sSQL, paramslist);
}
paramslist = null;
}
else //edited record
{
//do the main update -- THIS WORKS
SQLParam[] paramslist = new SQLParam[7];
string sSQL = "UPDATE[dbo].[Jobs] " +
"SET [CustomerID] = #Param0 " +
",[JobName] = #Param1 " +
",[JobDescription] = #Param2 " +
",[IsRecurringJob] = #Param3 " +
",[JobStatusID] = #Param4 " +
",[LastModifiedByStaffID] = #Param5 " +
",[DateModified] = getdate() " +
"WHERE [JobID] = #Param6";
paramslist[0] = new SQLParam(SqlDbType.Int, Convert.ToInt32(cboCustomerID.SelectedValue));
paramslist[1] = new SQLParam(SqlDbType.VarChar, JobName.Text);
paramslist[2] = new SQLParam(SqlDbType.VarChar, JobDescription.Text);
paramslist[3] = new SQLParam(SqlDbType.Bit, Convert.ToBoolean(IsRecurringJob.Checked));
paramslist[4] = new SQLParam(SqlDbType.Int, Convert.ToInt32(cboJobStatusID.SelectedValue));
paramslist[5] = new SQLParam(SqlDbType.Int, System.Web.HttpContext.Current.Session["StaffID"]);
paramslist[6] = new SQLParam(SqlDbType.Int, Convert.ToInt32(JobID.Text));
GeekConn.ActionQueryWithParams(sSQL, paramslist);
paramslist = null;
//auto insert new occurrence (if this is a recurring job and there are no occurrences already) -- THIS THROWS AN ERROR
if ((IsRecurringJob.Checked) && (JobRecurrenceID.Text.ToString() == ""))
{
paramslist = new SQLParam[2];
sSQL = "INSERT INTO [dbo].[JobRecurrences] ([JobID], [StatusLastModified], [LastModifiedByStaffID]) " +
"OUTPUT INSERTED.[JobRecurrenceID] " +
"SELECT #Param0 AS JobID, getdate(), #Param1 AS StaffID " +
"WHERE NOT EXISTS (SELECT * FROM [dbo].[JobRecurrences] WHERE JobID = #Param0)";
paramslist[0] = new SQLParam(SqlDbType.Int, Convert.ToInt32(JobID.Text));
paramslist[1] = new SQLParam(SqlDbType.Int, System.Web.HttpContext.Current.Session["StaffID"]);
// ERROR IS HERE: System.NullReferenceException: Object reference not set to an instance of an object.
GeekConn.ActionQueryWithParams(sSQL, paramslist);
if (GeekConn.InsertedID != null)
{
sRecurrenceID = GeekConn.InsertedID.ToString();
}
}
paramslist = null;
}
GeekConn = null;
I've confirmed that the SQL statement for auto-inserting a new occurrence works in SSMS. And, as far as I can tell, there's nothing in the broken code that isn't also in the working code. Can anybody spot anything I'm missing?
Many thanks!
Many thanks, all! The problem appears to have fixed itself when I fixed another issue (where it wasn't always loading the most recent JobRecurrence into JobRecurrenceID.Text on load).
I ran another test (using the debugger, as recommended), and it does appear to work correctly when the query is actually inserting a record. The issue was that I sometimes had the query run but, because of the WHERE condition (NOT EXISTS), it wasn't actually inserting a record, and it seems it was probably breaking this line of code in the GCDB.ActionQueryWithParams method (only including relevant code):
bool bolIsInsert = (sSQLUpper.Contains("OUTPUT INSERTED."));
try
{
if (bolIsInsert)
{
cmd.Parameters.Add("#ID", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
InsertedID = (int)cmd.ExecuteScalar();
} else
{
cmd.ExecuteNonQuery();
}
}
catch (SqlException e)
{
Error = e.Message.ToString();
}
Apparently I need to include a way to handle INSERT statements that did not actually insert anything. Hmm... Well, that's a separate question. :)
I have a strange problem:
Database: Firebird
Connection String:
Driver={Firebird/InterBase(r)driver};Dbname=xxx;CHARSET=NONE;UID=xxx;
PASSWORD=xxx
I use a set of ODBC classes to operation(select) the database table
when I loop the db records with OdbcDataReader.GetValue(), if some fields(char type) have no value(char_length()=0), it would get the last record field value; if fields has the value, it's ok(does not get the value from last record)
My code likes below:
var dr = this.SqlExecutor.Open(sql); //sql is String variable that stored the sql statement
while (dr.Read())
{
this.Logger.Info("-----Customer_Id: " + this.SqlReader.GetFieldAsString(dr, "Customer_Id") + " -----"); // this not duplicated because it's not empty
this.Logger.Info("-----Customer_Email: " + this.SqlReader.GetFieldAsString(dr, "Customer_email") + " -----"); //this would if some records has empty value
}
// the method SqlExecutor.Open(sql) and SqlReader.GetFieldAsString() please refer to below:
public IDataReader Open(string sql)
{
this.Logger.Debug("sql: " + sql);
if (this.reader != null && !this.reader.IsClosed)
{
this.reader.Close();
this.reader = null;
}
try
{
this.cmdForSelect.Connection = this.conn;
this.cmdForSelect.CommandTimeout = 120;
this.cmdForSelect.CommandText = sql;
this.cmdForSelect.Parameters.Clear();
foreach (var p in this.dbParameters)
{
this.cmdForSelect.Parameters.Add(p);
}
this.reader = cmdForSelect.ExecuteReader();
}
catch (Exception ex)
{
this.Logger.Error("There is an error: {0}", ex.Message);
this.Logger.Info("Error sql query:" + sql);
throw;
}
finally
{
this.ClearParameters();
}
return this.reader;
}
public string GetFieldAsString(IDataReader dr, string fieldName)
{
try
{
var value = dr.GetValue(dr.GetOrdinal(fieldName));
if (value == DBNull.Value)
{
return string.Empty;
}
return Convert.ToString(value);
}
catch
{
return string.Empty;
}
}
Besides, this case is fine on my computer, just happened on my customer's computer, I feel this does not matter with mycode, anyone know this, please help me, thanks a lot!!!
Assuming the actual code is not posted in your question; I think the problem is with re-initiation of the variable in the actual code. You need to revisit the code and check the IF-ELSE condition you have applied on the this.SqlReader.GetFieldAsString(dr, "Customer_email")
I faced a problem while trying to build a Windows form solution for a college assignment, and hope somebody can point out my mistake.
The solution is about a mobile shop. I have two classes, Apple and Android forms. I need to read the data in the database table, categorize the entries to either Android or Apple phones, and then display all phones in a list when the form loads.
I can successfully categorize phones, but when trying to read the entries, I always end up with the same entry twice in my list on the form, while the second entry doesn't appear at all.
I know I made a big stupid mistake while doing the connection but I can't find it!.
Here is my code:
public abstract class MobilePhone {
private Int32 phoneID;
private string operatingSystem;
private string make;
private string model;
public enum Condition { Poor, Fair, Good, Mint };
private Condition condition;
private decimal originalPrice;
private DateTime datePurchase;
private string description;
private clsDataConnection dbConnection;
//constructor
public MobilePhone(string make, string model, decimal originalPrice, DateTime datePurchase, Condition condition, string description) {
this.make = make;
this.model = model;
this.originalPrice = originalPrice;
this.datePurchase = datePurchase;
this.condition = condition;
this.description = description;
}
Not complete, but that's what is relevant:
public class ApplePhone : MobilePhone {
decimal ApproxValue;
public ApplePhone(string make, string model, decimal originalPrice, DateTime datePurchase, Condition condition, string description)
: base(make, model, originalPrice, datePurchase, condition, description) {
}
The Android class is the same but with different other functions.
class Shop {
clsDataConnection dbConnection;
const int NotAdded = -1; // invalid primary key
private string name;
private decimal ApproxValue;
private Int32 phoneID;
private string operatingSystem;
private string make;
private string model;
private MobilePhone.Condition condition;
private decimal originalPrice;
private DateTime datePurchase;
private string description;
Int32 Index;
private List<MobilePhone> phonesForSale;
//constructor
public Shop(string name) {
this.name = name;
}
MobilePhone phone;
public void SelectAll() {
dbConnection = new clsDataConnection();
dbConnection.Execute("SellectAllPhones");
}
public void FilterByOperatingSystem(string operatingSystem) {
dbConnection = new clsDataConnection();
dbConnection.AddParameter("#OperatingSystem", operatingSystem);
dbConnection.Execute("FilterByOperatingSystem");
}
public Int32 Count {
get {
//return the count of records
return dbConnection.Count;
}
}
public string DescribeCurrentPhone(int Index) {
Int32 phoneID;
string make;
string model;
MobilePhone.Condition condition;
decimal originalPrice;
DateTime datePurchase;
string description;
phoneID = Convert.ToInt32(phonesForSale[Index].PhoneID);
make = Convert.ToString(phonesForSale[Index].Make);
model = Convert.ToString(phonesForSale[Index].Model);
condition = phonesForSale[Index].GetCondition;
originalPrice = Convert.ToDecimal(phonesForSale[Index].OriginalPrice);
datePurchase = Convert.ToDateTime(phonesForSale[Index].DatePurchased);
description = Convert.ToString(phonesForSale[Index].Description);
//set up a new object of class list item
string listItemText = make + " " + "|" + " " + model + " " + "|" + " " + condition + " " + "|" + " " + "£" + Math.Round(originalPrice, 2) + " " + "|" + " " + datePurchase.ToShortDateString() + " " + "|" + " " + description;
return listItemText;
}
public List<MobilePhone> Allphones {
get {
phonesForSale = new List<MobilePhone>();
int count = Count;
Index = 0;
while (Index < count) {
phoneID = Convert.ToInt32(dbConnection.DataTable.Rows[Index]["PhoneId"]);
operatingSystem = Convert.ToString(dbConnection.DataTable.Rows[Index]["OperatingSystem"]);
make = Convert.ToString(dbConnection.DataTable.Rows[Index]["Make"]);
model = Convert.ToString(dbConnection.DataTable.Rows[Index]["Model"]);
string conditionString = Convert.ToString(dbConnection.DataTable.Rows[Index]["Condition"]);
originalPrice = Convert.ToInt32(dbConnection.DataTable.Rows[Index]["OriginalPrice"]);
datePurchase = Convert.ToDateTime(dbConnection.DataTable.Rows[Index]["DatePurchased"]);
description = Convert.ToString(dbConnection.DataTable.Rows[Index]["Description"]);
// Set Condition
if (conditionString == "Poor") {
condition = MobilePhone.Condition.Poor;
} else if (conditionString == "Fair") {
condition = MobilePhone.Condition.Fair;
} else if (conditionString == "Good") {
condition = MobilePhone.Condition.Good;
} else if (conditionString == "Mint") {
condition = MobilePhone.Condition.Mint;
}
//check Operating System
if (operatingSystem == "IOS") {
phone = new ApplePhone(make, model, originalPrice, datePurchase, condition, description);
//ApproxValue = ApplePhone.CalculateApproximateValue();
} else if (operatingSystem == "Android") {
phone = new AndroidPhone(make, model, originalPrice, datePurchase, condition, description);
//ApproxValue = AndroidPhone.CalculateApproximateValue();
}
Index++;
phonesForSale.Add(phone);
}
return phonesForSale;
}
}
And the form code is:
public partial class FormMain : Form {
public FormMain() {
InitializeComponent();
Shop shop = new Shop("");
}
private void FormMain_Load(object sender, EventArgs e) {
DisplayItems("");
}
protected int DisplayItems(string operatingSystem) {
Shop MyShop = new Shop("");
Int32 RecordCount;
Int32 Index = 0;
Int32 PID;
if (operatingSystem != "") {
MyShop.FilterByOperatingSystem(operatingSystem);
} else {
MyShop.SelectAll();
}
RecordCount = MyShop.Count;
ArrayList MyPhones = new ArrayList();
while (Index < RecordCount) {
// I Suspect this line is the problem but don't know how to fix it
PID = MyShop.Allphones[Index].PhoneID
string listItemText = MyShop.DescribeCurrentPhone(PID);
//add the new item to the list
MyPhones.Add(listItemText);
//increment the index
Index++;
}
listBox1.DataSource = MyPhones;
return RecordCount;
}
I am not used to connecting to databases, so any advice will be of help!
An example of an alternative to the DB connection you have made is below
List<MyPhone> myIPhoneList = new List<Myphone>();
List<MyPhone> myAndroidList = new List<Myphone>();
SqlConnection myDBConnection = new SqlConnection("MyConnectionString"); //DB Connection
SqlCommand dbCommand = new SqlCommand("SelectAllPhones"); //Stored Procedure
SqlDataReader recordReader = dbCommand.ExecuteReader(); //Execute
//Read records return in to phone objects
while (recordReader.Read()) {
var phoneField1 = recordReader["PhoneField1FromDatabase"];
var phoneField2 = recordReader["PhoneField2FromDatabase"];
//etc...
var myPhone = new MyPhone();
myPhone.Name = phoneField1;
//etc...
if (myPhone.OS == "iPhone")
myIPhoneList.Add(myPhone);
if (myPhone.OS = "Android")
myAndroidList.Add(myPhone);
}
Just a twist to Wheels answer really,
I'd personally put a filter on the stored-proc.
SqlCommand dbCommand = new SqlCommand("SelectAllPhones"); //Stored Procedure
becomes something like:
using (SqlConnection conn = new SqlConnection())
{
using (SqlCommand cmd = new SqlCommand("SelectAllPhones", conn))
{
cmd.Parameters.Add(new SqlParameter() { ParameterName = "#OS", SqlDbType = SqlDbType.VarChar, Direction = ParameterDirection.Input, Value = phoneOS });
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// load your data...
}
}
}
Only because there is very little point dragging both sets of phone data (android/iphone) for each class. You may as well only pull back the data you require.
Of course the Stored-Proc will need an update to cater for the parameter.
something like:
AND PhoneOS = #OS
needs appending to your SQL condition.
clsDataConnection dbConnection; is unknown to me - is this a third party library or a class you've wrote and not included?
public Int32 Count
{
get
{
//return the count of records
return dbConnection.Count;
}
}
dbConnection.Count seems very non-standard. Doesn't read as if you're trying to get the number of rows, more the number of connections - which is invalid here.
dbConnection.DataTables[0].Rows.Count; would be a better way of determining the rows using your existing code, as currently it reads as if your counting the number of database connections which isn't what your after - and would be redundant if using either mine or Wheels as you wont need to know beforehand how many rows your about to process.
My goal is to display the cost for a One-Day Conference on a web page, which is $50.00. However, I keep getting $0.00 in return. I tested my SELECT statement in SQL and it is retrieving the correct data. Now I have narrowed down the problem to be in my if...else if statements in the PayBackCC method but I am not certain. It should get the cost from variable cOneDCost. Any help is appreciated.
Code behind
protected void PayBackInfo()
{
try
{
con.Open();
SqlCommand PBCredit = new SqlCommand("SELECT * FROM PaymentInfo, ConferenceReg WHERE PaymentInfoID=PaymentInfoIDNum AND PaymentInfoID=#payID AND ConferenceReg.Deleted='N' AND ConferenceIDNum=#confID", con);
PBCredit.Parameters.AddWithValue("#confID", confID);
PBCredit.Parameters.AddWithValue("#payID", Request.QueryString["payID"]);
SqlDataReader readerPB = PBCredit.ExecuteReader();
while (readerPB.Read())
{
piID = readerPB["PaymentInfoID"].ToString();
cID = readerPB["ConferenceIDNum"].ToString();
poID = readerPB["PurchaseOrder"].ToString();
partnersNum = readerPB["PartnersIDNum"].ToString();
cFullCost = Convert.ToDecimal(readerPB["ConferenceFullFee"]).ToString("#,##0.00");
cOneDCost = Convert.ToDecimal(readerPB["ConferenceOneDayFee"]).ToString("#,##0.00");
partnersCost = Convert.ToDecimal(readerPB["PartnersFee"]).ToString("#,##0.00");
PayBackCC();
}
readerPB.Close();
}
finally
{
con.Close();
}
}
private void PayBackCC()
{
if (!partnersNum.Equals("null") || !partnersNum.Equals("0"))
{
msgLbl.Text = "$" + partnersCost;
}
else if (!cFullCost.Equals("0"))
{
msgLbl.Text = "$" + cFullCost;
}
else if (!cOneDCost.Equals("0"))
{
msgLbl.Text = "$" + cOneDCost;
}
}
Please change
if (!partnersNum.Equals("null") || !partnersNum.Equals("0"))
to
if (!String.IsNullOrEmpty(partnersNum) || !partnersNum.Equals("0"))
unless you are expecting "null" string from your query
Here is my code, everything is working fine the only problem is with the ReadData() method in which i want the string value to be increment i.e AM0001,AM0002,AM0003 etc. This is happening till the execution of the program once i stop the execution of program, the second time when i run the program the same value i.e AM0001 is getting return. Due to this i am getting a error from oledb because of AM0001 is a primary key field.
This is my code:
class Jewellery : Connectionstr
{
string lmcode;
public string LM_code
{
get { return lmcode;}
set { lmcode = ReadData();}
}
string mname;
public string M_Name
{
get { return mname; }
set { mname = value;}
}
string desc;
public string Desc
{
get { return desc; }
set { desc = value; }
}
public string ReadData()
{
string jid = string.Empty;
string displayString = string.Empty;
String query = "select max(LM_code)from Master_Accounts";
Datamanager.RunExecuteReader(Constr,query);
jid = LM_code;// this is working on first execution, the second time when i run the program the value null defined in LM_code.
if (string.IsNullOrEmpty(jid))
{
jid = "AM0000";//This string value has to increment at every time, but it is getting increment only one time.
}
int len = jid.Length;
string split = jid.Substring(2, len - 2);
int num = Convert.ToInt32(split);
num++;
displayString = jid.Substring(0, 2) + num.ToString("0000");
return displayString;
}
public void add()
{
String query ="insert into Master_Accounts values ('" + LM_code + "','" + M_Name + "','" + Desc + "')";
Datamanager.RunExecuteNonQuery(Constr , query);
}
Any help will be appreciated.
Do not declare jid in method, declare it in class level:
private string jid = string.Empty;