Click here to Skip to main content
15,920,676 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys, I'm creating a software to help me out on my gym and I want to add a plan to a client, but when I add it it gives me this error "string or data would be truncated".


This is the code i actually have for the save button.

C#
try
{
    if (txtMemberName.Text == "")
    {
        MessageBox.Show("Introduza os dados de cliente", "",
        MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtMemberName.Focus();
        return;
    }
    if (txtMonths.Text == "")
    {
        MessageBox.Show("Introduza o tempo de subscrição (meses)", "",
        MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtMonths.Focus();
        return;
    }
    if (cmbMembershipType.Text == "")
    {
        MessageBox.Show("Escolha o tipo de plano", "",
        MessageBoxButtons.OK, MessageBoxIcon.Warning);
        cmbMembershipType.Focus();
        return;
    }
    if (txtDiscountPer.Text == "")
    {
        MessageBox.Show("Introduza o desconto", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtDiscountPer.Focus();
        return;
    }
    if (txtTotalPaid.Text == "")
    {
        MessageBox.Show("Introduza o valor pago", "",
        MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtTotalPaid.Focus();
        return;
    }
    double val1 = 0;
    double val2 = 0;
    double.TryParse(txtGrandTotal.Text, out val1);
    double.TryParse(txtTotalPaid.Text, out val2);
    if (val2 > val1)
    {
        MessageBox.Show("O total não pode ser maior do que o valor pago", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
        txtTotalPaid.Text = "";
        txtTotalPaid.Focus();
        return;

    }
    cc.con = new SqlConnection(cs.DBConn);
    cc.con.Open();
    string ct = "SELECT * FROM CustomerMembership WHERE DateFrom <= '" + dtpDateTo.Value.Date + "' AND DateTo >= '" + dtpDateFrom.Value.Date + "' and CustomerID=" + txtM_ID.Text + "";
    cc.cmd = new SqlCommand(ct);
    cc.cmd.Connection = cc.con;
    cc.rdr = cc.cmd.ExecuteReader();
    if (cc.rdr.Read())
    {
        MessageBox.Show("A mensalidade ainda não expirou.." + "\n" + "O pagamento não é permitido", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        if ((cc.rdr != null))
        {
            cc.rdr.Close();
        }
        return;
    }
    cc.con = new SqlConnection(cs.DBConn);
    cc.con.Open();
    string cb = "insert into CustomerMembership(CM_ID,BillDate,CustomerID,MembershipID,DateFrom,Months,DateTo,ChargesPerMonth,TotalCharges,DiscountPer,DiscountAmount,SubTotal,VATPer,VATAmount,ServiceTaxPer,ServiceTaxAmount,GrandTotal,TotalPaid) VALUES (@d1,@d2,@d3,@d4,@d5,@d6,@d7,@d8,@d9,@d10,@d11,@d12,@d13,@d14,@d15,@d16,@d17,@d18)";
    cc.cmd = new SqlCommand(cb);
    cc.cmd.Connection = cc.con;
    cc.cmd.Parameters.AddWithValue("@d1",txtMembershipID.Text);
    cc.cmd.Parameters.AddWithValue("@d2",dtpBillDate.Value);
    cc.cmd.Parameters.AddWithValue("@d3",txtM_ID.Text);
    cc.cmd.Parameters.AddWithValue("@d4", txtMembershipTypeID.Text);
    cc.cmd.Parameters.AddWithValue("@d5", dtpDateFrom.Value);
    cc.cmd.Parameters.AddWithValue("@d6", txtMonths.Text);
    cc.cmd.Parameters.AddWithValue("@d7", dtpDateTo.Value);
    cc.cmd.Parameters.AddWithValue("@d8", txtChargesPerMonth.Text);
    cc.cmd.Parameters.AddWithValue("@d9", txtTotalCharges.Text);
    cc.cmd.Parameters.AddWithValue("@d10",txtDiscountPer.Text);
    cc.cmd.Parameters.AddWithValue("@d11",txtDiscountAmount.Text);
    cc.cmd.Parameters.AddWithValue("@d12",txtSubTotal.Text);
    cc.cmd.Parameters.AddWithValue("@d13", txtVATPer.Text);
    cc.cmd.Parameters.AddWithValue("@d14", txtVATAmount.Text);
    cc.cmd.Parameters.AddWithValue("@d15", txtServiceTaxPer.Text);
    cc.cmd.Parameters.AddWithValue("@d16", txtServiceTaxAmount.Text);
    cc.cmd.Parameters.AddWithValue("@d17", txtGrandTotal.Text);
    cc.cmd.Parameters.AddWithValue("@d18", txtTotalPaid.Text);
    cc.cmd.ExecuteReader();
    cc.con.Close();
    st1 = lblUser.Text;
    st2 = "Foi adicionada uma nova mensalidade com o id '" + txtMembershipID.Text + "' ao membro '" + txtMemberName.Text + "'";
    cf.LogFunc(st1, System.DateTime.Now, st2);
    btnSave.Enabled = false;
    MessageBox.Show("Gravado com sucesso", "Registo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}


Sql table:
SQL
CREATE TABLE [dbo].[CustomerMembership] (
    [CM_ID]            INT            NOT NULL,
    [CustomerID]       INT             NOT NULL,
    [MembershipID]     INT             NOT NULL,
    [DateFrom]         DATETIME        NOT NULL,
    [Months]           VARCHAR (2)     NOT NULL,
    [DateTo]           DATETIME        NOT NULL,
    [ChargesPerMonth]  DECIMAL (18, 2) NOT NULL,
    [DiscountPer]      DECIMAL (3)     NOT NULL,
    [VATPer]           DECIMAL (3)     NOT NULL,
    [VATAmount]        DECIMAL (3)     NOT NULL,
    [ServiceTaxPer]    DECIMAL (3)     NOT NULL,
    [ServiceTaxAmount] DECIMAL (3)     NOT NULL,
    [TotalCharges]     DECIMAL (18, 2) NOT NULL,
    [BillDate]         DATETIME        NOT NULL,
    [SubTotal]         DECIMAL (18, 2) NOT NULL,
    [GrandTotal]       DECIMAL (18, 2) NOT NULL,
    [TotalPaid]        DECIMAL (18, 2) NOT NULL,
    [DiscountAmount]   DECIMAL (3)     NOT NULL,
    CONSTRAINT [PK_CustomerMembership] PRIMARY KEY CLUSTERED ([CM_ID] ASC),
    CONSTRAINT [FK_CustomerMembership_Customer] FOREIGN KEY ([CustomerID]) REFERENCES [dbo].[Customer] ([C_ID]) ON UPDATE CASCADE,
    CONSTRAINT [FK_CustomerMembership_Membership] FOREIGN KEY ([MembershipID]) REFERENCES [dbo].[Membership] ([M_ID]) ON UPDATE CASCADE
);


What I have tried:

Tryied to set the CM_ID to VARCHAR and then program a sort of algorithm to set the id to I-{number} instead of just {number}.
Tryied to set the Values according to the Add function
Ex:
...Add("@d1", SqlDbType.Int).Value = txtMemberShipID.Text;
But this didn't work too.

Any ideias?
Posted
Updated 5-Feb-17 18:35pm
Comments
[no name] 4-Feb-17 10:25am    
"Any ideias?", yep, find the field that you are trying to stuff too much information into and change it so it fits.
Scribling Doodle 4-Feb-17 10:46am    
My main problem is with the CM_ID which is set to be a string, but for every function like stocks or even clients, i have ST-{number} for stocks and C-{number} for clients, and all of the other forms are working correctly, this one is giving me a pain in the ass...
[no name] 4-Feb-17 11:34am    
According to your posting, CM_ID is NOT a string, it's an int.

The error message is pretty explicit:
String or data would be truncated
What it means is you are passing a value that is too long for the field definition. Use the debugger to look at exactly what values you are passing to SQL (pay particular attention to the Months field) and either change your app to not send so much data, or your table to accept the data you are sending.
 
Share this answer
 
Comments
Scribling Doodle 4-Feb-17 11:06am    
I've checked it already and it seems all fine, but this CM_ID wont accept values like I{number}. Even if I change it to varchar.
To generate a unique CM_ID in the form of
I-{number}
for each insertion, first change the field type of CM_ID to varchar, then Ask Your Database for that Unique ID[^]
 
Share this answer
 
v2
Comments
Scribling Doodle 4-Feb-17 11:10am    
Did that and did not work. If I manualy insert the values in the database it's all fine. But if I use my interface it won't work.
This issue occurred due mismatch between table column size and the data which you passed for pushing. In debug mode check the data length which you pass is more than the size of that columns.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900