Click here to Skip to main content
15,917,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in button click event

C#
private void button3_Click(object sender, EventArgs e)
        {
            SqlStr = String.Format("insert into employee(empid,ename,salary,deptno) values ({0},{1},{2},{3})", textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
            ExecuteDML();
            button3.Enabled = false;
        }


in command exection method i have written the code like this

C#
private void ExecuteDML()
{
    DialogResult d = MessageBox.Show("Are you sure of executing the below SQl Statement?\n\n" + SqlStr, "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if(d==DialogResult.Yes)
    {
        cmd.CommandText = SqlStr;
        int Count = cmd.ExecuteNonQuery();
        if(Count>0)
        {
            MessageBox.Show("Statement executed Successfully");
        }
        else
        {
            MessageBox.Show("Statement failed execution");
        }
        LoadData();
    }
}


but i am getting the invalid column name error while executing the code.
someone help me thanks.
Posted

1 solution

Basically the error comes because you add the values from the text boxes without having starting and ending '.

However the bigger problem is that you don't use parameters.

Correct way to fix this is to use SqlParameter[^]
So instead of
C#
SqlStr = String.Format("insert into employee(empid,ename,salary,deptno) values ({0},{1},{2},{3})", textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
ExecuteDML();

You should have something like
C#
SqlStr = "insert into employee(empid,ename,salary,deptno) values (@empid,@ename,@salary,@deptno)");
ExecuteDML();

and then using AddWithValue[^] you add the parameters to the parameter collection of the command to be used.
 
Share this answer
 
v2
Comments
raxhemanth 17-Jul-15 2:51am    
thankyou mika and i changed the format u suggested and i have another issue called conversion failed when converting the varchar value textbox1 to datatype int. how can i convert it to int
Wendelius 17-Jul-15 3:46am    
You must define the parameter with data type int and make sure that the value of the text box is integer
Sergey Alexandrovich Kryukov 17-Jul-15 3:10am    
Sure, a 5.
—SA
Wendelius 17-Jul-15 3:46am    
Thanks SA!

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