claudia2 Posted May 8, 2009 at 04:38 PM Report #262420 Posted May 8, 2009 at 04:38 PM 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 Se alguém me poder ajudar
M6 Posted May 8, 2009 at 04:45 PM Report #262423 Posted May 8, 2009 at 04:45 PM 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."
claudia2 Posted May 8, 2009 at 04:46 PM Author Report #262424 Posted May 8, 2009 at 04:46 PM Vou procurar e ver se consigo fazer isso. Mas já agora, não preciso fazer nada no sql?
claudia2 Posted May 8, 2009 at 04:53 PM Author Report #262426 Posted May 8, 2009 at 04:53 PM 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?
M6 Posted May 8, 2009 at 04:57 PM Report #262430 Posted May 8, 2009 at 04:57 PM 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."
claudia2 Posted May 11, 2009 at 10:13 AM Author Report #262963 Posted May 11, 2009 at 10:13 AM 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
claudia2 Posted May 11, 2009 at 01:45 PM Author Report #262999 Posted May 11, 2009 at 01:45 PM Já resolvi o problema
claudia2 Posted May 11, 2009 at 01:46 PM Author Report #263001 Posted May 11, 2009 at 01:46 PM Bem... se alguem souber com posso ir buscar os dados á BD para aparecer na text quando carrego no botão de ultimo registo que me diga pf
amiloM1425 Posted May 11, 2009 at 03:59 PM Report #263034 Posted May 11, 2009 at 03:59 PM Assim de uma forma muito simples podes fazer a tua consulta, em que ordenas os resultados de forma descendente pelo pk e o último registo será o primeiro da tabela de resultados.
claudia2 Posted May 12, 2009 at 08:22 AM Author Report #263243 Posted May 12, 2009 at 08:22 AM Eu entendi o que disses-te, mas o problema é que nao sei fazer
amiloM1425 Posted May 12, 2009 at 08:38 AM Report #263251 Posted May 12, 2009 at 08:38 AM 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.
claudia2 Posted May 12, 2009 at 08:51 AM Author Report #263252 Posted May 12, 2009 at 08:51 AM 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.
amiloM1425 Posted May 12, 2009 at 09:05 AM Report #263255 Posted May 12, 2009 at 09:05 AM 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"];
claudia2 Posted May 12, 2009 at 09:15 AM Author Report #263258 Posted May 12, 2009 at 09:15 AM Desculpa mas eu nao percebo mesmo nada disto Se poderes me explicar aonde coloco esse código e o código que tenho de retirar agradeço
amiloM1425 Posted May 12, 2009 at 09:24 AM Report #263263 Posted May 12, 2009 at 09:24 AM 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.
claudia2 Posted May 12, 2009 at 09:37 AM Author Report #263271 Posted May 12, 2009 at 09:37 AM { { #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
amiloM1425 Posted May 12, 2009 at 09:48 AM Report #263277 Posted May 12, 2009 at 09:48 AM 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
claudia2 Posted May 12, 2009 at 10:09 AM Author Report #263292 Posted May 12, 2009 at 10:09 AM { { #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')
amiloM1425 Posted May 12, 2009 at 10:43 AM Report #263314 Posted May 12, 2009 at 10:43 AM 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 } }
claudia2 Posted May 12, 2009 at 10:59 AM Author Report #263328 Posted May 12, 2009 at 10:59 AM É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?
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now