我正在编写桌面应用程序。在一个表单中,我从数据库表中获取最大日期并填入文本框(tbdate)。现在我有另一个文本框(tbvouch),它将获得最大的vouchernumber + 1,其中date = tbdate。用户也可以自己输入日期。
现在如果该日期出现在表格中,那么它必须选择最大值vouchernumber +1。另外,它默认将凭证号码设为5001。
以上逻辑我正在放置文本框(tbvouch)的ENTER事件。我的代码是
private void tbvouch_Enter(object sender, EventArgs e)
{
DateTime d = Convert.ToDateTime(tbdate.Text);
int vcnum;
SqlConnection c = new SqlConnection();
c.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='D:\\Documents\\Visual Studio 2008\\Projects\\Accounts\\Accounts\\Database1.mdf';Integrated Security=True;User Instance=True";
c.Open();
string q = "select max(vc_number) from lgr where date = '"+d+"' ";
SqlCommand cmd = new SqlCommand(q, c);
SqlDataReader rd = cmd.ExecuteReader();
try
{
if (rd.Read())
{
int val = rd.GetInt32(0);
if (val != 0)
{
vcnum = val + 1;
tbvouch.Text = vcnum.ToString();
}
}
}
catch (Exception ex)
{
tbvouch.Text = "05001";
}
}
答案 0 :(得分:3)
private void tbvouch_Enter(object sender, EventArgs e)
{
DateTime d = Convert.ToDateTime(tbdate.Text);
int vcnum;
SqlConnection c = new SqlConnection();
c.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='D:\\Documents\\Visual Studio 2008\\Projects\\Accounts\\Accounts\\Database1.mdf';Integrated Security=True;User Instance=True";
c.Open();
string q = "IF EXISTS(SELECT 1 FROM lgr WHERE date = @date)
BEGIN
select max(vc_number)+1 from lgr where date = @date
END
ELSE
BEGIN SELECT 05001 END";
using (var cmd = new SqlCommand(q, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = d;
vcum = (int)cmd.ExecuteScalar();
}
}