c# - 如何使用 c# Winforms 执行字符串和整数?

标签 c# winforms ms-access

在我的发票表单中,我有 textEdit1,它会在第一次显示 "INV001"。然后我们将该发票表单详细信息存储到 MS Access 数据库中。下次 textEdit1 会自动显示下一个发票编号,例如 "INV002"。如何执行此操作?

如果它只是数字,我试过此代码成功运行,但现在我也有 3 个字母,那么如何执行此操作?

OleDbConnection con =
    new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/Srihari/Srihari/Invoice.accdb");
con.Open();

OleDbCommand cmd =
    new OleDbCommand(
        "SELECT * FROM NewInvoice_1 WHERE InvoiceNumber = (select max(InvoiceNumber) from NewInvoice_1)",
        con);

OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
    int a = reader.GetInt32(1);
    TXE_Invoice_Number.Text = (1 + a).ToString();
}

最佳答案

我会在数据库中存储 int 而不是 string:

using(var con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/Srihari/Srihari/Invoice.accdb"))
using(var cmd = new OleDbCommand("SELECT MAX(InvoiceNumber) from NewInvoice_1", con))
{
    con.Open();
    int max = 0;
    object objMax = cmd.ExecuteScalar();
    if(objMax != null) max = (int) objMax;
    int newMax = max++; // insert this into the database instead of the string "INV001"
    // you can use newMax.ToString("000") or ToString("D3") or ToString().PadLeft(3, '0')
    string newNumber = string.Format("INV{0}", newMax.ToString().PadLeft(3, '0'));
    // ...
}

如果您坚持使用 string 和这种模式 "INV001":

string maxStr = (string)cmd.ExecuteScalar() ?? "INV0";
int newMax = int.Parse(maxStr.Substring(3)) + 1;
string newNumber = string.Format("INV{0}", newMax.ToString().PadLeft(3, '0'));

在这个 Substring 方法中,是否有前导零并不重要。

关于c# - 如何使用 c# Winforms 执行字符串和整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21252546/

相关文章:

c# - 如何在 wpf 中的 ItemsPanelTemplate 中找到控件?

c# - c# winForms 列表数组的奇怪结果

excel - 奇怪的 Excel 格式

c# - asp.net如何区分服务器端的并发进度条请求

c# - 将 DataGridView 单元格多选限制为仅列或行

c# - GMap - 无法检测到点击多边形

c# - 使用 C# 获取目录中带有 *.tif 文件掩码的文件

forms - 如何在运行时将 Microsoft Access 表单 View 从单一表单更改为连续表单?

xml - 将 XML 导入到 MS Access 2003 时, bool 变量被作为字符串导入

c# - 在 C# 中从字符串到日期时间的转换