Jump to content

Recommended Posts

Posted

Oi...

O meu programa é em c# com ligação a sql server .

tenho o seguinte código para guardar novos dados dos clientes:

#region Building the connection string

            string Server = "*****";
            string Username = "sa";
            string Password = "******";
            string Database = "***";

            string ConnectionString = "Data Source=" + Server + ";";
            ConnectionString += "User ID=" + Username + ";";
            ConnectionString += "Password=" + Password + ";";
            ConnectionString += "Initial Catalog=" + Database;

            #endregion


            #region Try to establish a connection to the database

            SqlConnection SQLConnection = new SqlConnection();

            try
            {
                SQLConnection.ConnectionString = ConnectionString;
                SQLConnection.Open();

                // You can get the server version 
                // SQLConnection.ServerVersion
            }
            catch (Exception Ex)
            {
                // Try to close the connection
                if (SQLConnection != null)
                    SQLConnection.Dispose();

                // Create a (useful) error message
                string ErrorMessage = "A error occurred while trying to connect to the server.";
                ErrorMessage += Environment.NewLine;
                ErrorMessage += Environment.NewLine;
                ErrorMessage += Ex.Message;

                // Show error message (this = the parent Form object)
                MessageBox.Show(this, ErrorMessage, "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                // Stop here
                return;
            }

            #endregion

            #region Execute a SQL query


            //string SQLStatement = "SELECT * FROM zona_postal";
            string SQLStatement = "select * from zona_postal where cod_postal = '" + textcodpostalcliente.Text + "'";
            // Create a SqlDataAdapter to get the results as DataTable
            SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(SQLStatement, SQLConnection);

            // Create a new DataTable
            DataTable dtResult = new DataTable();

            // Fill the DataTable with the result of the SQL statement
            //SQLDataAdapter.Fill(dtResult);
            int nrows = dtResult.Rows.Count;
            MessageBox.Show(nrows.ToString());
            string codpostal = "";
            // Loop through all entries
            foreach (DataRow drRow in dtResult.Rows)
            {
                // Show a message box with the content of 
                // the "Name" column
                //MessageBox.Show(drRow["localidade"].ToString());
                codpostal = drRow["cod_postal"].ToString();
            }
            //MessageBox.Show(codpostal);
            // We don't need the data adapter any more
            SQLDataAdapter.Dispose();

            if (nrows == 0)
            {
                string sqlIns = "INSERT INTO zona_postal (cod_postal, localidade) VALUES ('" + textcodpostalcliente.Text + "','" + textlocalidadecliente.Text + "')";
                try
                {
                    SqlCommand cmdIns = new SqlCommand(sqlIns, SQLConnection);
                    cmdIns.ExecuteNonQuery();
                    cmdIns.Dispose();
                    cmdIns = null;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString(), ex);
                }
            }

            string sqlIns2 = "INSERT INTO clientes (nome_cliente, morada, telefone, telemovel, email, bi, cod_postal) VALUES ('" + textnomecliente.Text + "', '" + textmoradacliente.Text + "', '" + textelefonecliente.Text + "', '" + textelemovelcliente.Text + "','" + textemailcliente.Text + "','" + textbicliente.Text + "', '" + textcodpostalcliente.Text + "')";
            //SQLConnection.Open();

            try
            {
                SqlCommand cmdIns = new SqlCommand(sqlIns2, SQLConnection);
                cmdIns.ExecuteNonQuery();
                cmdIns.Dispose();
                cmdIns = null;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString(), ex);
            }


            #endregion

mas disseram-me que para fazer o update tambem tinha de ser neste botão.

Tenho numeração automatica  mas nao faço a minima ideia com fazer o update aqui neste botão e como o programa vai saber quando é update ou para guardar novo registo.

Quem poder me ajudar, agradeço!

Posted

Boas.

Calculo que isto seja Windows Form, portanto é muito simples.

Só utilizas o botão guardar quando vais adicionar alguma coisa. Imagina que tens o botão 'novo', então, cada vez que clicares no botão 'novo', o botão 'xpto' irá ter o nome de guardar. Caso contrário, irá ter o nome actualizar. Dou o seguinte exemplo:

protected void btnNovo_Click(object sender, EventArgs e)
{
   btnXPTO.text = "Guardar";
}

  //Aqui ficará a condição para cada vez que premires o botão XPTO
protected void btnNovo_Click(object sender, EventArgs e)
{
   if(btnXPTO.text == "Guardar")
       // Código para guardar
   else
      // Código para actualizar

   // Poderás sempre fazer um else if (btnXPTO.text == "Actualizar") caso opter por mais do que uma condição ou algo do género
}

Cumps 🙂

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.