Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am write a code for inserting data in database table it work almost well but one value doesn't insert in database table coulumn
in database one couloumn show-System.Web.UI.WebControls.TextBox
System.Web.UI.WebControls.TextBox
System.Web.UI.WebControls.TextBox
System.Web.UI.WebControls.TextBox

i geting error where textbox name is-bstocks.Text

What I have tried:

namespace NovletyShop
{
    public partial class AdBooks : System.Web.UI.Page
    {
        SqlConnection con;
        SqlCommand cmd;

       
        protected void Page_Load(object sender, EventArgs e)
        {
           String path = "Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=NoveltySystem;Integrated Security=True";
           con = new SqlConnection();
           con.ConnectionString = path;
           con.Open();
           blang.SelectedIndex = 0;
        }

        protected void addB_Click(object sender, EventArgs e)
        {
           
            String query = "Insert into addBooks(BkName,BkLanguage,BkStd,BkAuthore,BkEditions,BkPrice,BkStocks) values('" + bname.Text + "','" + blang.Text + "','" + bstd.Text + "','" + bauthore.Text + "','" + bedition.Text + "', '" + bprice.Text + "','" + bstocks + "')";
            cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
            con.Close();
Posted
Updated 13-Jan-19 19:10pm
v2

As already noticed by a few members, your code is bad and your logic is messed up. First off, you should NOT append the values of your TextBox to your SQL statement as it could potentially leads you to SQL Injection attack. Here's an article that I wrote a while back the demonstrate how dangerous it is: [^]

Second, don't hard code your connection string and embed it in your C# code. Connection String should be put in your web.config file under connectionStrings element: Creating a Connection String and Working with SQL Server LocalDB | Microsoft Docs[^]

For example:

HTML
<connectionStrings>
  <add name="MyDBConnectionString" connectionString="Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=NoveltySystem;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>


You can then reference your Connection String value via ConfigurationManager class like this:

C#
string dbConnectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;


Third, don't initialize your SqlConnection in Page_Load event since you are inserting data at Button's Click event.

Forth, make it a habit to put objects that eat resources such as SqlConnection, SqlCommand within a using block to ensure that objects will be properly disposed and after they are used.

Finally, I would recommend you to separate your code/logic for inserting data to database and keep them out from your Button click event for the ease of maintenance and separation of concerns.

Your code would now look something like this:

C#
private void InsertRecord(string name, string language, string std, string author, string edition, string price, string stock){
      string dbConnectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
	using (SqlConnection connection = new SqlConnection(dbConnectionString)) {
                string sql = "INSERT INTO addBooks(BkName,BkLanguage,BkStd,BkAuthore,BkEditions,BkPrice,BkStocks) VALUES (@BookName,@BookLanguage,@BookStd,@BookAuthor,@BookEdition,@BookPrice,@BookStock)";
                using (SqlCommand cmd = new SqlCommand(sql, connection)) {

                        connection.Open();
			cmd.Parameters.AddWithValue("@BookName", name);
	        	cmd.Parameters.AddWithValue("@BookLanguage", language);
			cmd.Parameters.AddWithValue("@BookStd", std);
			cmd.Parameters.AddWithValue("@BookAuthor", author);
			cmd.Parameters.AddWithValue("@BookEdition", edition);
                        cmd.Parameters.AddWithValue("@BookPrice", price);
                        cmd.Parameters.AddWithValue("@BookStock", stock);
			cmd.ExecuteNonQuery();
                }
 	}
}

protected void addB_Click(object sender, EventArgs e){
        InsertRecord(bname.Text,blang.Text,bstd.Text,bauthore.Text,bedition.Text, bprice.Text,bstocks);
}


Note: The may need to double check the datatype you used in your SQL Database as we passing all parameters as string datatype in this example. For example, if the BkPrice and BkStocks columns in your database is decimal and integer, then you need to change your C# code datatype as well.

Hope that helps!
 
Share this answer
 
Please read bobby-tables.com: A guide to preventing SQL injection[^]. It explains why you should never use string concatenation to create SQL cpmmands. You are building your command from information provided by the user with no attempt to verify whether that data is valid or not.
 
Share this answer
 
There are multiple problems in the code. For example
- You concatenate values from user interface directly to the SQL statement. As said in previous answer, this leaves you open to SQL injections
- You open a connection when the page is loaded and keep it open until user presses a button
- You don't dispose commands etc.

I would recommend going through Properly executing database operations[^]. The same principles apply regardless of the type of the UI
 
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