Visual C#2008Express。2010データベースにアクセスします。次のコードを使用すると、「基準式のデータ型の不一致」というエラーが表示されますが、txt85x11bw_Validatingイベントのコードを取得すると、問題なく機能します。日付型の不一致がどのようにあるかを理解しようとしています。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace GISReciepts
{
public partial class GISReceipts : Form
{
public GISReceipts()
{
InitializeComponent();
}
private void cmdExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void cmdAdd_Click(object sender, EventArgs e)
{
string strSQL = "INSERT INTO Table1(Name1, Date1, CollectedBy, 85x11BW) VALUES(@Name, @Date, @CollectedBy, @85x11BW)";
//OleDbConnection is a class that represents an open connection to a data source
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Temp\\GISTest.accdb");
//OleDbCommand is a class that represents an SQL statement or stored procedure to execute against a data source.(takes care of passing queries to the database.
OleDbCommand myCommand = new OleDbCommand(strSQL, myConnection);
myCommand.Parameters.AddWithValue("@Name", txtName.Text);
myCommand.Parameters.AddWithValue("@Date", maskedTextBoxDate.Text);
myCommand.Parameters.AddWithValue("@CollectedBy", txtCollectedBy.Text);
myCommand.Parameters.AddWithValue("@85x11BW", txt85x11bw.Text);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
myConnection.Close();
// MessageBox.Show("Entry Added"); //this is displaying even on errors & when no data is added to table
}
}
private void GISReceipts_Load(object sender, EventArgs e)
{
maskedTextBoxDate.Text = DateTime.Today.ToString("MM/dd/yyyy");
txt85x11bw.Validating += new CancelEventHandler(txt85x11bw_Validating);
}
private void GISReceipts_FormClosing(object sender, FormClosingEventArgs e)
{
DateTime value;
//DateTime.TryParse converts the srting representation of a date to its DateTime equivalent & returns a value that indicates whether the conversion succedded.
if (!DateTime.TryParse(maskedTextBoxDate.Text, out value))
{
maskedTextBoxDate.Text = DateTime.Today.ToShortDateString();
}
}
private void txt85x11bw_Validating(object sender, CancelEventArgs e)
{
if (string.IsNullOrEmpty(txt85x11bw.Text))
{
//do nothing
}
else
{
//initialize the variable numberEntered of type int
int numberEntered;
//int=integer TryParse=method that converts strings into integer (value, out result)
if (int.TryParse(txt85x11bw.Text, out numberEntered))
{
//if number is less than 1 or more than 1,000
if (numberEntered < 1 || numberEntered > 1000)
MessageBox.Show("You must enter a valid number");
txt85x11bw.Clear();
}
//if conversion failed
else
{
MessageBox.Show("You must enter a number");
txt85x11bw.Clear();
}
}
}
}
}