Inserting data query error - c#

i have tried to insert the data by login to the system. my query doesn't have any error, but the exception has thrown by the run time as "Object reference not set to an instance of an object ". check my code and please correct me.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (TextBox6.Text == " ")
{
string alertmessage = "";
alertmessage = "Username should not be blank";
this.CreateMessageAlert(this, alertmessage, "alertKey");
TextBox6.Focus();
}
else if (TextBox7.Text == " ")
{
string alertmessage = "";
alertmessage = "Username should not be blank";
this.CreateMessageAlert(this, alertmessage, "alertKey");
TextBox7.Focus();
}
else
{
string sq = "SELECT COUNT(*) FROM tbl_KKSUser WHERE Uname=#un and Password=#pas";
SqlCommand sd = new SqlCommand(sq, con);
SqlParameter unameparam;
unameparam = new SqlParameter("#un", SqlDbType.VarChar, 25);
unameparam.Value = TextBox6.Text;
sd.Parameters.Add(unameparam);
string original = TextBox7.Text.Trim();
string withhash = original;
b1 = Encoding.BigEndianUnicode.GetBytes(withhash);
encrypted = Convert.ToBase64String(b1);
SqlParameter passparam;
passparam = new SqlParameter("#pas", SqlDbType.VarChar, 8000);
passparam.Value = Convert.ToString(encrypted);
sd.Parameters.Add(passparam);
con.Open();
{
int iresults;
iresults = Convert.ToInt32(sd.ExecuteScalar().ToString());
if (iresults > 0)
{
string q = "insert into tbl_KKSMaterialRaise(MaterialCode,Source,Category,Population,StockInStores,Specification,PrearedBy,CheckedBy,ApprovedBy,CreatedDate) values(#mc,#sc,#cat,#pop,#sis,#spec,#pb,#cb,#ab,#cd)";
SqlCommand dm = new SqlCommand(q, con);
dm.Parameters.AddWithValue("#mc", Mcodeddl.SelectedItem.Text);
dm.Parameters.AddWithValue("#sc", TextBox1.Text.Trim());
dm.Parameters.AddWithValue("#cat", TextBox2.Text.Trim());
dm.Parameters.AddWithValue("#pop", TextBox3.Text.Trim());
dm.Parameters.AddWithValue("#sis", TextBox4.Text.Trim());
dm.Parameters.AddWithValue("#spec", TextBox5.Text.Trim());
dm.Parameters.AddWithValue("#pb", PBddl.SelectedItem.Text);
dm.Parameters.AddWithValue("#cb", CBddl.SelectedItem.Text);//In this line i have got error
dm.Parameters.AddWithValue("#ab", ABddl.SelectedItem.Text);
dm.Parameters.AddWithValue("#cd", DateTime.Today);
dm.ExecuteNonQuery();
string alertmessage = "";
alertmessage = "Component Details Saved";
this.CreateMessageAlert(this, alertmessage, "alertKey");
}
else
{
Response.Write("<script>alert('Invalid Username/Password')</script>");
}
}
con.Close();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

It looks most likely that one of your dropdownlists has no option selected, i.e. the null reference is coming from one of the lines like:
dm.Parameters.AddWithValue("#mc", Mcodeddl.SelectedItem.Text);
Try checking that all of those have items selected before retrieving the .Text property.
If it isn't that, it would be useful to know which line is causing the exception - you can usually get that from the exception stack trace.

It means you have not initialized or assigned a variable. The debugger should tell you which variable specifically. Take a closer look at it. Then you only have to check that it is already initialized (= new Class()) or assigned (= instance).
You may want to take a look at this question.

Related

How to check if user in mysql database exists (in c#)

So I know this is a often asked question but I want to check if the username is already taken in the database using c#. I tried this:
MySqlCommand cmd2 = new MySqlCommand("SELECT * FROM tablename WHERE(name = '" + tb1.Text + "');");
cmd2.Connection = connect;
connect.Open();
string unt = "";
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
unt= dr.GetString("name");
}
dr.Close();
}
catch (Exception ex)
{
errorbox.Content = ex.Message;
}
finally
{
connect.Close();
}
if(unt == "" || unt == "0") {
continuel = false;
tb2.Text = "User " +tb1.Text+ " doesn't exist!";
Popup1.IsOpen = true;
}
Its a WPF project and the variable 'continuel' is set to true by default. The code doesn't recognize if a user doesn't exist.
First off your code is vulnerable to sql inject, you should never concatenate values into a query. secondly you can do a count and execute a scalar. Not I stripped down your code a little you'll have to add error handling back.
bool userExists = false;
private String sql = "SELECT COUNT(*) FROM tableName WHERE name = #usernameparam;";
MySqlCommand m = new MySqlCommand(sql);
m.Parameters.AddWithValue("#usernameparam", tb1.Text.Trim());
int userCount = Convert.ToInt32(m.ExecuteScalar());
if(userCount>0)
{
userExists = true;
}
//use userExists variable to evaluate if user exists

Update query not throwing error

Thanks for the help in advance.
Im trying to use update query in C#
Error : command is getting executed even if I use incorrect values
Design view
Code :
protected void Button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
cmd = new SqlCommand("update Comcast_AvayaID set Status='Inactive' where Employee_Id='" + TxtEMPID.Text + "' and AvayaID ='" + TxtAvayaID.Text + "'", con);
cmd = new SqlCommand("UPDATE Avaya_Id SET Status = 'UnAssigned' where Avaya_ID ='" + TxtAvayaID.Text + "'", con);
cmd.ExecuteNonQuery();
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Successfull";
con.Close();
}
catch (SqlException ex)
{
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Unsuccessfull";
}
your code would look better like this, it not the most optimal, but ia already a way better piece of code then your snippet
1) added parameters using a helper function for the sql injection issue
2) an ExecuteNonQuery returns the rows affected, so if you are expecting that 1 row was updated, you can check on that
3) if you update a row with an id that not exists, it will not throw a SqlException like you are expecting in your code, this happens e.g. when locking occurs
public void Update()
{
var con = new SqlConnection();
try
{
var empId = TxtEMPID.Text
var avayaId = TxtAvayaID.Text
con.Open();
var cmd1 = new SqlCommand("update Comcast_AvayaID set Status='Inactive' where Employee_Id=#empId and AvayaID = #avayaId", con);
cmd1.Parameters.Add(AddParameter("#empId",empId));
cmd1.Parameters.Add(AddParameter("#avayaId", avayaId));
var cmd2 = new SqlCommand("UPDATE Avaya_Id SET Status = 'UnAssigned' where Avaya_ID =avayaId", con);
cmd2.Parameters.Add(AddParameter("#avayaId", avayaId));
var rowsaffected1 = cmd1.ExecuteNonQuery();
var rowsAffected2 = cmd2.ExecuteNonQuery();
if (rowsaffected1 == 1 && rowsAffected2 == 1)
{
//success code goes here
//--------
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Successfull";
}
else
{
// failure code goes here
//-----------------------
LBLSuccess.Visible = true;
LBLSuccess.Text = "Deactivation Unsuccessfull";
}
}
catch (SqlException ex)
{
//handle errors
}
finally
{
con.Close();
}
Console.ReadLine();
}
private SqlParameter AddParameter(string name, object value) {
var par = new SqlParameter();
par.ParameterName = name;
par.Value = value;
return par;
}
If you put "incorrect" values it just updates zero of records. No errors/exception expected here.

Identifying duplicate data, and re-search database based on new user input

I have been able to identify if the value is duplicated or not but only for the very first value entered, it seems as if the first entry is being held as a search and it doesn't update the search when the value has been changed in the textbox. For visual representation see images below.
Here is my method I have used:
private void CheckContactNumber()
{
DataSet myDataSet = new DataSet();
try
{
string strAccessSelect = "select count(*) from Employee where ContactNumber='" + addContactNum.Text + "'";
OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect, conn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
conn.Open();
myDataAdapter.Fill(myDataSet, "Employee");
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
return;
}
finally
{
conn.Close();
}
DataTable dt = myDataSet.Tables[0];
if (dt != null)
{
if (int.Parse(dt.Rows[0][0].ToString()) > 0)
{
uniqueContactNumber = false;
}
}
}
Here is the method of which the checkContactNumber method links to:
private void addEmployee_Click(object sender, EventArgs e)
{
string err = "";
if (addFirstName.Text.Trim() == "")
{
errorFirstName.Visible = true;
err += "Enter a value for First Name\r\n";
}
else if (!Regex.IsMatch(addFirstName.Text, #"^[a-zA-Z]+$"))//has numerical and has a value
{
errorFirstName.Visible = true;
err += "Enter a valid First Name\r\n";
}
else errorFirstName.Visible = false;
if (addLastName.Text.Trim() == "")
{
errorLastName.Visible = true;
err += "Enter a value for Last Name\r\n";
}
else if (!Regex.IsMatch(addLastName.Text, #"^[a-zA-Z]+$"))
{
errorLastName.Visible = true;
err += "Enter a valid Last Name\r\n";
}
else errorLastName.Visible = false;
if (addFirstName.Text.Trim() != "" && addLastName.Text.Trim() != "" && addFirstName.Text.Trim() == addLastName.Text.Trim())//identifies if FirstName + SecondName is equal to each other.
{
errorFirstName.Visible = true;
errorLastName.Visible = true;
err += "First Name and Second Name must be unique\r\n";
}
if (addRole.Text.Trim() == "")
{
errorRole.Visible = true;
err += "Select a Role type\r\n";
}
else errorRole.Visible = false;
if (!Regex.IsMatch(addContactNum.Text, #"^\d{11}$"))
{
errorContactNum.Visible = true;
err += "Enter a value for Contact Number\r\n";
}
else errorContactNum.Visible = false;
CheckContactNumber();
if(uniqueContactNumber == false && addContactNum.Text != "")
{
err += "Contact Number Already exist..\r\n";
errorContactNum.Visible = true;
}
if (err == "" && uniqueContactNumber == true)
{
string addEmployee = "INSERT INTO Employee (FirstName, LastName, Role, DateOfHire, ContactNumber)" +
"VALUES (#FirstName, #LastName, #Role, #DateOfHire, #ContactNumber)";
OleDbCommand cmd = new OleDbCommand(addEmployee, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = addFirstName.Text;
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = addLastName.Text;
cmd.Parameters.Add("#Role", OleDbType.VarChar).Value = addRole.Text;
cmd.Parameters.Add("#DateOfHire", OleDbType.VarChar).Value = addDateOfHire.Text;
cmd.Parameters.Add("#ContactNumber", OleDbType.VarChar).Value = addContactNum.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
//addFirstName.Text = String.Empty;
//addLastName.Text = String.Empty;
//addRole.Text = String.Empty;
//addContactNum.Text = String.Empty;
addRole.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
}
//Save It
else
{
MessageBox.Show(err);
}
}
Here is an example image showing that it can identify if there is duplicate data.
This shows that I have re-entered to make it unique but it still says it exists.
This shows that I have closed the program and ran it again using the same contact number in image 2 and it then saves.
If you click the addEmployee button when contact number is a duplicate uniqueContactNumber is set to false and a message box is shown. If you than change the contact number with a new one and click the button again the CheckContactNumber method does nothing leaving uniqueContactNumber with the value false.
You need to make sure to set uniqueContactNumber to true in that case.
You can fix it using the code below:
if (int.Parse(dt.Rows[0][0].ToString()) > 0)
{
uniqueContactNumber = false;
}
else
{
uniqueContactNumber = true;
}
I'd recommend that you add a UNIQUE constraint to Index which contains the ContactNumber field for the Employee table and that you catch the error thrown by MySQL when a record is inserted which violates that constraint.
The first two images I see appear to be identical (http://i.stack.imgur.com/a3WLr.png, http://i.stack.imgur.com/W2SoA.png)
The 3rd image (XOE0Q.png, sorry SO won't let me post another link) appears to have a different number than the above two.
Thus, I think your code is doing the right thing unless the 2nd image was an error. If a different number was typed in for image 2 vs image 1, then your form is probably not calling the validate method again, upon further input. To verify this, use the debugger and set a breakpoint inside your checkContactNumber method and verify that it's being called again. Which event is this method bound to on the contactNumber input?

How do I check if the record already exists in SQL database?

I am trying to check if the value exists in a database column. I know this question asked several times but none of them is solving my problem. I have tried it in many ways. Anyway my following code through an exception;
"An unhandled exception of type 'System.ArgumentException' occurred in
System.Data.dll Additional information: No mapping exists from
object type System.Windows.Forms.TextBox to a known managed provider
native type."
This problem is resolved of exception that was a mistake. but it still not working although the record is in database but it is not restricting me.
Can anyone tell me whats wrong with my code, the code is;
private void btn_Register_Click(object sender, EventArgs e)
{
lbl_Available.Visible = false;
lbl_Empty.Visible = false;
bool hasValue1 = string.IsNullOrWhiteSpace(txt_PinCode.Text);
bool hasValue2 = string.IsNullOrWhiteSpace(txt_Name.Text);
if (!hasValue1 && !hasValue2)
{
string pincode = txt_PinCode.Text;
if (UserExists(pincode))
{
lbl_Available.Visible = true;
return;
}
else
{
this.Hide();
RegCluePoint frm = new RegCluePoint();
frm.lbl_PinCode.Text = txt_PinCode.Text;
frm.lbl_Name.Text = txt_Name.Text;
frm.Show();
}
}
else
{
lbl_Empty.Visible = true;
}
}
private bool UserExists(string pincode)
{
//pincode = txt_PinCode.Text
//SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT PINCODE from UserInput where PINCODE = '#pincode'";
cmd.Parameters.AddWithValue("PINCODE", pincode);
if (conn.State != ConnectionState.Open)
conn.Open();
string pinString = (string)cmd.ExecuteScalar();
conn.Close();
return (pinString != null);
}
You are sending txt_PinCode, a textbox object instead of a string (txt_PinCode.Text) in this line cmd.Parameters.AddWithValue("PINCODE", txt_PinCode);
You are not passing the pincode that is passed to the method, instead you are passing the textbox itself (not even the value of the textbox).
private bool UserExists(string pincode)
{
//pincode = txt_PinCode.Text
//SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT PINCODE from UserInput where PINCODE = '#pincode'";
cmd.Parameters.AddWithValue("#pincode", pincode);
if (conn.State != ConnectionState.Open)
conn.Open();
//Execute scalar returns the first column of the first row in the result set
string pinString = (string)cmd.ExecuteScalar();
conn.Close();
return (pinString != null);
}
You are trying to pass the textbox itself, but not text. Change the code
cmd.Connection = conn;
cmd.CommandText = "SELECT PINCODE from UserInput where PINCODE = '#pincode'";
cmd.Parameters.AddWithValue("PINCODE", txt_PinCode.Text);
In this line of code you are sending the textbox object onstead of text.
cmd.Parameters.AddWithValue("PINCODE", txt_PinCode);
Change it to:
cmd.Parameters.AddWithValue("PINCODE", txt_PinCode.Text);

Why does disposing a SqlCeConnection both solve one exception and raise a different one?

When calling the same query method twice in a session of the app, I get "DBCommandExcept"
As an experiment, I decided to dispose of the connection object at the end of the method, to see if that was the problem.
I no longer get the DBCommandExcept err msg, but instead get, "the connectionstring property has not been initialized."
IOW, it's sort of a Catch-22 situation at the moment. The pertinent code is:
string query = "SELECT Bla FROM Blah";
SqlCeCommand cmd = new SqlCeCommand(query);
cmd.CommandType = CommandType.Text;
SqlCeConnection conn = dbconn.GetConnection();
cmd.CommandType = CommandType.Text;//probably unnecessary
cmd.Connection = conn;
SqlCeDataReader myReader = cmd.ExecuteReader(CommandBehavior.SingleRow);
try
{
if (myReader.Read())
{
itemID = myReader.GetString(ITEMID_INDEX);
packSize = myReader.GetString(PACKSIZE_INDEX);
recordFound = true;
}
}
catch (Exception ex)
{
RRDR.LogMsgs.Append(string.Format("Exception in PopulateControlsIfVendorItemsFound(): {0}", ex.Message));
}
finally
{
myReader.Close();
//if (null != conn)
//{
// conn.Dispose();
//}
}
// Re: the commented-out block above: When it is active, the DBCommandExcept problem is not seen; however, I then get, "the connectionstring property has not been initialized"
I think the only non-SQL-CE-standard bit above is the dbConn.GetConnection(). Here's some of that code:
SqlCeConnection objCon = null;
. . .
public SqlCeConnection GetConnection()
{
return objCon;
}
private DBConnection() // class constructor
{
try
{
. . .
objCon = new SqlCeConnection(conStr);
objCon.Open();
. . .
Again, the error (either one, whichever one I "choose" to have) is seen only the second time through this method during one run of the app. The first time works fine.
UPDATE
I added the code below, and the comments tell the tale of woe:
// With conn check only, still get two consecutive DBCommandExcepts
// With cmd check only, still get two consecutive DBCommandExcepts
// With both, still get two consecutive DBCommandExcepts; IOW, all have the same effect
if (null != conn)
{
conn.Close();
}
if (null != cmd)
{
cmd.Dispose();
}
UPDATE 2
Based on unicron's suggestion, I tried using "using."
In two of the three cases (SqlCeCommand and SqlCeDataReader), converting to "using" made no diff; in the other one (SqlCeConnection), it raised the err msgs, "The ConnectionString property has not been initialized."
Still, though, the code is cleaner with the two usings, so thanks for that nudge in the best practices direction.
Here's what it looks like now:
private bool PopulateControlsIfPlatypusItemsFound()
{
const int ITEMID_INDEX = 0;
const int PACKSIZE_INDEX = 1;
bool recordFound = false;
try
{
string PlatypusId = txtPlatypus.Text.ToString().Trim();
string PlatypusItemId = txtUPC.Text.ToString().Trim();
string itemID = string.Empty;
string packSize = string.Empty;
string query = string.Format("SELECT ItemID, PackSize FROM PlatypusItems WHERE PlatypusID = {0} AND PlatypusItemID = {1}", PlatypusId, PlatypusItemId);
using (SqlCeCommand cmd = new SqlCeCommand(query))
{
cmd.CommandType = CommandType.Text;
SqlCeConnection conn = dbconn.GetConnection();
if ((null != conn) && (!conn.State.Equals(ConnectionState.Open)))
{
conn.Open();
TTBT.LogMsgs.Append("Connection opened");
}
cmd.CommandType = CommandType.Text;//probably unnecessary
cmd.Connection = conn;
using (SqlCeDataReader myReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (myReader.Read())
{
itemID = myReader.GetString(ITEMID_INDEX);
packSize = myReader.GetString(PACKSIZE_INDEX);
recordFound = true;
}
}
txtID.Text = itemID;
txtSize.Text = packSize;
return recordFound;
}
}
catch (Exception ex)
{
TTBT.LogMsgs.Append(string.Format("Exception in PopulateControlsIfPlatypusItemsFound: {0} - {1}\r\n", ex.Message, ex.InnerException));
return recordFound;
}
}
UPDATE 3
I've come even closer to normalcy by replacing the custom connection code with the generic sort, adding another "using" to the mix:
private bool PopulateControlsIfVendorItemsFound()
{
const int ITEMID_INDEX = 0;
const int PACKSIZE_INDEX = 1;
bool recordFound = false;
DUCKBILL.LogMsgs.Append("Made it into frmEntry.PopulateControlsIfVendorItemsFound()\r\n");
try
{
string vendorId = txtVendor.Text.ToString().Trim();
string vendorItemId = txtUPC.Text.ToString().Trim();
string itemID = string.Empty;
string packSize = string.Empty;
if ( dbconn.isValidTable( "VendorItems" ) == -1 )
{
DUCKBILL.LogMsgs.Append("VendorItems not a valid table");//do not see this msg; good! VendorItems is seen as valid...
return false;
}
string query = string.Format("SELECT ItemID, PackSize FROM VendorItems WHERE VendorID = {0} AND VendorItemID = {1}", vendorId, vendorItemId);
using (SqlCeCommand cmd = new SqlCeCommand(query))
{
cmd.CommandType = CommandType.Text;
using (SqlCeConnection conn = new SqlCeConnection())
{
string filename = "\\badPlace2B\\CCRDB.SDF";
conn.ConnectionString = string.Format("Data Source = {0}", filename);
cmd.CommandType = CommandType.Text;//probably unnecessary/moot
cmd.Connection = conn;
conn.Open();
using (SqlCeDataReader myReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (myReader.Read())
{
itemID = myReader.GetString(ITEMID_INDEX);
packSize = myReader.GetString(PACKSIZE_INDEX);
recordFound = true;
}
}
}
txtID.Text = itemID;
txtSize.Text = packSize;
return recordFound;
}
}
catch (Exception ex)
{
DUCKBILL.LogMsgs.Append(string.Format("Exception in PopulateControlsIfVendorItemsFound: {0} - {1}\r\n", ex.Message, ex.InnerException));
return recordFound;
}
}
...yet I still get "DBCommandExcept"...
As to "stop futzing around with opening the connection," isn't it necessary to do so? How could/should the code above be different?
UPDATE 4
What is even more bizarre is that now my debug log file has stopped being written. I have been writing it out both in the global exception handler AND in the main form's Closed event(), and it always has (until now) at least a few entries, but within the last couple of updates to the code, it is no longer being written...????
Both places global exception handler and main form's Closed event(), the code is like so:
public static bool inDebugMode = true;
. . .
if (CCR.inDebugMode)
{
DateTime dt = DateTime.Now;
string timeAsStr = string.Format("{0}_{1}_{2}_{3}.txt", dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
using (StreamWriter file = new StreamWriter(timeAsStr))
{
// If the app closes normally, this is how the file is written; if it doesn't,
// (it crashed) it's written in PDAClient.ExceptionHandler()
file.WriteLine(SSCS.LogMsgs.ToString());
}
}
Since you are making several calls to a database file (that isn't going to change), I'd start out by defining your connection string and your SQL statements at the top of your class as global values:
private const int ITEMID_INDEX = 0;
private const int PACKSIZE_INDEX = 1;
private const string SQL_CONN_STR = "Data Source=\\badPlace2B\\CCRDB.SDF";
private const string SQL_GET_VENDOR_ITEMS = "SELECT ItemID, PackSize " +
"FROM VendorItems " +
"WHERE VendorID=#VendorID AND VendorItemID=#VendorItemID";
These never change, so there is no reason to define them again each time you call your routine.
Personally, I do not like inserting values into SQL statements, like you have shown. Rather, try to use Parameters.
To use Parameters, you'll need to look into your database to see what type of columns VendorID and VendorItemID are. My guess is that they are both int values, but these could be GUID like values, requiring VarChar type strings. If these are strings, you should write down what sizes the columns are defined as.
For example: Below, my Serial_Number column is the SqlDbType.NVarChar and the size is 50. An SqlCeParameter for this column would be:
cmd.Parameters.Add("#Serial_Number", SqlDbType.NVarChar, 50).Value = txtSerial_Number.Text.Trim();
Since I did not know what type of data you use, I created an enumerated type to show how each method would be used. If you do not have access to the table's design, the last resort is "AddWithValue" (I personally hate that one, because it makes me look like I don't know what my database has inside).
enum ParamStyle { AddWithValue, AddIntegers, AddVarChar }
To use this enumerated type, I modified the signature of your method to pass in that value:
private bool PopulateControlsIfVendorItemsFound(ParamStyle style) {
Obviously, you will not need this, because you should know what technique you are going to be coding with.
I wasn't able to figure out what your dbconn object was. Initially, I thought this was your SqlCeConnection, but that does not have an isValidTable method, so I just commented it out:
//if (dbconn.isValidTable("VendorItems") == -1) {
// DUCKBILL.LogMsgs.Append("VendorItems not a valid table");//do not see this msg; good! VendorItems is seen as valid...
// return false;
//}
Speaking of SqlCeConnection...
I combined your SqlCeCommand instance with your SqlCeConnection instance. Less code typically means fewer errors:
using (var cmd = new SqlCeCommand(SQL_GET_VENDOR_ITEMS, new SqlCeConnection(SQL_CONN_STR))) {
The CommandType, by default, is CommandType.Text, so this line is unnecessary:
// cmd.CommandType = CommandType.Text; (this is the default)
I moved most of your variable reading outside of the try/catch routine, as none of that should ever cause an exception to be generated.
Also, I used the more targeted SqlCeException instead of the general Exception. The only thing that could fail in the block is something SqlCe related, and the SqlCeException will give you better/more specific error messages than the general Exception object will.
} catch (SqlCeException err) {
So, what does it look like all put together?
Code:
enum ParamStyle { AddWithValue, AddIntegers, AddVarChar }
private const int ITEMID_INDEX = 0;
private const int PACKSIZE_INDEX = 1;
private const string SQL_CONN_STR = "Data Source=\\badPlace2B\\CCRDB.SDF";
private const string SQL_GET_VENDOR_ITEMS = "SELECT ItemID, PackSize FROM VendorItems WHERE VendorID=#VendorID AND VendorItemID=#VendorItemID";
private bool PopulateControlsIfVendorItemsFound(ParamStyle style) {
bool recordFound = false;
//DUCKBILL.LogMsgs.Append("Made it into frmEntry.PopulateControlsIfVendorItemsFound()\r\n");
string itemID = null;
string packSize = null;
//string vendorId = txtVendor.Text.Trim();
//string vendorItemId = txtUPC.Text.Trim();
//string query = string.Format("SELECT ItemID, PackSize FROM VendorItems WHERE VendorID = {0} AND VendorItemID = {1}", vendorId, vendorItemId);
//if (dbconn.isValidTable("VendorItems") == -1) {
// DUCKBILL.LogMsgs.Append("VendorItems not a valid table");//do not see this msg; good! VendorItems is seen as valid...
// return false;
//}
using (var cmd = new SqlCeCommand(SQL_GET_VENDOR_ITEMS, new SqlCeConnection(SQL_CONN_STR))) {
// cmd.CommandType = CommandType.Text; (this is the default)
if (style == ParamStyle.AddIntegers) { // Adding Integers:
cmd.Parameters.Add("#VendorID", SqlDbType.Int).Value = Convert.ToInt32(txtVendor.Text.Trim());
cmd.Parameters.Add("#VendorItemID", SqlDbType.Int).Value = Convert.ToInt32(txtUPC.Text.Trim());
} else if (style == ParamStyle.AddVarChar) { // Adding String Values
// NOTE: Here, you should look in your database table and
// use the size you defined for your VendorID and VendorItemID columns.
cmd.Parameters.Add("#VendorID", SqlDbType.VarChar, 25).Value = txtVendor.Text.Trim();
cmd.Parameters.Add("#VendorItemID", SqlDbType.VarChar, 50).Value = txtUPC.Text.Trim();
} else if (style == ParamStyle.AddWithValue) { // Adding as Objects (only if you don't know what the data types are)
cmd.Parameters.AddWithValue("#VendorID", txtVendor.Text.Trim());
cmd.Parameters.AddWithValue("#VendorItemID", txtUPC.Text.Trim());
}
try {
cmd.Connection.Open();
using (var myReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) {
if (myReader.Read()) {
itemID = myReader.GetString(ITEMID_INDEX);
packSize = myReader.GetString(PACKSIZE_INDEX);
recordFound = true;
}
}
} catch (SqlCeException err) {
//DUCKBILL.LogMsgs.Append(string.Format("Exception in PopulateControlsIfVendorItemsFound: {0}\r\n", err.Message));
// (I never return from a 'catch' statement) return recordFound;
} finally {
if (cmd.Connection.State == ConnectionState.Open) {
cmd.Connection.Close();
}
}
}
if (recordFound) { // set these last, and set them OUTSIDE of the try/catch block
txtID.Text = itemID;
txtSize.Text = packSize;
}
return recordFound;
}
Happy Coding!

Categories

Resources