首页 > 解决方案 > 为什么我添加新用户的代码不起作用,它只读取用于检查 ID 是否存在于数据库中的代码?

问题描述

当我尝试在数据库中添加新用户时,它只会读取检查 ID 的代码(如果它存在于数据库中)。我应该如何处理我的代码?

我还没有尝试其他代码,因为我找不到一个,所以任何帮助将不胜感激。

private void btnAdd_Click(object sender, EventArgs e)
{
    if (txtSupID.Text == "" || txtName.Text == "" || txtAddress.Text == "" || txtContactNum.Text == "")
    {
        MessageBox.Show("Please fill out the required fields", "Required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
    else
    {
        string checkID = "SELECT SupplierID FROM Suppliers WHERE SupplierID = @SupplyID";
        cmd.CommandText = checkID;
        cmd.Connection = con;
        cmd.Parameters.AddWithValue("@SupplyID", txtSupID.Text);
        adapt.InsertCommand = cmd;
        cmd.Parameters.Clear();
        adapt.Fill(ds);
        int i = ds.Tables[0].Rows.Count;

        if (i > 0)
        {
            ds.Clear();
            MessageBox.Show("Supplier ID " + txtSupID.Text + " already exist", "Invalid", MessageBoxButtons.OK,
            MessageBoxIcon.Exclamation);
        }
        else
        {
            try
            {
                con.Open();

                string insert = "INSERT INTO Suppliers (SupplierID, Name, Address, ContactNumber, Email, Notes) VALUES(@SID,
@name, @address, @contactnum, @email, @notes)";
cmd.CommandText = insert;

                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@SID", txtSupID.Text);
                cmd.Parameters.AddWithValue("@name", txtName.Text);
                cmd.Parameters.AddWithValue("@address", txtAddress.Text);
                cmd.Parameters.AddWithValue("@contactnum", txtContactNum.Text);
                cmd.Parameters.AddWithValue("@email", txtEmail.Text);
                cmd.Parameters.AddWithValue("@notes", txtNotes.Text);
                cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                GetData();

                dtgSuppliers.Refresh();

                MessageBox.Show("Successfully added a new Supplier", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

                ClearAll();

                con.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

标签: c#

解决方案


推荐阅读