Data grid view not showing data from mysql table - c#

Im trying to get data in data grid view . this code works fine if i use this query :- "Select * from employee.transaction"
But when im trying to put the conditions it does not give any output (just shows a blank table)
My table has month,year column of type Int.Im using mysql server 5.6.25
I cant find the problem with my code.Please help.Thx in advance.
private void load_data_Click(object sender, EventArgs e)
{
string constring = "datasource = localhost;port = 3306;username = ****;password = ****";
MySqlConnection conDataBase = new MySqlConnection(constring);
var cmdDataBase = conDataBase.CreateCommand();
cmdDataBase.CommandText = #"select * from employee.transaction where department = #department AND month = #month AND year = #year";
cmdDataBase.Parameters.AddWithValue("#department", this.department.Text);
cmdDataBase.Parameters.AddWithValue("#month", this.dateTimePicker1.Value.Month);
cmdDataBase.Parameters.AddWithValue("#year", this.dateTimePicker1.Value.Year);
try
{
// here im trying to show table in datagrid view
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
//here im trying to make a excel file which would contain what is currently being displayed in the datagrid view
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
ds.Tables.Add(dbdataset);
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

The problem could be, as mentioned by #Bjorn-Roger in the comments, that both 'month' and 'year' are keywords in SQL.
I would suggest you try :
select * from employee.transaction where department = #department AND [month] = #month AND [year] = #year
P.S: Notice the use of [] with the fields 'month' and 'year'.
Edit 1
Also, you might want to check if the date format of the input fields 'month' and 'year' is same as that of database table fields.

Related

I have been following a tutorial on a snake game for C# but there is one part of the code that is not working and I am not sure why

I am recently getting back into coding. I have been working on this Snake Game program that i've been following a tutorial on. However, I am a tad confused as to why its saying "The name dataGridView1 does not exist in the current context. Basically what I am trying to do is display score history in my program through a database and I have followed everything exactly how it is on the tutorial, just cant seem to make it work though. Any help would be appreciated as I am a complete noob at this, thank you!
private void UpdateScoreBoard()
{
//Get data from database and show in data grid view
string query = "SELECT Date,Name,Scores FROM scores";
using(SqlConnection con = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
var ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1w.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Sort(this.dataGridView1.Columns[0], ListSortDirection.Descending);
}
}
}
}
You need to declare it in your Form object to be accessible (check the example here):
public class Form1 : System.Windows.Forms.Form
{
// Declare the gridview as a class member.
DataGridView dataGridView1 = new DataGridView();
// Rest of the code
private void UpdateScoreBoard()
{
//Get data from database and show in data grid view
string query = "SELECT Date,Name,Scores FROM scores";
using(SqlConnection con = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
var ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1w.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Sort(this.dataGridView1.Columns[0], ListSortDirection.Descending);
}
}
}
Then at some point you need to add it to the form
this.Controls.Add(songsDataGridView);

Display the data on GridView by built SQL from multi tables

GridView1 does not display the data that the SQL statement brings
as :
.....{statements to select attributes and conditions to putting SQL statement}
(Example on SQL :SELECT [patient].name_patient FROM patient, visitFACTABLE, datetime, disease WHERE [patient].Id_patient = [visitFACTABLE].Id AND [visitFACTABLE].Id = [datetime].Id_datetime AND [patient].gender_patient = 'Male')
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
con.Open();
string q_sql = "SELECT " + slct + " FROM patient, visitFACTABLE, datetime, disease WHERE [patient].Id_patient = [visitFACTABLE].Id AND [visitFACTABLE].Id = [datetime].Id_datetime " + w;SqlDataAdapter da = new SqlDataAdapter(q_sql, con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
trigger debugger break point # GridView1.DataSource = dt;
then hover visualize 🔎 and check did your dt ( data table) contain at least 1 row . if got row , by right your Gridview shall show data

Web Forms - Multiple Select Query Results in a GridView?

I'm an extreme newbie. Please bear with me.
I'm trying to populate a GridView with multiple resultsets. I'm using a DataSet with mulitple DataTables. This code has only 2 DataTables, but I will need to use more than 5 or maybe 10.
ASP.NET 4.5.1 Web Forms w/ MSSQL
Method
public DataSet GvTest()
{
using (SqlConnection conn = new SqlConnection(strConn))
{
conn.Open();
SqlCommand cmd = new SqlCommand
(
"SELECT s.StudioName, i.Studio, i.UPC, i.Title, i.Price, i.Availability, i.Location, i.Qty " +
"FROM tbl_Item i JOIN tbl_studio s ON i.Studio = s.StudioID WHERE i.Availability = 'T' and i.Qty > 0 ORDER BY i.Location; " +
"SELECT d.UPC, SUM(d.Qty) FROM tbl_PROrderDetail d JOIN tbl_PROrder p ON d.OrderNo = p.OrderNo " +
"WHERE p.Status = 'P' and p.Type = 'P' GROUP BY d.UPC;"
, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
conn.Close();
DataTable dtTest = new DataTable();
ds.Tables[0].Merge(ds.Tables[1]);
dtTest = ds.Tables[0];
return ds;
}
}
Code behind
protected void Page_Load(object sender, EventArgs e)
{
DataModel dm = new DataModel();
DataSet ds = dm.GvTest();
GridBind(ds);
}
private void GridBind(DataSet ds)
{
gvItemList.DataSource = ds.Tables[0];
gvItemList.DataBind();
}
This code just generates the first SELECT result and then the second SELECT result right after.
What I need to do is add a new column to Tables[0], and the result set of Tables[1] fills the new column.
Row count of Tables[0] = 94
Row count of Tables[1] = 6800
I need 94 rows on my GridView, not 6800. UPC is the connection.
Thanks in advance!

Listbox returns System.Data.DataRowView instead of values

I am doing a project for my school, where I have to make a C# Windows Forms application that lets me interact with my PostgreSQL database. I have made a listbox, which is supposed to get the names of the tables from my database, and when I select these names, data from that table is show in the datagridview object in the form. The problem is, however, all my listbox values are System.Data.DataRowView, and datagridview only displays values from the first table in the list.
The code:
DataTable tabulusaraksts = new DataTable();
DataTable tabula = new DataTable();
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
NpgsqlDataAdapter adapter2 = new NpgsqlDataAdapter();
string tab;
public datubaze()
{
InitializeComponent();
string connectionstring = "Server=localhost;Port=5432;UserId=postgres;Password=students;Database=retrospeles;";
//string connectionstring = String.Format("Server={0};Port={1};" +
// "User Id={2};Password={3};Database={4};",
// serveris.ToString(), port.ToString(), user.ToString(),
// password.ToString(), database.ToString());
NpgsqlConnection ncon = new NpgsqlConnection(connectionstring);
NpgsqlCommand listfill = new NpgsqlCommand("select table_name from INFORMATION_SCHEMA.tables WHERE table_schema = ANY (current_schemas(false));", ncon);
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.DataSource = tabulusaraksts;
listBox1.DisplayMember = "table_name";
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;
}
public void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
tab = listBox1.GetItemText(listBox1.SelectedItem);
adapter2.Fill(tabula);
dataGridView1.DataSource = tabula;
}
That code should work. I tried it with some test data and ListBox was filled with correct values.
To be sure, try to also set ValueMember like
listBox1.DisplayMember = "table_name";
I think the best approach is to add DataTable rows to your ListBox using loop or Linq list. After filling tabulusaraksts iterate through DataRows and add them as items to ListBox, without setting DataSource Something like this (Linq):
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.Items.AddRange(tabulusaraksts.AsEnumerable().Select(row => row[0].ToString()).ToArray());
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;
or, using foreach loop
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.Items.Clear();
foreach (DataRow row in tabulusaraksts.Rows)
{
listBox1.Items.add(tabulusaraksts[0].ToString());
}
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;

GridView doesn't show data

private void fill()
{
adptr = new OleDbDataAdapter(#"SELECT * FROM LibraryInfo WHERE First_Name='"+LoginName+"'", cn);
//LoginName is a string variable for displaying users info after the login
ds.Clear();
adptr.Fill(ds);
dataGridView1.DataSource = "";
dataGridView1.DataSource = ds.Tables[0];
}
After the database updated, GridView didn't show data.
Taken from this msdn article on the DataBind Property.
ASP EXAMPLE
void Page_Load(Object sender, EventArgs e)
{
// This example uses Microsoft SQL Server and connects
// to the Northwind sample database. The data source needs
// to be bound to the GridView control only when the
// page is first loaded. Thereafter, the values are
// stored in view state.
if(!IsPostBack)
{
// Declare the query string.
String queryString =
"Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]";
// Run the query and bind the resulting DataSet
// to the GridView control.
DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
AuthorsGridView.DataSource = ds;
AuthorsGridView.DataBind();
}
else
{
Message.Text = "Unable to connect to the database.";
}
}
}
DataSet GetData(String queryString)
{
// Retrieve the connection string stored in the Web.config file.
String connectionString = ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
// Connect to the database and run the query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
// Fill the DataSet.
adapter.Fill(ds);
}
catch(Exception ex)
{
// The connection failed. Display an error message.
Message.Text = "Unable to connect to the database.";
}
return ds;
}
This snippet shows you how to (a) bind your dataset to a gridview, by assigning it using the Databind method.
The site also says:
Use the DataBind() method to bind data from a data source to the GridView control. This method resolves all data-binding expressions in the active template of the control.
SOLUTION
I would like to reference the line saying:
AuthorsGridView.DataBind();
which actually binds the data to the control.
SIDE NOTE
To protect yourself from SQLi, you should read up on SQL Parameters, and not direct concatenation.
WINFORM EXAMPLE
Tutorial was found: here
//create the connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\myDatabase.mdb";
//create the database query
string query = "SELECT * FROM MyTable";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
Also:
//the DataGridView
DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dgView.DataSource = bSource;
Use are missing to call databind method here.Use following code :
DataAdapter adapter=new DataAdapter(SqlCommand,SqlConn);
DataTable tbl=new Datatable();
adapter.Fill(tbl);
GridView1.DataSource=tbl;
GridView1.DataBind();//This line is missing in your code
try with this format?

Categories

Resources