kapo kapo - 1 year ago 114
C# Question

'System.Data.SqlClient.SqlException' thrown

protected void Button1_Click(object sender, EventArgs e)
SqlConnection con = new SqlConnection(str);

SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Companyregister";
cmd.Parameters.AddWithValue("@Company_name", txtname.Text);
cmd.Parameters.AddWithValue("@Register_no", txtreg_no.Text);
cmd.Parameters.AddWithValue("@Type", DropDownList1.Text);
cmd.Parameters.AddWithValue("@Address", txtadrs.Text);
cmd.Parameters.AddWithValue("@Email", txtemail.Text);
cmd.Parameters.AddWithValue("@Contact_no", txtphone.Text);

Response.Write("Register succesful");

Stored procedure:

CREATE PROCEDURE [dbo].Companyregister
@Company_name varchar(50),
@Register_no varchar(50),
@Type varchar(50),
@Address varchar(50),
@Email varchar(50),
@Contact_no varchar(50)
insert into company_reg (Company_name, Register_no, Type, Address, Email, Contact_no)
values (@Company_name, @Register_no, @Type, @Address, @Email, @Contact_no)



An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: String or binary data would be truncated.

Answer Source

The following error indicates that one or more of your data field is NOT able to fit in the DB field. For eg, may be your address is of 60 characters but your DB size for it is only 50 characters.

String or binary data would be truncated.

To solve this, first check if the data you are inserting complies to the sizes defined in you DB. To catch this more easily, define your parameters to stored procedure as follows:

cmd.Parameters.Add("@Company_name", SqlDbType.VarChar, 50).Value = txtname.Text;
cmd.Parameters.Add("@Register_no", SqlDbType.VarChar, 50).Value = txtreg_no.Text;
cmd.Parameters.Add("@Type", SqlDbType.VarChar, 50).Value = DropDownList1.Text;
cmd.Parameters.Add("@Address", SqlDbType.VarChar, 50).Value = txtadrs.Text;
cmd.Parameters.Add("@Email", SqlDbType.VarChar, 50).Value = txtemail.Text;
cmd.Parameters.Add("@Contact_no", SqlDbType.VarChar, 50).Value = txtphone.Text;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download