C# Bizarre Object Reference Not Set error with custom class [duplicate] - c#

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. :)

Related

C# Webservice stucks. Need to override published file to restart

Please help me, I'm facing a fatal problem here. If someone could fix this, I swear I will treat u to a huge drink whenever u step into my country (Vietnam). Ok here's the problem: I'm coding a webservice for multi connection simultaneously from tablet (around 100 clients). It ran well but recently whenever high traffic occurs, my webservice seems to stuck somehow and I need to copy - override the published file of webservice in order for it to run again (restart website in IIS is no use) ...
This is my w/s code for handling the data:
public string Info_Handling(string id, string name, string strDetails)
{
string checkExist = "";
string str = "";
string str2 = "";
MLL_Customer _customerClient = new MLL_Customer();
MLL_CustomerCategory _categoryClient = new MLL_CustomerCategory();
MLL_Product _productClient = new MLL_Product();
MLL_SampleProduct _sampleClient = new MLL_SampleProduct();
if (_customerClient.CheckExistCustomer(id, name.ToUpper(), 2) == 1) // SID & NAME
{
checkExist = "EXIST";
}
using (SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["Main.ConnectionString"]))
{
connection.Open();
SqlTransaction trans = connection.BeginTransaction("XXX");
try
{
// ID Example: 11 means VIP - 12 means Normal - 13 means ples... jkg
// First - Insert Customer
string strCustomerCategory = _categoryClient.SelectCategoryByID(id).ToString();
if (!checkExist.Equals("EXIST"))
{
Customer businessObject = new Customer();
businessObject.ID = sid;
businessObject.Name = name.ToUpper();
businessObject.CategoryID = strCustomerCategory;
str = "" + _customerClient.Insert(businessObject, connection, trans);
}
// Second Insert Product spliting from a string Ex: "TV&Laptop&CD"
string[] productDetails = strDetails.Split(new char[] { '&' });
object obj3;
SampleProduct objSample;
Product objProduct;
for (int j = 0; j < productDetails.Length; j++)
{
if (_productClient.CheckExist(id, productDetails[j])) == null) // Check if customer already owns this product
{
// Get the properties of sample product.
objSample = _sampleClient.SelectSampleProduct(productDetails[j]);
objProduct = new Product();
objProduct.SID = sid;
objProduct.Testcode = objSample.TestCode;
objProduct.Category = objSample.Category;
objProduct.Unit = objSample.Unit;
objProduct.Price = objSample.Price;
if (_productClient.Insert(objProduct, connection, trans) != 0)
{
str2 = str2 + "&" + objProduct.Testcode;
// return the code of product in order to see which product has been inserted successfully
}
}
}
trans.Commit();
SqlConnection.ClearAllPools();
}
catch (Exception exception)
{
str = "0";
str2 = exception.Message + exception.Source;
try
{
trans.Rollback();
}
catch (Exception)
{
}
}
}
if (!str2.Equals(""))
{
return (str + "&" + id + str2);
}
return ("0&" + sid + str);
}
I modified the code but this is basically how i roll. Could anyone plz tell me some solution. Deeply thank u.
1 more thing about ClearAllPools() method: I know how it works but I dont even know why I need it. Without this, my data will be messed up terrible. CategoryID of one customer will be assigned for another customer sometimes. ???? How could it happened ?? HELP

C# QuickBooks Cannot add Check

I'm attempting to add the ability to transfer commission payments from my system to QuickBooks using C#, and I've got a whole bunch of it working except for the add check requests. Currently, I'm getting this output
CheckAdd
ExpenseLineAddList:
element(2) - Required object is empty
End of ExpenseLineAddList
End of CheckAdd
and here's the code. It's a little long unfortunately, but that's just what surrounds the necessary bits.
MySql.Data.MySqlClient.MySqlConnection CheckConn = new MySql.Data.MySqlClient.MySqlConnection();
MySqlCommand CheckCmd = new MySqlCommand();
CheckConn.ConnectionString = myConnectionString;
CheckConn.Open();
CheckCmd.Connection = CheckConn;
CheckCmd.CommandText = "select `companies`.`ParentCompanyName`, `DateTimeStart`, `DateTimeEnd` from `commissiontransfers` join `orders` using (`InvoiceID`) join `companies` using (`CompanyID`) where `Transfered`=0 group by `ParentCompanyName`;";
MySqlDataReader CheckReader = CheckCmd.ExecuteReader();
DataTable Checks;
using (CheckReader)
{
Checks = new System.Data.DataTable();
Checks.Load(CheckReader);
}
CheckReader.Close();
CheckReader.Dispose();
CheckConn.Close();
CheckConn.Dispose();
foreach (DataRow Check in Checks.Rows)
{
IMsgSetRequest AddCheckMsgSet = sessionManager.CreateMsgSetRequest("US", 8, 0);
AddCheckMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
ICheckAdd CheckAddRq = AddCheckMsgSet.AppendCheckAddRq();
CheckAddRq.AccountRef.FullName.SetValue("Bank Account");
CheckAddRq.PayeeEntityRef.FullName.SetValue(Convert.ToString(Check["ParentCompanyName"]));
CheckAddRq.Memo.SetValue("Date Range: From " + Convert.ToDateTime(Check["DateTimeStart"]).ToString("MM/dd/yyyy") + " to " + Convert.ToDateTime(Check["DateTimeEnd"]).ToString("MM/dd/yyyy"));
CheckAddRq.IsToBePrinted.SetValue(true);
MySql.Data.MySqlClient.MySqlConnection CommissionTransferConn = new MySql.Data.MySqlClient.MySqlConnection();
MySqlCommand CommissionTransferCmd = new MySqlCommand();
CommissionTransferConn.ConnectionString = myConnectionString;
CommissionTransferConn.Open();
CommissionTransferCmd.Connection = CommissionTransferConn;
CommissionTransferCmd.CommandText = "select `CommissionTransferID`, round(`OrderCommission`-`FactoryCommission`-`ShippingCommission`, 2) `Total`, `orders`.`DateTimePaid`, `companies`.`OldQBName`, `orders`.`Customer` from `commissiontransfers` join `orders` using (`InvoiceID`) join `companies` using (`CompanyID`) where `Transfered`=0;";
MySqlDataReader CommissionTransferReader = CommissionTransferCmd.ExecuteReader();
DataTable CommissionTransfers;
using (CommissionTransferReader)
{
CommissionTransfers = new System.Data.DataTable();
CommissionTransfers.Load(CommissionTransferReader);
}
CommissionTransferReader.Close();
CommissionTransferReader.Dispose();
CommissionTransferConn.Close();
CommissionTransferConn.Dispose();
foreach (DataRow CommissionTransfer in CommissionTransfers.Rows)
{
IExpenseLineAdd ExpenseLineAdd = CheckAddRq.ExpenseLineAddList.Append();
ExpenseLineAdd = CheckAddRq.ExpenseLineAddList.Append();
ExpenseLineAdd.AccountRef.FullName.SetValue("Contract Labor:1099's");
ExpenseLineAdd.Amount.SetValue(Convert.ToDouble(CommissionTransfer["Total"]));
ExpenseLineAdd.Memo.SetValue(Convert.ToString(CommissionTransfer["Customer"]) + " - " + Convert.ToDateTime(CommissionTransfer["DateTimePaid"]).ToString("MM/dd/yyyy"));
ExpenseLineAdd.ClassRef.FullName.SetValue(Convert.ToString(CommissionTransfer["OldQBName"]));
GetFirstRow("update `commissiontransfers` set `Transfered`=1 where `CommissionTransferID`='" + CommissionTransfer["CommissionTransferID"] + "';");
}
CheckAddRq.IncludeRetElementList.Add("TxnID");
try {
IMsgSetResponse CheckResponseMsgSet = sessionManager.DoRequests(AddCheckMsgSet);
IResponse CheckResponse = CheckResponseMsgSet.ResponseList.GetAt(0);
MessageBox.Show(CheckResponse.StatusCode + ": " + CheckResponse.StatusMessage);
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
It seems to be acting like my AddCheckMsgSet variable is empty, but I can't for the life of me figure out why it would be. Any help is much appreciated!
Of course, I spend three hours stuck on this problem, and then solve it myself right after I post it here. Well, the problem had to do with these lines
IExpenseLineAdd ExpenseLineAdd = CheckAddRq.ExpenseLineAddList.Append();
ExpenseLineAdd = CheckAddRq.ExpenseLineAddList.Append();
All I needed to do was get rid of the second line, since I was already appending a new expense line, and the second append caused the first request to be blank. Hope this helps someone in the future, since I've had only problems with trying to connect to QuickBooks.

AS400 RPG Program not returning anything

I have the following code. The program just exits, no value returned from call. Any ideas?
AS400System system = new AS400System();
system.Define(ConfigurationManager.AppSettings["AS400Server"]);
system.UserID = ConfigurationManager.AppSettings["AS400User"];
system.Password = ConfigurationManager.AppSettings["AS400Password"];
system.IPAddress = "10.98.1.21";
system.Connect(cwbcoServiceEnum.cwbcoServiceRemoteCmd);
if(system.IsConnected(cwbcoServiceEnum.cwbcoServiceRemoteCmd) == 1) {
Program program = new Program();
program.LibraryName = "P2PTST";
program.ProgramName = "AUI0XFR";
program.system = system;
program.system.Signon();
string paramStatus = "A";
Int64 paramStockItem = Int64.Parse(t.EtagNumber);
Guid paramGuid = Guid.NewGuid();
string paramReturn;
StringConverter stringConverter = new StringConverter();
ProgramParameters parameters = new ProgramParameters();
parameters.Append("ApiIGuid", cwbrcParameterTypeEnum.cwbrcInout, 38);
parameters.Append("StockItemNumber", cwbrcParameterTypeEnum.cwbrcInout, 20);
parameters.Append("ItemStatus", cwbrcParameterTypeEnum.cwbrcInout, 1);
parameters.Append("ReturnCode", cwbrcParameterTypeEnum.cwbrcInout, 7);
parameters["ApiIGuid"].Value = stringConverter.ToBytes(paramGuid.ToString().PadRight(38, ' '));
parameters["StockItemNumber"].Value = stringConverter.ToBytes(paramStockItem.ToString().PadRight(20, ' '));
parameters["ItemStatus"].Value = stringConverter.ToBytes(paramStatus.ToString());
try{
program.Call(parameters);
paramReturn = stringConverter.FromBytes(parameters["ReturnCode"].Value);
system.Disconnect(cwbcoServiceEnum.cwbcoServiceAll);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
We just went through this and had the same issues, so decided to create and use a stored procedure to accomplish this in .NET. Because we were concerned about having the 400 side distribute the code to create a stored procedure, it ended up being very quick to go ahead and create the procedure on the PC side, followed by our remote command, so no additional changes were necessary on the 400 side.
My environment is Win7 x64 running VS2012 C#, CAX V7.1, and importing both IBM.Data.DB2.iSeries, and System.Data;
I need System.Data for the Parameters. That ended up being critical to get data back!
I send the 400 two params, filesetID and a name. I get back a number and a uuid.
(but they are all characters!)
It looks something like this:
public void RemoteCmd(ref PicMeta pm)
{
iDB2Connection cn;
try
{
using (cn = new iDB2Connection("DataSource=<servername/IP>; UserID="<user>"; Password="<pass>";"))
{
cn.Open();
using (iDB2Command cm = cn.CreateCommand())
{
//Place a try/catch here, so it will create the procedure the first time, or any time it has been removed from the 400. If already set, it will fail, and you'll go directly to the remote command.
try
{
//Here we create a procedure and execute or continue.
cm.CommandText = "CREATE PROCEDURE LIBRARY.SP_PICGETID(INOUT FSET CHAR (1 ), INOUT UNIT CHAR (6 ), INOUT NEXTID CHAR (3 ), INOUT UUID CHAR (36 )) LANGUAGE RPGLE NOT DETERMINISTIC NO SQL CALLED ON NULL INPUT EXTERNAL NAME LIBRARY.PICGETID PARAMETER STYLE GENERAL";
cm.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.Out.WriteLine(ex.Message);
}
//Continue - create and call the command
//ParameterDirection needs "using System.Data;"
cm.CommandTimeout = 0;
cm.CommandType = System.Data.CommandType.StoredProcedure;
cm.CommandText = "LIBRARY.SP_PICGETID";
iDB2Parameter p = new iDB2Parameter();
p.ParameterName = "FSET";
p.Direction = ParameterDirection.Input;
p.iDB2DbType = iDB2DbType.iDB2Char;
p.Size = 1;
p.iDB2Value = pm.fileset;
cm.Parameters.Add(p);
p = new iDB2Parameter();
p.ParameterName = "UNIT";
p.Direction = ParameterDirection.Input;
p.iDB2DbType = iDB2DbType.iDB2Char;
p.Size = 6;
p.iDB2Value = pm.unit;
cm.Parameters.Add(p);
p = new iDB2Parameter();
p.ParameterName = "NEXTID";
p.Direction = ParameterDirection.InputOutput;
p.iDB2DbType = iDB2DbType.iDB2Char;
p.Size = 3;
p.iDB2Value = "";
cm.Parameters.Add(p);
p = new iDB2Parameter();
p.ParameterName = "GUUID";
p.Direction = ParameterDirection.InputOutput;
p.iDB2DbType = iDB2DbType.iDB2Char;
p.Size = 36;
p.iDB2Value = "";
cm.Parameters.Add(p);
cm.ExecuteNonQuery();
iDB2ParameterCollection pc = cm.Parameters;
//We get our Out parameters here
pm.nextid = pc["NEXTID"].Value.ToString();
pm.uuid = pc["GUUID"].Value.ToString();
}
cn.Close();
}
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
}
return;
}
Hope this helps!

Issues with INSERT statement (I think)

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

Use command line variable in later code

I have a WinForm,
I am have added command line functions as so-
foreach (string arg in args)
{
if (arg == "-id")
{
string u = "";
ADODB.Connection ADconn = new ADODB.Connection();
string connstr = "db connection string";
ADconn.ConnectionString = connstr;
object recs;
ADODB.Recordset rs = new ADODB.Recordset();
ADconn.Open(connstr);
string qry = string.Format("Select ID from TABLE where NO = '" + args[counts + 1] + "'");
rs = ADconn.Execute(qry, out recs, 0);
for (; !rs.EOF; rs.MoveNext())
{
string test = rs.Fields["column"].Value.ToString();
u = test;
}
}
counts = counts + 1;
}
Therefore args[counts + 1] is whatever variable the user input in the command line after -id. I need to use this value later on in my code however how can I do this?
One option is to create a class with static properties that encapsulate the command line arguments, e.g.
public class RunConfiguration
{
public static int Id { get; set; }
}
Initialize the values in your main() routine. You can then reference them anywhere in your program like
int id = RunConfiguration.Id;
Use Environment.GetCommandLineArgs to access command line arguments from anywhere in your program, not just the main method. (It prevents you from needing to pass them around everywhere as well.)

Categories

Resources