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");
Related
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);
}
}
I am trying to show Oracle Data in a DataGridView in my Windows Form Application but it just returns a grey blank view. My code for this currently is:
string insertquery = "select * from Candidate where CandidateName like '"+ txtBoxSearchData.Text +"%'";
OracleConnection con = new OracleConnection(oradb);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = insertquery;
try
{
OracleDataReader reader = cmd.ExecuteReader();
OracleDataAdapter orada = new OracleDataAdapter(cmd);
DataTable dataTable = new DataTable();
orada.Fill(dataTable);
dataTable.Load(reader);
BindingSource bSource = new BindingSource();
bSource.DataSource = dataTable;
dataGridViewSearch.DataSource = bSource;
orada.Update(dataTable);
}
catch(ArgumentException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
catch(OracleException ex1)
{
MessageBox.Show("Error: " + ex1.Message);
}
finally
{
cmd.Dispose();
con.Dispose();
}
}
I am positive I do not require all those functions in my Try statement but I have come across many different methods to do this - I just included all of those into my code to experiment. The connection string is correct too as I have succeeded in adding data into the tables through queries in another part of my application.
Doing something like the following should be enough. There should be no need for an OracleDataAdapter or BindingSource. Just can't test it here, as I do not have an Oracle database around.
public void fillDataGrid()
{
try
{
using(OracleConnection connection = new OracleConnection("connectstring"))
using(OracleCommand cmd = new OracleCommand("select * from my super table", connection ))
{
connection .Open();
using(OracleDataReader oracleDataReader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(oracleDataReader );
myDataGrid.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
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 !");
}
}
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();
I have this piece of code which should be pretty straight forward.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection sqlConn = new SqlConnection(connString))
{
sqlConn.Open();
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand("SELECT Id, FirstName, LastName, TcReadOnly FROM PersonTable", sqlConn);
using (SqlCommandBuilder builder = new SqlCommandBuilder(da))
{
DataTable dt = (DataTable)dgvUsers.DataSource;
da.UpdateCommand = builder.GetUpdateCommand();
da.Update(dt);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Der er sket en fejl \r\n \r\n" + ex.ToString());
}
}
However, I recieve this error when the code is run.
Line 96 in Userform being
da.Update(dt);
I have already checked that my SelectCommand return a primary in Id, so that shouldn't be the problem.
Of course, seconds after asking the question I found the answer.
The SelectCommand I'm using to actually fill the DataTable looks like this
da.SelectCommand = new SqlCommand("SELECT Id, FirstName AS Fornavn, LastName AS Efternavn, " +
"TcReadOnly AS 'Read only' FROM PersonTable", sqlConn);
Which means that the columns in my DataTable doesn't have the same names as the ones I'm trying to update the database with :-) Brainfart....