Convert string to smalldatetime before a database insert - c#

I have everything inserting fine until I try to insert a string "09/21/3013" into the ArrivalDate column which is a smalldatetime. How do I convert this so I can insert into the database? Thanks in advance!
Here's the code:
private void ExecuteInsert(string BookingName, string BookedBy)
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string sql = "INSERT INTO tbBooking (BookingName, BookedBy, ArrivalDate) VALUES "
+ " (#BookingName, #BookedBy, #ArrivalDate)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
//param[0] = new SqlParameter("#id", SqlDbType.Int, 20);
param[0] = new SqlParameter("#BookingName", System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#BookedBy", System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#ArrivalDate", System.Data.SqlDbType.SmallDateTime);
param[0].Value = BookingName;
param[1].Value = BookedBy;
param[2].Value = ArrivalDate;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void BtnCatering_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//call the method to execute insert to the database
ExecuteInsert(BookingName.Text, BookedBy.Text);
Response.Write("Record was successfully added!");
}
}

if (ArrivalDate != DBNull.Value)
param[2].Value = Convert.ToDateTime(ArrivalDate);
else
{
param[2].Value = // default value
}

You may try to use DateTime instead of String.
param[2].Value = Convert.ToDateTime(ArrivalDate);

Using DateTime.ParseExact will allow you to control the exact conversion of your date:
CultureInfo provider = CultureInfo.InvariantCulture;
param[2].Value = DateTime.ParseExact(ArrivalDate, "MM/dd/yyyy hh:mm:ss tt", provider);

Related

How to correct error "string was not recognized as a valid DateTime" when executing program?

How to correct this error "String was not recognized as a valid DateTime"?
The error happens when trying to save the data
tried something like this with no luck as well("Checkin_Time"):
"this.Text="1/01/2019";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);"
Changed the approach to a more simplified way of sorts...
Thank you
try
{
string thisDay1 = DateTime.Now.ToString();
Bitmap bm = new Bitmap(UpdateName);
OleDbCommand cmd = new OleDbCommand("INSERT INTO [IMGs] (UPC, Checkin_Time, Photo) values (?, ?, ?)", Conn);
byte[] image_bytes = ImageToBytes(bm, ImageFormat.Png);
OleDbParameter param = new OleDbParameter();
param.OleDbType = OleDbType.Binary;
param.ParameterName = "Image";
param.Value = image_bytes;
cmd.Parameters.Add(param);
OleDbParameter param1 = new OleDbParameter();
param1.OleDbType = OleDbType.VarChar;
param1.ParameterName = "UPC";
param1.Value = textBox1.Text;
cmd.Parameters.Add(param1);
OleDbParameter param2 = new OleDbParameter();
DateTime date = DateTime.ParseExact(DateTime.Now.ToString(),"yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
param2.OleDbType = OleDbType.DBTime;//
param2.ParameterName = "Checkin_Time";
param2.Value = date;//TRIED USING THE "thisDay1" DIRECTLY & GOT SAME ERROR|FIELD IN DB IS SET AS Date/Time
cmd.Parameters.Add(param2);
// Execute the command (with no return value).
cmd.Connection = Conn;
Conn.Open();
cmd.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (Conn.State != ConnectionState.Closed) Conn.Close();
}
Your string provider should be like this :
OleDbConnection con1 = new OleDbConnection(#" provider=Microsoft.ace.Oledb.12.0; data source=C:\fotos\IMRDATABASE.accdb; Persist Security Info=False");
for more information about connection strings see this

MVC: second parameter for SqlCommand appearing as Null in Database

I can't figure out why my second parameter (NotifyDateParameter) for my SqlCommand isn't working properly. It does not give an error, but it appears as null in my SQL Server database. The first parameter (StringParameter) appears just as intended. I could use some of your expertise right about now.
try
{
{
string connstr = #"Server=.\SQLEXPRESS;Database=ImageDB;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string query;
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[upload].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[upload].ContentLength);
}
query = "insert into Images(ImageData, NotifyDate) values(#ImageData, #NotifyDate)";
SqlParameter StringParameter = new SqlParameter();
StringParameter.SqlDbType = SqlDbType.VarBinary;
StringParameter.ParameterName = "ImageData";
StringParameter.Value = fileData;
DateTime today = DateTime.Now;
DateTime notifyDate = today.AddDays(1);
//string notifyDateString = notifyDate.ToString();
SqlParameter NotifyDateParameter = new SqlParameter();
NotifyDateParameter.SqlDbType = SqlDbType.DateTime;
NotifyDateParameter.ParameterName = "NotifyDate";
NotifyDateParameter.Value = notifyDate;
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(StringParameter);
cmd.Parameters.Add(NotifyDateParameter);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
conn.Dispose();
}
}
catch (Exception e)
{
string exceptionCause = String.Format("An error occurred: '{0}'", e);
System.IO.File.WriteAllText(#"C:\Users\Nathan\Documents\Visual Studio 2013\Projects\MVCImageUpload\uploads\exception.txt", exceptionCause);
}
Well for starters do try 2 things
Replace NotifyDateParameter.ParameterName = "NotifyDate"; with NotifyDateParameter.ParameterName = "#NotifyDate"; // #added to parameter name.
Check if parameter type is SqlDbType.DateTime or SqlDbType.Date

Error/exception handling (try-catch) C#

How to achieve the requirements below:
The Retrieve button click event:
if user doesn't enter CustID in txtCustID need to inform them to enter Customer Id via lblMessage;
if entered CustId doesn't exist in database inform user that it doesn't exist via lblMessage.
The Update button click event - need to ensure that Customer ID already exists in the database.
The Delete button click event: same requirements as for Retrieve button.
I must use error/exception handling (try-catch) to achieve these (project requirement). I spent hours trying, but no success. I would be very grateful for some help! My code is below:
namespace ACME
{
public partial class Customer : System.Web.UI.Page
{
SqlConnection conn;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
SqlCommand command = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
}
private void Page_PreInit(object sender, EventArgs e)
{
HttpCookie setTheme = Request.Cookies.Get("UserSelectedTheme");
if (setTheme != null)
{
Page.Theme = setTheme.Value;
}
}
protected void Clear()
{
txtCustID.Text = "";
txtFirstname.Text = "";
txtSurname.Text = "";
rbtGender.SelectedValue = "";
txtAge.Text = "";
txtAddress1.Text = "";
txtAddress2.Text = "";
txtCity.Text = "";
txtPhone.Text = "";
txtMobile.Text = "";
txtEmail.Text = "";
txtEmail2.Text = "";
}
protected void btnNew_Click(object sender, EventArgs e)
{
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataTable table1 = new DataTable();
SqlCommand command1 = new SqlCommand();
Clear();
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
command1.Connection = conn;
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "LargestCustID";
command1.Connection.Open();
int id = (int)command1.ExecuteScalar() + 1;
txtCustID.Text = id.ToString();
command1.Dispose();
conn.Close();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "AddCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
lblMessage.Text = "The new record has been added to the database!";
command.Connection.Close();
Clear();
}
protected void btnRetrieve_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustID";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
int id = table.Rows.Count;
if (id == 0)
{
lblMessage.Text = "Customer ID does not exists!";
}
else
{
lblMessage.Text = "";
txtFirstname.Text = table.Rows[0].Field<string>("Firstname");
txtFirstname.DataBind();
txtSurname.Text = table.Rows[0].Field<string>("Surname");
txtSurname.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAddress1.Text = table.Rows[0].Field<string>("Address1");
txtAddress1.DataBind();
txtAddress2.Text = table.Rows[0].Field<string>("Address2");
txtAddress2.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City");
txtCity.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone");
txtPhone.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile");
txtMobile.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email");
txtEmail.DataBind();
}
command.Connection.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
lblMessage.Text = "The record has been updated!";
command.Connection.Close();
Clear();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "DeleteCustomer";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = (int)param.Value;
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text += "Please enter Customer ID!";
}
try
{
lblMessage.Text = "";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = table.Rows.Count;
id = (int)param.Value;
lblMessage.Text += "Customer record has been deleted";
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text = "Customer ID doesnot exists!";
}
Clear();
}
public string CustID { get; set; }
}
}
It sounds like you are trying to control flow of your application by use of exceptions. There are many reasons against this approach:
1) Code is difficult to understand and to debug.
2) Throwing exceptions in .Net is expensive.
3) If exception control flow of application how do you differentiate them from a real exceptions (thrown when something doesn't work as expected)?
If, on the other hand, you want to throw an exception when any of the scenarios you listed in the question happens then you can use standard .Net Exception class:
if (string.IsNullOrWhiteSpace(txtCustID.Text))
{
throw new Exception("Id not provided.");
}
Or you can create a custom exception to provide some more specific information:
public class IdNotProvidedException : Exception
{
public string MyCommandName { get; set; }
public IdNotProvidedException(string msg)
: base(msg)
{
}
public IdNotProvidedException(string msg, string myCommandName)
: base(msg)
{
this.MyCommandName = myCommandName;
}
}
And then you initialize and throw your custom exception.
Lastly, there are already places in your code, though not mentioned in your question, that are worth wrapping in a try...catch block. Basically, any place where you connect with the server may result in something unexpected (for instance, the server may not be available).

Trying to Insert Values into a Database from TextBoxes

I am totally stumped on this one, and I'm brand new to C# so maybe one of you fine folks can help me out. I'm trying to update a database from form fields using ADO.NET.
Basically, the error I'm getting is that I am trying to insert null values into the database. The exact text of the error is:
System.ArgumentNullException: The SqlParameterCollection only accepts non-null SqlParameter type objects.
Here is the code behind for the page I am trying to use:
private void ExecuteInsert(string firstName, string lastName, string emailAddress, string city, string phone)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO contactInfo (firstName, lastName, emailAddress, city, phone) VALUES "
+ " (#firstName, #lastName, #emailAddress, #city, #phone)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[6];
param[0] = new SqlParameter("#firstName", SqlDbType.NVarChar, 25);
param[1] = new SqlParameter("#lastName", SqlDbType.NVarChar, 25);
param[2] = new SqlParameter("#emailAddress", SqlDbType.NVarChar, 30);
param[3] = new SqlParameter("#city", SqlDbType.NVarChar, 50);
param[4] = new SqlParameter("#phone", SqlDbType.Int, 10);
param[0].Value = firstName;
param[1].Value = lastName;
param[2].Value = emailAddress;
param[3].Value = city;
param[4].Value = phone;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (firstName.Text != null)
{
//call the method to execute insert to the database
ExecuteInsert(firstName.Text,
lastName.Text,
emailAddress.Text,
city.Text,
phone.Text);
Response.Write("Record was successfully added!");
ClearControls(Page);
}
else
{
Response.Write("Please enter your name");
}
}
public static void ClearControls(Control Parent)
{
if (Parent is TextBox)
{ (Parent as TextBox).Text = string.Empty; }
else
{
foreach (Control c in Parent.Controls)
ClearControls(c);
}
}
If there is another way that I should be doing this, I would love to hear it. I just can't seem to find good information online.
This line:
SqlParameter[] param = new SqlParameter[6];
Should be (array is too big and you don't set last parameter):
SqlParameter[] param = new SqlParameter[5];
Change
SqlParameter[] param = new SqlParameter[6];
to
SqlParameter[] param = new SqlParameter[5];
You can add your parameters directly to cmd.Parameters without creating temp array.

Saving ID to database based on dropdown selection

I am using the following code to bind BusinessID as the DataValueField of the ddlIndustry dropdown. What I want to do is save the selected ID to a different table (Company). I am doing this with ddlIndustry.SelectedValue. For some reason, the first value is always saved (1), and not the selected value. Do you have any ideas as to why this might be happening?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindCountry();
BindIndustry();
}
private void BindCountry()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("countries.xml"));
foreach (XmlNode node in doc.SelectNodes("//country"))
{
ddlCountry.Items.Add(new ListItem(node.InnerText, node.Attributes["code"].InnerText));
ddlCountry.SelectedIndex = 94;
}
}
private void BindIndustry()
{
SqlCommand cmd = null;
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
cmd = new SqlCommand("Select Industry, BusinessID FROM BusinessType", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
ddlIndustry.DataSource = ds;
ddlIndustry.DataTextField = "Industry";
ddlIndustry.DataValueField = "BusinessID";
ddlIndustry.DataBind();
//ddlIndustry.Items.Insert(0, new System.Web.UI.WebControls.ListItem("-- Please Select Industry --", "0"));
}
private void ExecuteCompanyDetailsInsert()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO Company (BusinessID, CompanyName, Email, AddressLine1, AddressLine2, Location, Telephone) VALUES "
+ " (#BusinessID, #CompanyName, #Email, #AddressLine1, #AddressLine2, #Location, #Telephone)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[7];
param[0] = new SqlParameter("#BusinessID", SqlDbType.Int);
param[1] = new SqlParameter("#CompanyName", SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#Email", SqlDbType.VarChar, 50);
param[3] = new SqlParameter("#AddressLine1", SqlDbType.VarChar, 50);
param[4] = new SqlParameter("#AddressLine2", SqlDbType.VarChar, 50);
param[5] = new SqlParameter("#Location", SqlDbType.VarChar, 50);
param[6] = new SqlParameter("#Telephone", SqlDbType.VarChar, 50);
param[0].Value = ddlIndustry.SelectedValue;
param[1].Value = company_name.Text;
param[2].Value = company_email.Text;
param[3].Value = address_line_1.Text;
param[4].Value = address_line_2.Text;
param[5].Value = ddlCountry.SelectedItem.Text;
param[6].Value = telephone.Text;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
First of all modify this code, because when your page is postback to server, your industry dropdown bind again and your selected value lost
if (!Page.IsPostBack)
{
BindCountry();
BindIndustry();
}
and then you can get selected value
ddlIndustry.SelectedValue

Categories