Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I just try to make
if (txtNo.Text != "" || txtName.Text != "" || txtAddress.Text != "")
{
MessageBox.Show("Please Fill Textbox");
}
I just click update with not value in textbox.
I just make clear when the textbox in the user press the update button, then the warning messages are displayed so that the user recharges. Without being subject to error or out of the program, I am using SQL SERVER to save data.
Your error states that your SQL Connection is not set up properly. Wrap your SQL command in a using statement with a SQL connection. You will need to supply a valid connection string to your database.
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd ...
cmd.ExecuteNonQuery() ...
}
Error is not related to textbox.text value.It is related to sqlcommand.
Please note that whenever you are using sqlcommand. you have to declare new sqlconnection object with connection string. And then apply it to sqlcommand.
Please check below query for example
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx
Your problem is not the string, which I would recommend you to use String.IsNullOrEmpty("YOURSTRING")
You have a problem with you database connection. Set this up properly, creating an instance of SQLConnection and try again.
Change your button code like this.
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtNo.Text == "" || txtName.Text == "" || txtAddress.Text == "")
{
MessageBox.Show("Please Fill TextBox");
return;
}
SqlCommand CMD = new SqlCommand(UPDATE...
Connection.Buka.....();
CMD.ExecuteNonQuery();
MessageBox.Show(....)
Connection.Tutu.....();
}
comparing strings with the .Equals() method instead of the == operator is best practice, may not solve your problem but the code will be cleaner
if((!string.isnullorwhitespace(txtNo.Text)) || (!string.isnullorwhitespace(txtName.Text)) ||(!string.isnullorwhitespace(txtAddress.Text)))
{
enter code here
}
Related
I'm hitting a wall right now in my project.
I have a form, with some listboxes, and add button. When I click on the add button, I got a small dialog form with a textbox, an OK and a Cancel button. The app is connected to a MySQL database. So whenever the text change, the program checks if the name exists in the database, disable the OK button and the textbox turn red if the name exists, otherwise it turns them back to normal. Works without a problem when I'm writing and the name doesn't exist, and when it does, it turns red, like it should. And here is the problem. After turning red, it doesn't go back to normal, even when I enter a valid name.
Here is the code :
private void DialogTxb_TextChanged(object sender, EventArgs e)
{
//ConnexionData class where i do all the SQL manipulation
MySqlDataReader selection = ConexionData.CheckSectionName(DialogTxb.Text);
while (selection.Read())
{
if (selection.HasRows)
{
DialogOk.Enabled = false;
toolTip1.Show("La section existe", TooltibLb);
DialogTxb.BackColor = System.Drawing.ColorTranslator.FromHtml("#ffaaaa");
}
else
{
toolTip1.Hide(TooltibLb);
DialogTxb.BackColor = Color.White;
DialogOk.Enabled = true;
}
}
ConexionData.ConexionClose();//Method to close connection
}
I think I have an idea where the problem is but have don't know why it happens and how to solve it. If I simply exit the form and try to do anything else, like select another element from a listbox which will trigger some database interaction, the program close and visual studio provide me with info on the error:"The connexion is already open". I tried to close in other moments of the code, looked for some solutions on the internet, tried MysqlConection.ClearAllPools(), and still the same issue.
Connexion opens and closes properly in other parts of the application.
Thanks for your attention.
Edit
Here are the methods in ConexionData
class ConnexionData
{
private static MySqlConnection Connexion;
public static MySqlCommand Command;
//Many other methods
//.......
public static void ConnexionClose()
{
Connexion.Close();
}
public static MySqlDataReader CheckSectionName(string name)
{
Connexion.Open();
string checkSectionName = ("Select sectionName from section where sectionName = '" + name + "'");
Command.CommandText = checkSectionName;
Reader = Command.ExecuteReader();
return Reader;
}
}
I use the Connexion.Close() in many parts of the program. I have 2 Data Grid views, and some list box where i load data from the database. I open and close those DGV and change values in listbox and all work fine. Then i try my small form to insert a new values on those tables, test it and close it (actually i insert nothing, i simply close it and there is a ConexionData.Close() in the close event) and here where the problem of connection start.
Edit-Solved
I finally solved the problem. I turned Private MysqlConection to public, and directly closed the property after closing the dialog.
if selection.Read() returns true it means you have at least 1 record. It seems you are looking for
private void DialogTxb_TextChanged(object sender, EventArgs e) {
try {
//TODO: check ConexionData.CheckSectionName (re-)creates connection if required
using (MySqlDataReader selection = ConexionData.CheckSectionName(DialogTxb.Text)) {
if (selection.Read()) {
// Name exists (we've read it)
DialogOk.Enabled = false;
toolTip1.Show("La section existe", TooltibLb);
DialogTxb.BackColor = System.Drawing.ColorTranslator.FromHtml("#ffaaaa");
}
else {
// Name doesn't exist: the cursor is empty (so we've failed to read it)
toolTip1.Hide(TooltibLb);
DialogTxb.BackColor = Color.White;
DialogOk.Enabled = true;
}
}
}
finally {
// finally: rain or shine the connection should be closed
ConexionData.ConexionClose(); // Method to close connection
}
}
In case connection is not closing then you can try to call close() connection or sqldatareader before executing method "CheckSectionName()".
FYR Below is some example Let me know, if it helps.
Approch 1:
System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection();
if(sqlConn.State!= System.Data.ConnectionState.Closed)
{
sqlConn.Close();
}
System.Data.SqlClient.SqlDataReader SqlReader= new System.Data.SqlClient.SqlDataReader();
if(!SqlReader.IsClosed)
{
SqlReader.Close();
}
MySqlDataReader selection = ConexionData.CheckSectionName(DialogTxb.Text);
Approch 2: We can use "using" clause
using (MySqlDataReader selection = ConexionData.CheckSectionName(DialogTxb.Text))
Approch 3:
Add close() and dispose() into finally block.
Is there a way to do this? I cannot seem to find anything online regarding this.
If I run the code below the SQL command will execute prior to hiding the div tag, when ideally I would like the div tag to be hidden and then have the SqlCommand execute.
protected void RunStoredProcedure_click(object sender, EventArgs e)
{
div.Visible = false;
Connection.Open();
SqlCommand StoredProcedure = new SqlCommand("StoredProcedure", Connection);
StoredProcedure.CommandTimeout = 0;
StoredProcedure.CommandType = CommandType.StoredProcedure;
StoredProcedure.Parameters.Add(new SqlParameter("#Date", DateForStoredProcedure.Text)); // DateForStoredProcedure.Text));
StoredProcedure.ExecuteNonQuery();
Connection.Close();
string queryAdditionalFilters = "where user = '" + user.Value + "'";
generateTagsForLiteral(queryAdditionalFilters);
}
Edit: Not sure why this was downvoted as it was marked as answered below with the answer shown below. Whoever downvoted me it would have been helpful to know why as I feel this is a very clear question that way in the future I can post questions correctly or in a preferred fashion.
Thanks to #Theo assisting.
The answer was to use javascript to first hide the tag, and then call the c# button click event.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
protected void Button1_Click(object sender, EventArgs e)
{
if (username.Text == "test" && password.Text == "test")
Response.Cookies ["TheCookie"]["Username"] = username.Text;
Response.Redirect("loggedIn.aspx");
else
Label1.Text = "Invalid Username and/or Password.";
}
Above is a function I'm trying to make happen. For some reason the else statement here isn't being accepted. I don't know why. Any help would be appreciated.
if (username.Text == "test" && password.Text == "test")
{
Response.Cookies ["TheCookie"]["Username"] = username.Text;
Response.Redirect("loggedIn.aspx");
}
else
Label1.Text = "Invalid Username and/or Password.";
Wrap it with braces, otherwise it'll take only the next immediate line (statement) as part of the condition.
It's a good practice to do that even for a one line if/else because it makes maintenance easier.
else
{
Label1.Text = "Invalid Username and/or Password.";
}
if-else (C# Reference) - MSDN
Both the then-statement and the else-statement can consist of a single
statement or multiple statements that are enclosed in braces
({}). For a single statement, the braces are optional but
recommended.
You have multiple statements in the then (true) part of if statement. Although you have used indentation, but those spaces/indents will not be considered by the compiler. Since you haven't specified {} to define scope of if statement, only a single statement is considered for if scope. Hence the error.
You can fix that by introducing scope with {}. It is also recommended to use {} (explicitly define scope) for single statement , as it makes code easier to understand and less prone to error. You code should be:
protected void Button1_Click(object sender, EventArgs e)
{
if (username.Text == "test" && password.Text == "test")
{
Response.Cookies["TheCookie"]["Username"] = username.Text;
Response.Redirect("loggedIn.aspx");
}
else
{
Label1.Text = "Invalid Username and/or Password.";
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
why is the form named (Smart_pharmacy) being closed when I execute this code :
private void LoginBTN_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=Abdullah-PC;Initial Catalog=SmartPharmacyDB;Integrated Security=True");
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "select userpass from usertab where username = #username";
com.Parameters.Add("#username", usernametxt.Text);
con.Open();
object returnedvalue = com.ExecuteScalar();
if (returnedvalue != null)
{
string returneduserpass = com.ExecuteScalar().ToString();
con.Close();
if (returneduserpass == userpasstxt.Text)
{
Smart_Pharmacy f = new Smart_Pharmacy();
f.Show();
this.Close();
}
else
{
MessageBox.Show("Incorrect username or password !");
}
}
else
{
MessageBox.Show("Incorrect username or password !");
}
}
I want the current form to be closed and keep the form (Smart_Pharmacy) opened please help.
I assume you have this code in your main form (one which is passed to Application.Run method in your Main method). When main application form is closed, all other forms are closed as well and application terminates.
What you should do is change application main form to Smart_Pharmacy. And close application if login failed. Like this:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using(LoginForm loginForm = new LoginForm())
{
if (loginForm.ShowDialog() != DialogResult.OK)
return; // exit applicatioin if login failed
}
// if login successfully this start main form
Application.Run(new Smart_Pharmacy());
}
I would say its because you created the Smart_Pharmacy form within the form that is then closed (ie. destroyed).
So the code does what you are telling it to...kill current form. Since the form is destroyed all objects referenced only within this form get destroyed too.
If you want the other form to stay open then you will have to keep a reference to it somewhere else.
PS: On an unrelated note, this code is horrible. You really shouldn't connect to db from button clicks and such. If you are in a position to revise this I would strongly suggest to separate your business logic from UI code.
Technically this works but you should always try to keep layered and easily maintainable.
I've had the same problem. I'm guessing that your login form is set as your start up form. In which case you would need to Hide it rather than close it.
Change to
Smart_Pharmacy f = new Smart_Pharmacy();
f.ShowDialog(this);
this.Close();
So this.Close() will execute after the Smart_Pharmacy form closed
if you need main form to be hidden, use this.WindowState = FormWindowState.Minimized; before opening Smart_Pharmacy
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
this is my snippet , please help me why the con .open is not working inside the function tabledel
i want to delete the table once i press the button , the connection gets opened for the first time but couldnt open it for the second time inside the function tabledel
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.OleDb;
namespace WFA_CREATE_DELETE
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbConnection con = new OleDbConnection(#"PROVIDER=Microsoft.ACE.OLEDB.12.0; Data Source=C:/Users/Dinesh/Documents/Database3.accdb");
OleDbDataAdapter ea = new OleDbDataAdapter();
DataSet dsl;
DataSet esl;
private void Form1_Load(object sender, EventArgs e)
{
OleDbDataAdapter da = new OleDbDataAdapter();
dsl = new DataSet();
con.Open();
DataTable table2 = con.GetSchema("tables");
MessageBox.Show("Database Open");
dataGridView1.DataSource = table2;
con.Close();
con.Dispose();
}
public void Tabledel()
{
int a = 0, d = 0, count, itr;
count = dataGridView1.RowCount;
itr = dataGridView1.ColumnCount;
while (a < count)
{
for (d = 0; d < itr; d++)
{
if (dataGridView1.Rows[a].Cells[d].Value.ToString() == textBox1.Text)
{
MessageBox.Show("table exists");
esl = new DataSet();
string vsql = "drop table '" + textBox1.Text + "'";
ea = new System.Data.OleDb.OleDbDataAdapter(vsql, con);
OleDbCommand cmdea = new OleDbCommand(vsql, con);
//cmdea.Connection = con;
con.Open();
cmdea.ExecuteNonQuery();
MessageBox.Show("table dropped");
con.Close();
con.Dispose();
}
}
a++;
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
public void button1_Click(object sender, EventArgs e)
{
Tabledel();
}
}
}
link
As I see you get this error:
The ConnectionString property has not been initialized.
May be you will create (dispose) your connection in somewhere else (except in form class global variable), so I suggest to set connection string explicitly (With recreating connection):
con = new OleDbConnection(
#"PROVIDER=Microsoft.ACE.OLEDB.12.0; Data Source=C:/Users/Dinesh/Documents/Database3.accdb");
con.Open();
Anyway it wasn't hard to include main part of your code here in SO.
The connection object is created when your Form is created. You open, use, close and DISPOSE the connection object in the Form_Load method. Therefore the connection object is gone by the time your button click handler starts to execute.
You have to either create a new connection object in the button click handler, or NOT dispose it in the Form_Load method.
Really hard to decode what your actual problem is, what's causing it and so on, but there are many problems with your code.
First off you shouldn't initialize your con object the way you do. Every time you are done using it and call Dispose, you'll destroy it. In any case it isn't rebuilt until next time your Form1 class is initialized. That's probably why you're getting the errors.
A suggestion would be to have a singleton that handles your connection. This leads me to the next point: It's a very bad idea to open new connections inside a loop. If you've made your connection handeler properly, you'd only have to open one connection per call. I'll give you so much better performance, which you'll notice if you have many elements to iterate through.
Next up, your delete statement is subject to SQL injections. You should strongly considder using a way that minimizes the user input to selecting from a list so they can't type in weird queries in your textBox1.Text
That's just some of it.. I hope you can use it.
Oh and please, please write a better question. Don't just say "Uh, something doesn't work. Link". Condensate your code and think about what you're asking to make sure it'll be widely understood.