【发布时间】:2018-09-14 14:21:30
【问题描述】:
在这些代码下方,我在增加数据库列“SupplierID”中的字符串值时得到了错误的输出。我在 ADDSupplier 表单中将字符串值传输到我的 lbl_id,这就是我用来将值插入到我的“SupplierID”的内容。
期望的输出:
- SPPL-0001
- SPPL-0002
- SPPL-0003
等
当前输出(在这些代码下方):
- SPPL-0001
- SPPL-00012
- SPPL-00013
等等
注意:当我重复插入数据时,我得到了上面所说的当前输出,但是当我重新启动程序和最后插入的值时,例如是 SPPL-00013。当我打开我的添加表单时,lbl_id 将 id 显示为 SPPL-0004。如果我继续,它会变成 SPPL-00045。
PS:SupplierID 在我的数据库中是 varchar(50),也是 PRIMARY_KEY
These image shows the wrong output of mine
我想要获得帮助的是纠正我的逻辑并获得所需的输出。请帮我。谢谢
public partial class SIMSSupplier : UserControl
{
ADDSupplier supply;
public SIMSSupplier()
{
InitializeComponent();
}
public string ID = "SPPL-000";
public void GenerateAutoID()
{
using (var con = SQLConnection.GetConnection())
{
using (var select = new SqlCommand("Select Count(SupplierID) from admin_supplier", con))
{
int i = Convert.ToInt32(select.ExecuteScalar());
i++;
supply.lbl_id.Text = ID + i.ToString();
}
}
}
private void btn_register_Click(object sender, EventArgs e)
{
supply = new ADDSupplier(this);
supply.Show();
GenerateAutoID();
}
}
public partial class ADDSupplier : MetroForm
{
SIMSSupplier _view;
public ADDSupplier(SIMSSupplier _view)
{
InitializeComponent();
this._view = _view;
}
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
private void btn_ok_Click(object sender, EventArgs e)
{
_view.ID = lbl_id.Text;
using (var con = SQLConnection.GetConnection())
{
if (string.IsNullOrEmpty(txt_name.Text) || string.IsNullOrEmpty(txt_contact.Text) || string.IsNullOrEmpty(cbox_remark.Text) || string.IsNullOrEmpty(txt_address.Text))
{
CustomNotifcation.Show("Please input the required fields", CustomNotifcation.AlertType.warning);
}
else
{
using (var select = new SqlCommand("Insert into admin_supplier (SupplierID, Companyname, Contactnumber, Date, Remarks, Address) Values (@SupplierID, @Companyname, @Contactnumber, @Date, @Remarks, @Address)", con))
{
select.Parameters.Add("@SupplierID", SqlDbType.VarChar).Value = lbl_id.Text;
select.Parameters.Add("@Companyname", SqlDbType.VarChar).Value = txt_name.Text;
select.Parameters.Add("@Contactnumber", SqlDbType.VarChar).Value = txt_contact.Text;
select.Parameters.Add("@Date", SqlDbType.VarChar).Value = date;
select.Parameters.Add("@Remarks", SqlDbType.VarChar).Value = cbox_remark.Text;
select.Parameters.Add("@Address", SqlDbType.VarChar).Value = txt_address.Text;
select.ExecuteNonQuery();
CustomMessage.Show("Message: Supplier successfully added!", CustomMessage.Messagetype.Success2);
_view._Supplier();
}
}
}
}
}
【问题讨论】:
-
supply.lbl_id.Text = "SPPL-" + i.ToString("0000");怎么样?或者在较新的版本中:supply.lbl_id.Text = $"SPPL-{i:0000}";-- 另请参阅:custom numeric format -
不过,一旦您在该表中有 10000 多个项目,您就会遇到类似的问题。 ^_^
-
你的设计很有问题。当您获得 10,000 行时会发生什么?突然间你的逻辑被打破了。我会使用身份列而不是滚动你自己的列。如果您想将该前缀添加到开头,请创建一个计算列。
-
让数据库为你做
auto increment。如果每一行都有SPPL-作为前缀,那么它仍然是多余的。使用数字类型并将其(前缀)添加到未映射的属性中,或者仅将其添加到您的视图中(如果相关)。 -
好吧,如果你在上面加上相同的前缀,那并不能完全帮助唯一性,它只是在开头打了几个字符。任何你自己的身份类型都充满了问题。
标签: c# sql-server winforms