Will a Winforms grid keep its datasource in memory? .Net - winforms

I've a grid in my winforms application and i bind a huge dataset to the grid. Will the dataset be stored in the memory by the grid after calling DataBind(). How does it operate on the data binded to the grid?
Update
I wrote the following code
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Server=server;Initial Catalog=db;User ID=testv;Pwd=pass"))
{
con.Open();
using (SqlCommand com = new SqlCommand("select * from tbl_Sample", con))
{
using (SqlDataAdapter ada = new SqlDataAdapter(com))
{
ada.Fill(dt);
dgvMain.DataSource = dt;
dt.Dispose();
}
}
}
After assigning the datatable as the datasource i'm able to dispose it. So does it make a copy in the memory?
Thanks
NLV

It doesn't make a copy, it makes a reference to the original datasource object.
P.S. Making a huge dataset is not a good idea anyway. If you need to display lots of rows, make some kind of paging or filters and restrict number of rows to load and display.

Related

c# wpf Filling datagrid with async await method

Filling datagrid with async await method
I would like to use the function in the above link.
using MySqlConnection con = new(Common.JOIN);
con.Open();
MySqlCommand cmd = new(
$"SELECT * FROM item WHERE CONCAT (`i_type`) like '{type.Text}' ORDER BY `i_name` ASC;", con);
MySqlDataAdapter adp = new(cmd);
DataSet ds = new();
adp.Fill(ds, "LoadDataBinding");
datagrid.DataContext = ds;
The tone may be a little odd.
I ask a question through Google Translate.
The code I am using is as above.
To use the code I use from the link in the link
How do I fix it?
I'm using C# WPF.
If you would replace this line
datagrid.DataContext = ds;
With this one
datagrid.ItemsSource = ds.Tables["LoadDataBinding"].DefaultView;
Then it should work

Unable to update SQL Server database with value from textbox in gridview

I have just joined stackoverflow as a relatively novice user of visual studio, with the hope that someone might be able to help answer a question to a problem I'm having.
I'm sure it's quite simple, but at the moment I have a Gridview which is bound to a table from our SQL Server.
My issue I'm having is with the gridview, which was generated with the help of the in-built wizard. My update SQL statement is a custom one, which is quite simply:
UPDATE SMCsummove
SET SubmitQty = #Textbox1 * - 1, HasBeenEdited = 'Y'
WHERE (SMCPOinteger = #SMCPOinteger) AND (SMCproduct = #PartNo)
Now being a novice, I am not quite sure if I am doing this right, but #Textbox1 is the value that the user enters as a new value to update the table with, after they have clicked the autogenerated 'edit' button. Quite simply once they have clicked the 'update' button, the gridview reverts back to the original value that was there in the SubmitQty column.
If anyone can shed some light or point out any massive oversights, that would be most appreciated!
Need to see more of the code from the gridview to know for sure, but it looks like a postback is occurring and this is causing your gridview to bind again and be reset.
I'm pretty new to this as well and what I have found works for gridviews is to have a pageload event like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridView();
}
}
Then have a separate statement for the binding (this is one that I uses:
private void bindGridView()
{
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
string selectSQL = String.Format("SQL Statement here");
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Review");
GridView1.DataSource = ds;
GridView1.DataBind();
}
You may find you have to call the gridbind as well after updating records to repopulate the gridview with the updated values.

Manipulating a database in C++

I apologize if has been asked, and answered somewhere else, but I have been searching like crazy and can't find what I'm looking for.
OleDbConnection^ conn = gcnew OleDbConnection ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Milestone3testdatabase.accdb; Persist Security Info=True");
OleDbCommand^ com = gcnew OleDbCommand();
com->Connection = conn;
com->CommandText = "SELECT *FROM tblcity;";
System::Data::DataSet^ ds = gcnew System::Data::DataSet();
OleDbDataAdapter^ adapt = gcnew OleDbDataAdapter();
adapt->SelectCommand = com;
adapt->Fill(ds,"why");
dataGridView1->DataSource = ds->Tables["why"];
I am trying to figure out how to actually use the data I obtain from the database. I was shown how to put it into a gridview, BUT I don't want a gridview. I want be able to take 1 cell of the table and display it as text.
How do I convert the table into usable data for a C++ forms application?
Either modify your SELECT so that it returns only a single value by using SqlCommand.ExecuteScalar Method or extract the value from your table with the DataTable.Select Method and DataTable.Rows Property
myDataTable->Rows[rowNumber][columnNumber]

Moving from SQL Databinding to using the Entity framework

I'm changing my WPF application to use the Entity Framework instead of calling sql db directly.
On this one window I have a listview containing a gridview and I'm databinding it by using the following method which calls a stored procedure to get the data.
Now I already have my model generated from my existing sql database and included the stored proc...
How would I go about changing this method to read the data from the entity model instead of directly from sql?
public static void BindData(DataGrid grid)
{
SqlConnection loginCon = new SqlConnection();
loginCon.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlDataAdapter adapter = new SqlDataAdapter("sp_SELECT_CONSHEAD", loginCon))
{
DataSet data = new DataSet();
adapter.Fill(data);
grid.ItemsSource = data.Tables[0].DefaultView;
}
}
You can use Function Import to get the stored procedure mapped to entity in EntityFramework. Then you can directly call the function in your code with single line of code.
grid.ItemsSource = dbContext.GetSP_Select_Conshead();

How do I populate a WPF Datagrid from a Datatable?

I am new here so forgive me if this is the wrong section for my question. My problem is that I can't populate a datgrid with the contents of a dataset. Having searched for the last few days to try and resolve this, I have given up and thought I would try here.
I am using Vs 2010 VB.Net and it's a WPF application
As you can tell from the code I am very new to this and any suggestions for improvement will be most welcome. I can see that the dataset is populated ok via the visualizer, I have a datagrid 'dgBOM' which I want to display the results. A popular solution in my searches was to add '.DataSource' but when I type the '.' after dgBOM the Datasource option is not there.
Any help would be much appreciated.
Thank you.
Code:
Public Sub Connect()
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim ds As DataSet
Dim da As OleDbDataAdapter
Dim dt As DataTable
Dim drow As DataRow
Dim PartColumn As DataColumn
Dim CostColumn As DataColumn
dt = New DataTable("BOM")
ds = New DataSet("BOM")
PartColumn = New DataColumn("PartNo")
CostColumn = New DataColumn("Cost")
da = Nothing
cn = Nothing
dr = Nothing
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\Ls-wtgl834\share\Adrian\PriceLists\WAP-PriceLists.mdb;User ID=Admin")
cn.Open()
cmd = New OleDbCommand("select * from Inventory", cn)
dr = cmd.ExecuteReader
da = New OleDbDataAdapter(cmd)
dt.Columns.Add(PartColumn)
dt.Columns.Add(CostColumn)
While dr.Read()
If dr(0) = FBladeExtNo Then
FrontBladeCost = dr(1)
drow = dt.NewRow()
drow("PartNo") = FBladeExtNo
drow("Cost") = FrontBladeCost
dt.Rows.Add(drow)
ds.Tables.Add(dt)
Exit While
End If
End While
dgBOM.ItemsSource = ds
Catch
End Try
dr.Close()
cn.Close()
End Sub
I have given up on DataReader and all that. After writing a program a couple years ago where I had to provide all of the logic for change tracking and concurrency and relationship tracking and everything I threw up my hands because it is so time intensive.
Nowadays I use an O/RM framework; that is Object/Relation Mapping. Two of the biggies right now are Entity Framework (my personal favored framework) and NHibernate (originally written for Java but ported for .NET). These frameworks allow you to map database tables to .NET classes. Either ones you write yourself or ones generated by the tool (in Entity Frameworks case.
EF in Visual Studio 2010 allows you to do Model-First and Database-First development. Model-First allows you to create a diagram of how you want your classes to relate to each other (e.g. A Customer class that has a collection of Addresses, Phone Numbers and Events) then generates a database to store that data. Database-First is the opposite. You create your database, and EF tries to make a model that reflects the Database structure. It takes care of connection string creation, entity change tracking and concurrency, and it presents the data in nice objects that in my opinion are generated pretty darned fast. Personally I have found EFs data retrieval faster than my own hand executed data retrieval and object population.
WPF, with it's databinding capabilities, is geared more toward these dataobjects (here after I will just call them entities) than to DataReaders and DataAdapters. If you want to dive right in, here is a little Microsoft video on getting started with EF. Also be sure to check out WindowsClient.net as they have some good stuff there too.
Later on, once you get the hang of EntityFramework, check out the MVVM design pattern.

Resources