Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
private void button2_Click(object sender, EventArgs e)
{
   string insert ="insert into [dbo].[Student_Info] values (@Name,@Address,@FatherName,@Class)";
   SqlCommand cmd = new SqlCommand(insert, con);
   SqlParameter[] prm = new SqlParameter[4];
   prm[0] = new SqlParameter("@Name", SqlDbType.VarChar);
   prm[0].Value = textBox9.Text;

   prm[1] = new SqlParameter("@Address", SqlDbType.VarChar);
   prm[1].Value = textBox8.Text;

   prm[2] = new SqlParameter("@FatherName", SqlDbType.VarChar);
   prm[2].Value = textBox7.Text;
   prm[3] = new SqlParameter("@Class", SqlDbType.VarChar);
   prm[3].Value = textBox6.Text;

   con.Open();
   cmd.ExecuteNonQuery();
   con.Close();
   MessageBox.Show("Inserted Data");
}


What I have tried:

please help me i have this erroe that want must be declare scalar variable
Posted
Updated 10-Aug-16 2:20am
v2

You didn't add the parameters to the command:
C#
// prepare parameter array

cmd.Parameters.AddRange(prm);

// execute command

Alternatively you can add parameters directly to the collection:
C#
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = textBox9.Text;
 
Share this answer
 
For an INSERT statement without any column specifiers, SQL assumes that every column will have a value and all values are supplied in the exact order of the columns in the table. Using this method is bad practice. If you change the schema of the table, you break all of your code if it isn't updated properly.

You should be doing your inserts like
INSERT INTO dbo.Student_Info (Name, Address, FatherName, Class)
VALUES (@Name, @Address, @FatherName, @Class)

Note that I'm guessing at your column names and just assuming they match the names of your parameter values.
 
Share this answer
 
You're simply creating SqlParameter objects, you're not attaching them to the command. After you create them attach them to the command's parameters collection

C#
cmd.Parameters.Add(prm[0]);
 
Share this answer
 
 
Share this answer
 

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



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