ExecuteNonQuery requires an open and available Connection - c#

In my server windows 2003 the default language and installation is in english language.
Now I need show the GridView of my aspx page in spanish language.
I have tried this code-behind but the output in GridView is always in english and I have error even when I try to run the query strSQL, why?
ExecuteNonQuery requires an open and available Connection.
The connection's current state is closed.
My code below.
I would greatly appreciate any help you can give me in working this problem.
Thank you in advance.
public DataTable GridViewBind()
{
sql = " SELECT * from .... ; ";
try
{
dadapter = new OdbcDataAdapter(sql, conn);
dset = new DataSet();
dset.Clear();
dadapter.Fill(dset);
DataTable dt = dset.Tables[0];
GridView1.DataSource = dt;
string strSQL = " SET lc_time_names = 'es_ES'; ";
OdbcCommand cmd = new OdbcCommand(strSQL, conn);
cmd.ExecuteNonQuery();
GridView1.DataBind();
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dadapter.Dispose();
dadapter = null;
conn.Close();
}
}
protected override void InitializeCulture()
{
Page.Culture = "es-ES";
Page.UICulture = "es-ES";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
InitializeCulture();
GridViewBind();
}
}
EDIT 1
conn.Open();
string strSQL = " SET lc_time_names = 'es_ES'; ";
OdbcCommand cmd = new OdbcCommand(strSQL, conn);
cmd.ExecuteNonQuery();

Make sure you're opening connection before using it in OdbcDataAdapter or OdbcCommand
conn.Open();

Related

Sort data by date, time, and name from Mysql database in c#

I have been really struggling to sort this data by date and time. As you can see, I have got this data. In addition, the data table is not taking the same space as the dataGridView space. How do I resolve that problem?
I am trying to sort out this data in c#. I have generated the above table by writing the below code:
private void ViewAppointment_Load(object sender, EventArgs e)
{
try
{
MySqlConnection connection = new MySqlConnection("server=localhost;port=****;username=root;password=****;database=appointment; pooling = false; convert zero datetime = True");
string Query = "SELECT * FROM `appointmentdetails`";
MySqlCommand myCommand = new MySqlCommand(Query, connection);
MySqlDataAdapter myAdapater = new MySqlDataAdapter();
myAdapater.SelectCommand = myCommand;
DataTable dTable = new DataTable();
myAdapater.Fill(dTable);
dataGridView1.DataSource = dTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks for your time
You can either sort directly on the DataGrid:
dataGridView1.Sort(dataGridView1.Columns["Date"], ListSortDirection.Ascending);
Or get the data sorted from sql:
string Query = "SELECT * FROM `appointmentdetails` order by Date";
You need to add your sorting to the Query
private void ViewAppointment_Load(object sender, EventArgs e)
{
try
{
MySqlConnection connection = new MySqlConnection("server=localhost;port=****;username=root;password=****;database=appointment; pooling = false; convert zero datetime = True");
string Query = "SELECT * FROM `appointmentdetails ORDER BY date DESC`";
MySqlCommand myCommand = new MySqlCommand(Query, connection);
MySqlDataAdapter myAdapater = new MySqlDataAdapter();
myAdapater.SelectCommand = myCommand;
DataTable dTable = new DataTable();
myAdapater.Fill(dTable);
dataGridView1.DataSource = dTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

refresh datagridview after insert or update or delete without selecting new sql query

I just want to clarify, can i refresh datagridview after insert or update or delete without selecting new sql query again ?
i have googled it, and still have no idea to do it.
here's my code
private void button4_Click(object sender, EventArgs e)
{
employee();
}
public void employee()
{
DataTable dtclubroom = new DataTable();
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
myConnection.Open();
dtclubroom.Clear();
command.Connection = myConnection;
command.CommandText = "Select * from employee ";
adapter.SelectCommand = command;
adapter.Fill(dtclubroom);
dataGridView2.DataSource = dtclubroom;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
SqlCommand command2 = new SqlCommand();
try
{
myConnection.Open();
command2.CommandText = "insert into employee (name,id) values (#name,#id)";
command2.Connection = myConnection;
command2.Parameters.AddWithValue("#name","Leon");
command2.Parameters.AddWithValue("#id", "002");
command2.ExecuteNonQuery();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
myConnection.Close();
}
employee() //<- refresh datagridview
}
Button 4 is to load data, and button 5 inserting data also load data. is there a way refresh datagridview without calling employee() method again ?
You can do it in couple of ways.
Add the newly inserted record to your datatable (you need to use a global datatable variable for this) and refresh your Grid View using this datatable.
You can add the newly inserted record directly to the Grid View
You can follow these techniques also for DELETE and UPDATE
Here is the implementation of idea #1 for your existing code :
DataTable dtclubroom = new DataTable();
private void button4_Click(object sender, EventArgs e)
{
employee();
}
public void employee()
{
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
myConnection.Open();
dtclubroom.Clear();
command.Connection = myConnection;
command.CommandText = "Select * from employee ";
adapter.SelectCommand = command;
adapter.Fill(dtclubroom);
dataGridView2.DataSource = dtclubroom;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
SqlCommand command2 = new SqlCommand();
try
{
myConnection.Open();
command2.CommandText = "insert into employee (name,id) values (#name,#id)";
command2.Connection = myConnection;
command2.Parameters.AddWithValue("#name","Leon");
command2.Parameters.AddWithValue("#id", "002");
command2.ExecuteNonQuery();
DataRow dr = dtclubroom.NewRow();
dr["name"] = "Leon";
dr["id"] = "002";
dtclubroom.Rows.Add(dr);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
myConnection.Close();
}
dataGridView2.DataSource = dtclubroom; //<- refresh datagridview
}
Look that the datatable declaration is moved up and you need to place it in top of your class :
DataTable dtclubroom = new DataTable();
Nothing else need to be global.

How to update data from DataGridView to database? ERROR - Cannot insert value NULL

I'm trying to update data from DataGridView to my database. While I was looking for the solution of this problem on google, I noticed that all of the solutions are managed by using class variables (for DataTable,SqlDataAdapter,...). I'm trying to do this just by using function variables.
This is how I loaded data to DataGridView:
private void LoadDataGridView(int ID)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT SENTENCE FROM Sentences WHERE CategoryID = #ID",connection);
cmd.Parameters.Add("#ID",SqlDbType.Int).Value = ID;
DataTable dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(dataTable);
DataGridView.DataSource = dataTable;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING TO DATABASE!");
}
}
DataGridView is showing just those sentences that match particular ID.
This is what I have tried so far:
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT SENTENCE FROM Sentences WHERE CategoryID IN(#CategoryID)", connection);
cmd.Parameters.Add("#CategoryID",SqlDbType.Int).Value = CategoryID;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataTable);
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
}
This is the error that comes up:
Cannot insert value NULL into column CategoryID, table ...;column does not allow nulls.Insert fails. The statement has been terminated.
if your Id data type is int ,you don't need put it inside "".
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
string connString;//WHAT EVER IT IS
string Query=string.Format(#"SELECT QUESTION FROM Questions WHERE CategoryID = '{0}'",CategoryID);
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Query, connection);
connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd,connString);
DataTable DataTable=new DataTable();
dataAdapter.Fill(DataTable);
datagridview1.DataSource=DataTable;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
catch (SqlException)
{
MessageBox.Show("SqL Error!");
}
}
SOLUTION of my problem:
Firstly, I have shown all columns of database table in DataGridView and then I have hided Primary Key column and CategoryID column. That is shown in the following code:
private void LoadDataGridView(int ID)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Sentences WHERE CategoryID = #ID";
cmd.Connection = connection;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value = ID;
dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(dataTable);
dataGridView.DataSource = dataTable;
dataGridView.Columns[0].Visible = false;
dataGridView.Columns[2].Visible = false;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
}
Then, I have set default value only for CategoryID column, because Primary Key column has an option of Auto - Increment. That is show in the following code:
private void dataGridView_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
e.Row.Cells["CategoryID"].Value = CategoryID;
}
The last thing I have done is implement the code for RefreshBtn (the following code is practically the same as the code in question):
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Questions WHERE CategoryID = #CategoryID";
cmd.Connection = connection;
cmd.Parameters.Add("#CategoryID", SqlDbType.Int).Value = CategoryID;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataTable);
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE !");
}
}

Displaying database details on a datagrid

I am trying to display my database details on a datagrid using the following methods. I am able to establish connection with the database and do updates so that's all fine. Just having issues with displaying the data after making a query.
The first method query below does the query. I am trying to use that info and run the codes under the 2nd method which is called when I click a button.
I am having problem callign my query method. I was under the impression I can call it under adapter.SelectCommand but that returns an error saying "cannot implicitly convert type". Please advice if I am running the query wrongly. Thanks.
public MySqlDataReader Query(string queryString)
{
MySqlDataReader reader;
MySqlCommand cmd2;
try
{
cmd2 = new MySqlCommand(queryString, conn);
reader = cmd2.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + " " + reader.GetString(1) + " " + reader.GetDouble(2));
}
return reader;
}
catch(Exception e)
{
Console.WriteLine("Error in query");
Console.Read();
}
return null;
}
private void Button_Retrieve(object sender, RoutedEventArgs e)
{
try
{
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = dataSource.Query("SELECT * FROM PERSONS WHERE Name = 'Sam';");//THis line returns the error
DataTable dt = new DataTable("PERSONS");
adapter.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
adapter.Update(dt);
}
catch (Exception error)
{
MessageBox.Show(error.StackTrace);
}
}
Your adapter does not have a connection
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");

c# How to refresh a datagrid when a record is added

I am having trouble refreshing my datagrid after i add a record. I have tried a few things from other tutorials but cant seam to get it working or figures out where i am going wrong.
Thanks in advance.
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(cmdInsert, con);
try
{
if (isvalid(textEmail.Text))
{
da.InsertCommand.Parameters.Add("#firstName", SqlDbType.VarChar);
da.InsertCommand.Parameters["#firstName"].Value = textFirstName.Text.Trim();
da.InsertCommand.Parameters.Add("#surname", SqlDbType.VarChar);
da.InsertCommand.Parameters["#surname"].Value = textSurname.Text.Trim();
da.InsertCommand.Parameters.Add("#email", SqlDbType.VarChar);
da.InsertCommand.Parameters["#email"].Value = textEmail.Text.Trim();
da.InsertCommand.Parameters.Add("#phone", SqlDbType.VarChar);
da.InsertCommand.Parameters["#phone"].Value = textPhone.Text.Trim();
da.InsertCommand.Parameters.Add("#mobile", SqlDbType.VarChar);
da.InsertCommand.Parameters["#mobile"].Value = textMobile.Text.Trim();
con.Open();
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Customer Added");
con.Close();
clearboxes();
customerDataSet.Clear();
dataGridView1.DataSource = null;
customerTableAdapter.Fill(customerDataSet.Customer);
dataGridView1.DataSource = customerDataSet.Customer;
}
else
{
textEmail.BackColor = Color.Red;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
There should be a function that will have a select statement on that particular table in which you have just inserted the record..
Call that function after every insert/update/delete operations which will give you the updated data present in database.
Can you please elaborate why do you want to refresh the datagrid?
Yes, there could be a number of reasons for refreshing and specifying yours would help us to answer your query.
Well as per my understanding till now, I could suggest you to add the operation/function that you wish to perform after the statement that marks a record to be added to the grid.
For anyone else who gets stuck with a similar problem this is how i managed to get round it. P.S. i am no expert so their is probably an easier / better way of doing it but here is the code and thanks to everyone for their input.
public void binddata()
{
try
{
customerDataSetBindingSource.DataSource = cmdselect;
dataGridView1.DataSource = customerDataSetBindingSource;
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(cmdselect, con);
DataTable dt = new DataTable();
dt.Locale = System.Globalization.CultureInfo.InvariantCulture;
da.Fill(dt);
dataGridView1.DataSource = dt;
MessageBox.Show("Data Updated");
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(cmdInsert, con);
try
{
if (isvalid(textEmail.Text))
{
da.InsertCommand.Parameters.Add("#firstName", SqlDbType.VarChar);
da.InsertCommand.Parameters["#firstName"].Value = textFirstName.Text.Trim();
da.InsertCommand.Parameters.Add("#surname", SqlDbType.VarChar);
da.InsertCommand.Parameters["#surname"].Value = textSurname.Text.Trim();
da.InsertCommand.Parameters.Add("#email", SqlDbType.VarChar);
da.InsertCommand.Parameters["#email"].Value = textEmail.Text.Trim();
da.InsertCommand.Parameters.Add("#phone", SqlDbType.VarChar);
da.InsertCommand.Parameters["#phone"].Value = textPhone.Text.Trim();
da.InsertCommand.Parameters.Add("#mobile", SqlDbType.VarChar);
da.InsertCommand.Parameters["#mobile"].Value = textMobile.Text.Trim();
con.Open();
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Customer Added");
con.Close();
clearboxes();
binddata();
}
else
{
textEmail.BackColor = Color.Red;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Categories