DatagridView by SQL - c#

I have a datagridview with 4 columns
[](https://i.stack.imgur.com/wvD94.png)
and I want to make a query in my database, so that it appears in my datagridview.
public DataTable pesquisar(string produto)
{
DataTable _dt = new DataTable();
string sqlQuery = "Select cd_produto, " +
"ds_produto, " +
"referencia, " +
"ds_marca " +
"FROM produto";
command.CommandText = sqlQuery;
try
{
command.Connection = conn.Conectar();
using (SqlDataAdapter da = new SqlDataAdapter(sqlQuery, command.Connection))
{
command.ExecuteNonQuery();
using (DataTable _DT = new DataTable())
{
da.Fill(_DT);
return _DT;
}
}
}
catch (Exception)
{
throw;
}
}
I did it like this, but this way it adds new columns to my datagrid

When you set the DataSource of a DataGridView and AutoGenerateColumns is set to true, any columns/properties in the data source that do not match existing columns will have a new column generated for them. The way you match a column that you create to a column/property in the data source is to set the grid column's DataPropertyName property. For example, if you have a column in your data source named "cd_produto" then you need to set the DataPropertyName property of the corresponding grid column to "cd_produto" and then that source column will bind to that grid column.

Related

How to add data from Npgsql(Postgres) to specific columns of Data grid view in window forms in c#?

I have been trying to add data fetched from Postgres using Npgsql and store the data in pre-defined columns of data grid view. I have tried this. First Time it works fine but second time it causes it the data grid view to remove the old columns and create new columns with the name of the columns in table in database.
I'm new to C# and windows forms but I can't figure this out.
public static void GetUsers(DataGridView GVObj, DataGridViewColumn User_Name_GVC,
DataGridViewColumn User_UserName_GVC,DataGridViewColumn User_Password_GVC,
DataGridViewColumn User_PhoneNumber_GVC, DataGridViewColumn User_Address_GVC,
DataGridViewColumn User_RoleID_GVC, DataGridViewColumn User_UserID_GVC)
{
try
{
SQLqUery = "SELECT * FROM users;";
CMD = new NpgsqlCommand(SQLqUery, Main.DbConnection);
Main.DbConnection.Open();
NpgsqlDataAdapter DA = new NpgsqlDataAdapter(CMD);
dt = new DataTable();
//CMD.ExecuteReader();
dt.Load(CMD.ExecuteReader());
//DA.Fill(dt);
Main.DbConnection.Close();
GVObj.DataSource = null;
//------Columns of The DataGridView
User_UserName_GVC.DataPropertyName = dt.Columns["UserName"].ToString();
User_Password_GVC.DataPropertyName = dt.Columns["Password"].ToString();
User_PhoneNumber_GVC.DataPropertyName = dt.Columns["PhoneNumber"].ToString();
User_Address_GVC.DataPropertyName = dt.Columns["Address"].ToString();
User_RoleID_GVC.DataPropertyName = dt.Columns["RoleFK"].ToString();
User_UserID_GVC.DataPropertyName = dt.Columns["UserId"].ToString();
User_Name_GVC.DataPropertyName = dt.Columns["Name"].ToString();
//Columns of The DataGridView------
GVObj.DataSource = dt;
}
catch (Exception ex)
{
Main.DbConnection.Close();
MessageBox.Show(ex.Message, "Error");
}
}
I was able to fixe the issue by giving "dataPropertyName" to each data grid view column and by setting GVObj.AutoGenerateColumns = false

SQL query to datatable

I had done till one last part. Unsure how or what should I do to add into code.
public String DisplaySheetList()
{
DataTable dt = new DataTable();
GridView gv = new GridView();
string sqlStatement1 = "SELECT cs.SheetId AS sheet_id, ltm.LocationType AS location_type, cs.PalletNo AS palletNo, cs.period AS period,cs.syncDate AS syncDate,cs.syncStatus AS syncStatus "
+ "FROM CountSheet cs JOIN LocationTypeMaster ltm ON ltm.LocationId = cs.LocationId " +
" ORDER BY 1 DESC";
SqlCommand sqlCmd1 = new SqlCommand(sqlStatement1, conn);
SqlDataAdapter sqlDa1 = new SqlDataAdapter(sqlCmd1);
sqlDa1.Fill(dt);
//What should i put here
gv.DataBind();
}
I created the table and the view, got the query and fill it in to the table (if I am not wrong). Is it completed or is thing else I should do to ensure it is in the gridview so I can display them out.
Any help will be good, thank you guys
Just Put :
gv.DataSource=dt;
in place of What should i put here to bind datatable data to gridview
So after you fill the result in your data table
Make dt the gridview datasource.
//put it in the gridview datasource.
gv.DataSource = dt;
You can refer to this MSDN page for setting gridview datasource
To complete your code:
public String DisplaySheetList()
{
DataTable dt = new DataTable();
GridView gv = new GridView();
string sqlStatement1 = "SELECT cs.SheetId AS sheet_id, ltm.LocationType AS location_type, cs.PalletNo AS palletNo, cs.period AS period,cs.syncDate AS syncDate,cs.syncStatus AS syncStatus "
+ "FROM CountSheet cs JOIN LocationTypeMaster ltm ON ltm.LocationId = cs.LocationId " +
" ORDER BY 1 DESC";
SqlCommand sqlCmd1 = new SqlCommand(sqlStatement1, conn);
SqlDataAdapter sqlDa1 = new SqlDataAdapter(sqlCmd1);
sqlDa1.Fill(dt);
//put it in the gridview datasource.
gv.DataSource = dt;
gv.DataBind();
}

C# - unexpected result in populating ComboBox with MySql database

I my class DBConnect, I have this function to populate a ComboBox to database based on input query:
public void POPULATE_COMBOBOX(string query, ComboBox myComboBox)
{
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable myDataTable = new DataTable();
adapter.Fill(myDataTable);
myComboBox.DataSource = myDataTable;
this.CloseConnection();
}
}
And here's how I use it
DBConnect.POPULATE_COMBOBOX("SELECT NAME FROM users", comboBox_Name);
I have 3 rows in column NAME, and I expect those 3 names will be displayed in my comboBox_Name. However instead, I got 3 lines of System.Data.DataRowView in my combobox. Any idea how to convert those DataRowView to string?
You have to tell combobox what column to display.
//Preparation
var dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add("Name1");
dt.Rows.Add("Name2");
//Setup data binding
myComboBox.DataSource = dt.DefaultView;
myComboBox.DisplayMember = "Name";
myComboBox.ValueMember = "Name";
Then SelectedItem gets the actual ComboBox item (in this case a DataRowView), whereas SelectedValue gets the value of the property you specified as the ValueMember of the ComboBox
Or another way how to populate your ComboBox is:
MySqlDataReader sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
myComboBox.Items.Add(sqlReader["Name"].ToString());
}
sqlReader.Close();

How to change a DataGridViewTextBoxColumn to a DataGridViewLinkColumn?

I have created a DataGridView and filled it with data from an MS Access database. One of the columns in the database is a hyperlink data type. Instead of it being a DataGridViewLinkColumn in my dataGridView2, it is a DataGridViewTextBoxColumn. Because of this it is displayed as a string and is unusable as a hyperlink. I need to know how to change the type of the column. I've been working on this for a while now and have yet to make any real progress.
This code is in my Form1_Load():
dataGridView2.DataSource = bindingSource2;
GetData2("SELECT ProdName, ProdDesc, PIN, EqVal, AsOf, IssDate, Vendor, Salesperson, OwnerName, InsuredName, Hyperlink FROM ProdInterim WHERE ProdInterim.OwnerID = " + id + "");
The Hyperlink column is the one in question here.
Here is the GetData2():
private void GetData2(string selectCommand)
{
try
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = U:/Syndicate II/Syndicate II.accdb;Persist Security Info = False";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(selectCommand, connectionString);
OleDbCommandBuilder builder = new OleDbCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource2.DataSource = table;
dataGridView2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}

Modifying a DataTable

Situation:
Hello! I am trying to populate a WPF toolkit DataGrid with a MS Access database.
Here is what I have right now (it works):
//Load the datagrid with the database
private void LoadDataGrid(string filename, string path)
{
string databaseConn = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + path + "\\" + filename,
tableName ="";
OleDbConnection conn = null;
DataTable schemaTable,
table = new DataTable();
try
{
conn = new OleDbConnection(databaseConn);
try
{
conn.Open();
schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] { null, null, null, "TABLE" });
tableName = "[" + schemaTable.Rows[0].ItemArray[2].ToString() + "];";
string sqlQuery = "SELECT * FROM " + tableName;
OleDbCommand command = new OleDbCommand(sqlQuery, conn);
OleDbDataReader reader;
reader = command.ExecuteReader();
table.Load(reader);
DataGrid_.ItemsSource = table.DefaultView;
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
The code sample above loads a WPF toolkit DataGrid with the help of a MS Access database.
What I would like to do is be able to insert a column in the DataGrid at the very beginning. This column would be used to write the row number. What I think could work is to modify the table variable (which is a DataTable object).
Question:
So, how can I insert a column in the table variable, add the row number for each rows in that new column, and have all the data from the database in the DataGrid?
An alternative is to create a column on the DataTable before loading the IDataReader into it.
// the rest of your code
//
DataTable table = new DataTable();
DataColumn col = table.Columns.Add("RowNumber", typeof(int));
col.AutoIncrementSeed = 1;
col.AutoIncrement = true;
//
// the rest of your code
//
table.Load(reader)
//
// the rest of your code
The code snippet bellow demonstrates the technique out of the question's context
//Simulates data coming from a database or another data source
DataTable origin = new DataTable();
DataColumnCollection columns = origin.Columns;
columns.Add("Id", typeof(int));
columns.Add("Name", typeof(string));
origin.Rows.Add(55, "Foo");
origin.Rows.Add(14, "Bar");
IDataReader reader = origin.CreateDataReader();
DataTable table = new DataTable();
//Sets up your target table to include a new column for displaying row numbers
//These are the three lines that make it all happen.
DataColumn col = table.Columns.Add("RowNumber", typeof(int));
col.AutoIncrementSeed = 1;
col.AutoIncrement = true;
//Simulates loading data from the database
table.Load(reader);
// Examine table through the debugger. Is will have the contents of "origin" with the column "RowNumber" prepended
Your easiest solution would be to modify your code to include a "virtual" RowNumber field in your original SELECT query, like so:
SELECT ROWNUM AS ROWNUMBER, * FROM TABLE1
Unfortunately, Access doesn't have anything like a ROWNUM function, so I think the easiest solution is to add a RowNumber column in the SELECT query like this:
SELECT 0 AS ROWNUMBER, * FROM TABLE1
which will add a column containing all zeroes at the beginning, and then iterate through the resulting DataTable and set the row number, like this:
int rownumber = 1;
foreach (DataRow row in table.Rows)
{
row["ROWNUMBER"] = rownumber;
rownumber++;
}
and then dump the DataTable into the grid.

Categories

Resources