Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
this is my code :

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


namespace Film
{
    public partial class Form1 : Form
    {
         string SqlStr;
        SqlCommand SqlCmd;
        SqlDataAdapter SqlDa;
        SqlDataReader SqlDr;

        public Form1()
        {
            InitializeComponent();
        }

       

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            SqlConnection CN = new SqlConnection("Data Source=(local);Initial Catalog=Movies;Integrated Security=True");

            try 
            
            {
                CN.Open();

                SqlStr = "Insert into Movies( [Name]";
                SqlStr = SqlStr + " ,[Director]";
                SqlStr = SqlStr + " ,[Year]";
                SqlStr = SqlStr + " ,[Type] ) ";
                SqlStr = SqlStr + " Values('" + TxtName.Text + "','" + TxtDirector.Text + "',";
                SqlStr = SqlStr + "'" + TxtYear.Text + "',";
                SqlStr = SqlStr + "'" + TxtType.Text + "',";
                SqlCmd = new SqlCommand(SqlStr, CN);
                

                MessageBox.Show("با موفقیت ثبت شد");
                Clear();


            }
            finally
            {
                CN.Close();
            }

        }

        public void Clear()
        {
            TxtName. Text = "";
            TxtDirector.Text = "";
            TxtYear.Text = "";
            TxtType.Text = "";
           
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            SqlConnection CN = new SqlConnection("Data Source=(local);Initial Catalog=Movies;Integrated Security=True");

            try
            {
                CN.Open();

                SqlStr = @"UPDATE Movies 
SET Name     = @Name,
    Director = @Director,
    Year     = @Year,
    Type     = @Type,
WHERE Id_Movies = @id";

                SqlCmd = new SqlCommand(SqlStr, CN);
                SqlCmd.Parameters.AddWithValue("@Name", TxtName.Text);
                SqlCmd.Parameters.AddWithValue("@Director", TxtDirector.Text);
                SqlCmd.Parameters.AddWithValue("@Year", TxtYear.Text);
                SqlCmd.Parameters.AddWithValue("@Type", TxtType.Text);
                SqlCmd.Parameters.AddWithValue("@Id", TxtId.Text);
               

                MessageBox.Show("Edited successfully.");
                Clear();


            }
            finally
            {
                CN.Close();
            }
        }

        private void TxtSearch_Click(object sender, EventArgs e)
        {
            SqlConnection CN = new SqlConnection("Data Source=(local);Initial Catalog=Movies;Integrated Security=True");
            try
            {
                CN.Open();
          
                SqlStr = "   select Name,Director,Year,Type ";
                SqlStr = SqlStr +" from Movies" ;
                SqlStr = SqlStr + " where Id_Movies='"+TxtId.Text+"'  ";

                SqlCmd = new SqlCommand(SqlStr, CN);
                SqlDr = SqlCmd.ExecuteReader();
              
                SqlDr.Read();

                if (!SqlDr.HasRows)
                {
                    MessageBox.Show("اطلاعات مورد نظر وجود ندارد");
                }
                else
                {
                    TxtName.Text = SqlDr["Name"].ToString();
                    TxtDirector.Text = SqlDr["Director"].ToString();
                    TxtYear.Text = SqlDr["Year"].ToString();
                    TxtType.Text = SqlDr["Type"].ToString();
      
                }

            }

            finally
            {
                CN.Close();
            }

        }
        }
        }



when i click on debug and change the texts and click on edit it say's edited secsussefull but in sql server nothing change . why ? how to fix it ?
Posted
Updated 22-Jul-15 8:01am
v2
Comments
[no name] 22-Jul-15 13:52pm    
You are not executing your command.
brandon1999 22-Jul-15 14:14pm    
how to do that ?
Richard Deeming 22-Jul-15 16:28pm    
Your code is vulnerable to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

You never execute the command. For example in insert
C#
SqlStr = "Insert into Movies( [Name]";
SqlStr = SqlStr + " ,[Director]";
SqlStr = SqlStr + " ,[Year]";
SqlStr = SqlStr + " ,[Type] ) ";
SqlStr = SqlStr + " Values('" + TxtName.Text + "','" + TxtDirector.Text + "',";
SqlStr = SqlStr + "'" + TxtYear.Text + "',";
SqlStr = SqlStr + "'" + TxtType.Text + "',";
SqlCmd = new SqlCommand(SqlStr, CN);


MessageBox.Show("با موفقیت ثبت شد");
Clear();

you should call the ExecuteNonQuery. LIke
C#
SqlStr = "Insert into Movies( [Name]";
SqlStr = SqlStr + " ,[Director]";
SqlStr = SqlStr + " ,[Year]";
SqlStr = SqlStr + " ,[Type] ) ";
SqlStr = SqlStr + " Values('" + TxtName.Text + "','" + TxtDirector.Text + "',";
SqlStr = SqlStr + "'" + TxtYear.Text + "',";
SqlStr = SqlStr + "'" + TxtType.Text + "',";
SqlCmd = new SqlCommand(SqlStr, CN);

SqlCmd.ExecuteNonQuery(); // This was missing

MessageBox.Show("با موفقیت ثبت شد");
Clear();


Side note 1: Also I can see that you corrected the update as guided but as I wrote, always use parameters so do the same thing for insert and select.

Side note 2: Always use try..catch blocks. Many things can go wrong when modifying the data so it's a good thing to have proper error handling

Side note 3: And it would be best to always use transactions

Hope this helps :)
 
Share this answer
 
v2
Comments
brandon1999 22-Jul-15 14:10pm    
i change the codes but still add and edit button dosen't work.
i check it tommorow . please give me the right code . this is my first program and i see the errors alot i'm tired. please help. i'll come back here tommorow.
Wendelius 22-Jul-15 14:19pm    
The example I wrote should be correct. Since you're learning programming, one tool you should master is the debugger. Use the debugger to execute your program line-by-line and investigate the values of the variables and so on. This way you will get all necessary data in order to solve why a program isn't working as it should.

HAve a look at https://msdn.microsoft.com/en-us/library/y740d9d3.aspx[^] and Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Richard Deeming 22-Jul-15 16:29pm    
What, no mention of the SQL Injection vulnerability? :P
Wendelius 23-Jul-15 4:05am    
Am I that predictable :greatlysurprised:

Actually I mentioned it in the previous question by the same OP and just referenced the issue in this one so you're right, I am predictable :)
brandon1999 23-Jul-15 4:13am    
i fix the problem . thank you so much for your helps.
Here's an updated version of your code with some of the issues fixed:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Film
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void Clear()
        {
            TxtName. Text = "";
            TxtDirector.Text = "";
            TxtYear.Text = "";
            TxtType.Text = "";
        }

        private static SqlConnection CreateConnection()
        {
            return new SqlConnection("Data Source=(local);Initial Catalog=Movies;Integrated Security=True");
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            using (SqlConnection connection = CreateConnection())
            using (SqlCommand command = new SqlCommand("Insert into Movies([Name], [Director], [Year], [Type]) VALUES (@Name, @Director, @Year, @Type)", connection))
            {
                command.Parameters.AddWithValue("@Name", TxtName.Text);
                command.Parameters.AddWithValue("@Director", TxtDirector.Text);
                command.Parameters.AddWithValue("@Year", TxtYear.Text);
                command.Parameters.AddWithValue("@Type", TxtType.Text);

                try
                {
                    connection.Open();
                    command.ExecuteNonQuery();
    
                    MessageBox.Show("Inserted successfully.");
                    Clear();
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                    // TODO: Log the error somewhere
                }
            }
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            using (SqlConnection connection = CreateConnection())
            using (SqlCommand command = new SqlCommand("UPDATE Movies SET Name = @Name, Director = @Director, Year = @Year, Type = @Type WHERE Id_Movies = @id", connection))
            {
                command.Parameters.AddWithValue("@Name", TxtName.Text);
                command.Parameters.AddWithValue("@Director", TxtDirector.Text);
                command.Parameters.AddWithValue("@Year", TxtYear.Text);
                command.Parameters.AddWithValue("@Type", TxtType.Text);
                command.Parameters.AddWithValue("@Id", TxtId.Text);

                try
                {
                    connection.Open();
                    command.ExecuteNonQuery();
    
                    MessageBox.Show("Edited successfully.");
                    Clear();
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                    // TODO: Log the error somewhere
                }
            }
        }

        private void TxtSearch_Click(object sender, EventArgs e)
        {
            using (SqlConnection connection = CreateConnection())
            using (SqlCommand command = new SqlCommand("SELECT Name, Director, Year, Type FROM Movies WHERE Id_Movies = @id", connection))
            {
                command.Parameters.AddWithValue("@Id", TxtId.Text);

                try
                {
                    connection.Open();
                    
                    using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        if (!reader.Read())
                        {
                            MessageBox.Show("Movie not found.");
                        }
                        else
                        {
                            TxtName.Text = (string)reader["Name"];
                            TxtDirector.Text = (string)reader["Director"];
                            TxtYear.Text = (string)reader["Year"];
                            TxtType.Text = (string)reader["Type"];
                        }
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                    // TODO: Log the error somewhere
                }
            }
        }
    }
}


  • Use parameterized queries everywhere to avoid SQL Injection[^] vulnerabilities;
  • Execute the queries, instead of just creating them and then throwing them away;
  • Catch and display / log exceptions from the database;
  • Wrap objects which implement IDisposable in a using block;
  • Don't use fields to store objects whose lifetime is limited to a single method call;
  • Extract the repeated code to create the SqlConnection object into a separate method;
  • Pass CommandBehavior.CloseConnection to the ExecuteReader method, so that the connection is closed as soon as the SqlDataReader is disposed;
  • Check the return value of the Read method, rather than ignoring it and then calling HasRows;
 
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