Jump to content

Recommended Posts

Posted

Olá...

Tenho um programa em c# com ligação a sql server 2005 aonde ele faz a gestão de uma clínica veterinária.

Quando adiciono um cliente automaticamente ele passa para o form animais para criar o boletim do animal.

O problema é que tanto o form "clientes" como o form "animais" tem de ter o mesmo Cod_numero e não sei como fazer isso  :wallbash:

Se alguém me poder ajudar

  • Replies 47
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Posted

Coloca um método nos forms para receberem esse valor.

Por exemplo, o construtor dos forms pode receber esse valor quando os forms são criados.

10 REM Generation 48K!
20 INPUT "URL:", A$
30 IF A$(1 TO 4) = "HTTP" THEN PRINT "400 Bad Request": GOTO 50
40 PRINT "404 Not Found"
50 PRINT "./M6 @ Portugal a Programar."

 

Posted

Esqueci-me duma coisa, ainda estou a fazer a parte de "quando adiciono um cliente automaticamente ele passa para o form animais para criar o boletim do animal"... a parte da numeração devo fazer depois ou antes?

Posted

Para passar o Cod_numero entre os forms não é necessário usar o sql para nada.

A numeração deverá ser feita apenas quando gravas a informação na bd, excepção feita se necessitares dela para alguma coisa antes de gravar a informação na bd.

10 REM Generation 48K!
20 INPUT "URL:", A$
30 IF A$(1 TO 4) = "HTTP" THEN PRINT "400 Bad Request": GOTO 50
40 PRINT "404 Not Found"
50 PRINT "./M6 @ Portugal a Programar."

 

Posted

tenho este código para guardar os dados dos clientes:

  #region Building the connection string

          string Server = "PORTATIL\\PAP";
            string Username = "sa";
            string Password = "****";
            string Database = "CLINICAVET";

            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 animais";
            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 (cod_clientes, nome_cliente, morada, telefone, telemovel, email, bi, cod_postal) VALUES ('" + textnumerocliente.Text + "', '" + 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 quando executo ele da erro na zona que esta a vermelho e nao sei porque.

Se alguém me poder ajudar

Posted

Aqui fica um exemplo de uma consulta simples cujos os resultados são ordenados de forma descendente pelo pk.

SELECT * FROM t_cliente ORDER BY pk_cliente DESC

Depois para acederes aos dados é igual como uma outra qualquer consulta.

Não sei como costumas fazer, mas assumindo que utilizas um DataReader, podes fazer o seguinte

while (reader.Read())
   {

      //Obter os dados
      int id= reader.GetInt32(0); // 0 = 1ª coluna do resultado
      string nome = reader.GetString(1); // 1 = 2ª coluna
      etc...
      break; // para parar a leitura do reader logo na primeira iteração
   }

Se estiveres a usar uma DataTable basta acederes à primeira linha.

Posted
private void primeiroregistocliente_Click(object sender, EventArgs e)
        {
            #region Building the connection string

            string Server = "PORTATIL\\PAP";
            string Username = "sa";
            string Password = "******";
            string Database = "CLINICAVET";

            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
            string SQLStatement = "SELECT * FROM t_cliente ORDER BY pk_cliente DESC";
            // 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;
           
            while (reader.Read())
   {

      //Obter os dados
      int id= reader.GetInt32(0); // 0 = 1ª coluna do resultado
      string nome = reader.GetString(1); // 1 = 2ª coluna
      //etc...
      break; // para parar a leitura do reader logo na primeira iteração

tenho isto no botão mas dá-me erro no reader.

Posted

Tu não tens o reader declarado. E no teu caso estás a devolver o resultado da consulta para dentro de uma DataTable.

Para acederes a uma linha do DataTable fazes o seguinte

dtResult.Rows[idx_linha]["nome_coluna"];
Posted

O código que tens de retirar é o que eu te dei há pouco, o que tem o while(reader.Read()).

Onde irás colocar a linha de código que te mostrei no último post é aqui:

            // 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;

            //Aqui fica o código para ires buscar os resultados que queres
            txtNome.Text = dtResult.Rows[0]["nome"].ToString();
            txtMorada.Text = dtResult.Rows[0]["morada"].ToString();
            etc...

Aconselho-te a colocares o código todo dentro do try catch, e acrescentares mais um catch(SqlException sex), de forma a que o código fique mais robusto e para que consigas de uma forma mais simples perceberes os erros que vão ocorrendo.

Posted
{
            {
                #region Building the connection string

                string Server = "PORTATIL\\PAP";
                string Username = "sa";
                string Password = "*****";
                string Database = "CLINICAVET";

                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
                string SQLStatement = "SELECT * FROM t_clientes ORDER BY pk_clientes DESC";
                // 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;
                //Aqui fica o código para ires buscar os resultados que queres
                textnumerocliente.Text = dtResult.Rows[0]["cod_clientes"].ToString();
                //textnomecliente.Text = dtResult.Rows[0]["nome_cliente"].ToString();
                //etc...
            }
        }
    }
}

Chega á linha que diz

textnumerocliente.Text = dtResult.Rows[0]["cod_clientes"].ToString();

e dá erro.

Aconselho-te a colocares o código todo dentro do try catch, e acrescentares mais um catch(SqlException sex), de forma a que o código fique mais robusto e para que consigas de uma forma mais simples perceberes os erros que vão ocorrendo.

Nao sei como se faz isso

Posted

Qual o erro que dá?

Tu já tens um try catch no método, copias este código para dentro do try:

string SQLStatement = "SELECT * FROM t_clientes ORDER BY pk_clientes DESC";
                // 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;
                //Aqui fica o código para ires buscar os resultados que queres
                textnumerocliente.Text = dtResult.Rows[0]["cod_clientes"].ToString();
                //textnomecliente.Text = dtResult.Rows[0]["nome_cliente"].ToString();
                //etc...

E a seguir ao catch que tens acrescentas outro:

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;
                }
                catch (SqlException SqlEx)
                {
                        MessageBox.Show(this, SqlEx.Message, "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

Aqui ficam alguns links onde podes ler mais sobre try catchs:

http://msdn.microsoft.com/en-us/library/dszsf989(VS.71).aspx

http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=128

Posted
{
            {
                #region Building the connection string

                string Server = "PORTATIL\\PAP";
                string Username = "sa";
                string Password = "****";
                string Database = "CLINICAVET";

                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);


                }

                #endregion
                string SQLStatement = "SELECT * FROM t_clientes ORDER BY pk_clientes DESC";
                // Create a SqlDataAdapter to get the results as DataTable
                SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(SQLStatement, SQLConnection);

                // Create a new DataTable
                DataTable dtResult = new DataTable();
                //SQLDataAdapter.Fill(dtResult);
                int nrows = dtResult.Rows.Count;
                //Código para ir buscar os resultados que quero
                textnumerocliente.Text = dtResult.Rows[0]["cod_clientes"].ToString();
                textnomecliente.Text = dtResult.Rows[0]["nome_cliente"].ToString();


                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;
                }
                catch (SqlException SqlEx)
                {

                    MessageBox.Show(this, SqlEx.Message, "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }

        }
    }
}

Acho que foi isto que disses-te. Mas da-me erro na linha:

catch (SqlException SqlEx)

O erro que dá é:

A previous catch clause already catches all exceptions of this or of a super type ('System.Exception')
Posted

Não era bem isso, o que deves fazer é o seguinte

{
{
    {
	#region Building the connection string

	string Server = "PORTATIL\\PAP";
	string Username = "sa";
	string Password = "****";
	string Database = "CLINICAVET";

	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

            string SQLStatement = "SELECT * FROM t_clientes ORDER BY pk_clientes DESC";
            // Create a SqlDataAdapter to get the results as DataTable
            SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(SQLStatement, SQLConnection);

            // Create a new DataTable
            DataTable dtResult = new DataTable();
            //SQLDataAdapter.Fill(dtResult);
            int nrows = dtResult.Rows.Count; //Acho que não precisas disto
            //Código para ir buscar os resultados que quero
            textnumerocliente.Text = dtResult.Rows[0]["cod_clientes"].ToString();
            textnomecliente.Text = dtResult.Rows[0]["nome_cliente"].ToString();

	}
        catch (SqlException SqlEx) //Este é colocado primeiro porque extende da classe Exception, então para que possas apanhar uma SqlException, esta tem de aparecer primeiro, como estava o catch(Exception ex) apanha todas as execpções
        {
		MessageBox.Show(this, SqlEx.Message, "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        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);
	}
        
	#endregion
    }
}
Posted

És muito fiche e tens uma paciência incrivél mas tenho de te pedir novamente ajuda.

Com esse código, a executar o programa quando carrego no botão de ultimo registo aparece-me isto:

a error occurred while trying to connect the server.

there is no row at position 0

O que se passa?

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.