datagridview columns disappears - vb.net

Guys i have a datagridview and a button on my form.
Under form load event following code runs for displaying data into datagridview columns.. I have manually added some columns in datagridview to populate data from dataset.
The button is placed on the form to clear all data except column..
I have tried several times but with data the columns also disappears..
is there any solution for this ? thanks in advance
I want to use this datagridview column again for displaying data entered in textbox... without dataset..
con.Open()
cmd.CommandText = "select Code,Name,Operations,Rate,Qty,Tax,Tax_amt,Discount,Total_Amount from products where Id = ('" & CStr(i) & "')"
Dim sdr As SqlDataReader = cmd.ExecuteReader
Dim dt As DataTable = New DataTable()
dt.Load(sdr)
dt.Columns("Code").ColumnName = "ii_code"
dt.Columns("Name").ColumnName = "ii_name"
dt.Columns("Operations").ColumnName = "ii_opera"
dt.Columns("Rate").ColumnName = "ii_rate"
dt.Columns("Qty").ColumnName = "ii_qty"
dt.Columns("Tax").ColumnName = "ii_Tax"
dt.Columns("Tax_Amt").ColumnName = "ii_taxamt"
dt.Columns("Discount").ColumnName = "ii_dis"
dt.Columns("Total_Amount").ColumnName = "ii_total"
DataGridView1.DataSource = dt
con.Close()

If the DataGridView is not bound to any data source, this code will do the trick:
DataGridView.Rows.Clear()
Else you can clear you data source in your example it is data table
Datatable.rows.clear()

I mean I have one datagridview on my form to view sales order...
On form load datagridview is filled with data...
But i want to place a button on my form which clears all the data from datagridview to accept new data without deleting data from database..
There are some text box on my form from that new data will be entered temporary on datagridview..

Related

How to disable SortMode in dynamically load table?

Actually i have an application where the user is able to load an excel file to it and that excel file will be shown in a DataGrid.
Now i would implement a method where the user will be able to select different interesting columns by clicking it but the issue is that i get the error "SortMode can't be automatic when SelectionMode is set to FullColumnSelect"
if i set other SelectionMode all works fine but i need the "FullColumnSelect". I've yet read in other question that i should disable SortMode for each column but the issue is that the columns doesn't exist till the user load the excel file.
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName)
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(dt)
dt.Rows.Remove(dt.Rows(0))
MetroGrid1.DataSource = dt 'App crash here
con.Close()
You could set the SortMode programmatically by looping through all the columns after the user has loaded the excel file.
'---> load the grid
dg1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
For Each col As DataGridViewColumn In dg1.Columns
col.SortMode = DataGridViewColumnSortMode.NotSortable
Next

How to make sortable a DataGrid bounded with a table

I load data on a DataGrid from a SQLite database with code like this:
conn.Open()
Dim sql = "SELECT * FROM TableDataGrid"
Dim cmdConnection As SQLiteCommand = New SQLiteCommand(sql, conn)
Dim da As New SQLiteDataAdapter
da.SelectCommand = cmdConnection
Dim dt As New DataTable
da.Fill(dt)
MyDataGrid.DataSource = dt
When the user click on a Row I display the data on a few textbox, combobox, no problem at all.
Now I need to let the user sort the DataGrid by clicking the column he want and of course is not that simple.
After research on the "e.RowIndex >= 0" and "System.NullReferenceException" error I understand that "The problem is that out of the box the BindingList does not support sorting! I know - sounds dumb but that is how it is." posted here: WinForms: DataGridView - programmatic sorting
So If I'm right I need to implement my own SortableBindingList but I'm confused because the samples of code are about a LIST and I load the database records on a TABLE (dt)
Example:
http://timvw.be/2007/02/22/presenting-the-sortablebindinglistt/
Another post say I can fix the trouble with a line like:
SortableBindingList<YourListType> sortableBindingList = new SortableBindingList<YourListType>(list)
What is the generic solution to make the DataGrid sortable on this case?
Thanks to the tips of the users I found the solution
Private Sub MyDataGrid_SelectionChanged(sender As Object, e As EventArgs) Handles MyDataGrid.SelectionChanged
'Check if the user clicked on a header or a row
Try
If MyDataGrid.CurrentRow.Index = Nothing Then
'Header clicked!!
Else
'Row clicked!!!
'Here I load the data of the clicked row on my form
FormCleanDataEntry()
FormShowRowData()
End If
Catch ex As Exception
'MsgBox(ex.ToString())
End Try
End Sub
The curiosity is that the exception is thrown but anyway I don't show any message to the user and the DataGrid is sorted and the program works fine

vb.net Filling data-set value as combo-box value-member issue

myORAConnection.Open()
Dim SQLString As String = "Select child_id as id, child_name as name from xxi_org_structure_v Where parent_id=" & LegalEntity & ""
Dim cmd As New OracleCommand(SQLString, myORAConnection, OraTrans)
Dim daTableORA As New OracleDataAdapter(cmd)
daTableORA.Fill(dtOrg)
daTableORA.Dispose()
cmd.Dispose()
myORAConnection.Close()
With IT_ORG_CODEComboBox
.DataSource = dtOrg.Tables(0)
.ValueMember = "id"
.DisplayMember = "name"
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
'TODO: This line of code loads data into the 'Main_POSDataSet.pos_promotion_item_group_details' table. You can move, or remove it, as needed.
Me.Pos_promotion_item_group_detailsTableAdapter.Fill(Me.Main_POSDataSet.pos_promotion_item_group_details)
'TODO: This line of code loads data into the 'Main_POSDataSet.pos_promotion_item_group_headers' table. You can move, or remove it, as needed.
Me.Pos_promotion_item_group_headersTableAdapter.Fill(Me.Main_POSDataSet.pos_promotion_item_group_headers)
I am filling the combobox with value from oracle, but getting the selected value from sql and storing it to sql too.
I am getting the value to fill in the form from "Main_POSDataSet.pos_promotion_item_group_headers", however I want to tell the form or the dataset or the combobox that the value retrieved from the "IT_ORG_CODE" column is to be used as combobox value-member and not display member.
is there anyway to solve this please ?
237 is the organisation id to use as combobox valuemember, but here it is used as display member !!
Just replace
Me.IT_ORG_CODEComboBox.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.Pos_promotion_item_group_headersBindingSource, "IT_ORG_CODE", True))
With
Me.IT_ORG_CODEComboBox.DataBindings.Add(New System.Windows.Forms.Binding("SelectedValue", Me.Pos_promotion_item_group_headersBindingSource, "IT_ORG_CODE", True))
in the form designer code

Using DataView with DataGridView breaks connection with BindingNavigator

Having trouble with a form with both a Datagridview control and a BindingNavigator control.
Initially I had the following code:
BS = New BindingSource(DS, dsTable) ' (earlier code) Dim BS as New BindingSource
BNV1.BindingSource = BS ' A BindingNavigator
DGV1.DataSource = BS ' A DataGridView
Everything worked well but when I inserted a new row it was displayed at the end of the DataGridView's list and I wanted it to show in the correct sequential location.
I found a recommendation in a forum somewhere that suggested using a DataView on the Datatable to solve this issue. I tried it and it worked great - almost.
Here's the new code:
BS = New BindingSource(DS, dsTable)
DV.Table = DS.Tables(dsTable) ' (earlier code) Dim DV as New DataView
DV.Sort = DS.Tables(dsTable).Columns(0).ColumnName
DGV1.DataSource = DV < ---- instead of the BindingSource 'BS'
BNV1.BindingSource = BS
New records were displayed right in the correctly sequenced location - but -
The BindingNavigator did not change as I scrolled the DataGridView. It never reflected the correct record number.
But when you clicked on the BindingNavigator's moveNext, Previous, Start and End arrows it changed the count correctly. Nothing happened in the
DataGridView but it seems like the BindingNavigator was tracking something else behind the scenes. I suppose it was the original table.
Any idea how to get the BindingNavigator sync'd to the DataView? So the DatagridView and BindingNavigator are looking at the same data?
(I know I can solve this by refilling the DataGridView each time but that seems wastefiul in resources.)
Additional Info: Code that actually does the Insert/ADD
Dim NewRow As DataRow = DT.NewRow
modCommonMaint.FillNewRow(NewRow, pnlData, dicFields)
NewRow(CntText + 1) = 0
NewRow(CntText + 2) = NewRow(0).ToString
LastAdd = txtID.Text.ToUpper.Trim
DT.Rows.Add(NewRow)
DGV1.Refresh()
Try
DA.InsertCommand = cmdA
DA.UpdateCommand = cmdU
DA.Update(DS, dsTable)
Catch ex As Exception
Console.WriteLine("Error" & ex.ToString)
Finally
End Try
This is the code that actually does the INSERT/ADD. It does NOT change under either scenario. To change the behavior all I do is swap the lines in the first 2 code blocks of this note.

Slow DataGridView Drawing\Rendering

I'm using a DataGridView to load data from a DataTable. This DataGridView is located on a tab (Forms.TabPage). When clicking this tab the datagrid takes a second or two to draw from the top down, regardless of wheather data is being loaded or not.
Is there anything I can do to speed up the Drawing\Rendering when clicking the Tab?
I Don't think the actual population of the DGV is causing this, as it's filled during form load so by the time the tabs click it would have loaded the few rows (20 - 30) it displays.
Using cn As New SqlConnection(connectionString)
Using cmd As SqlCommand = cn.CreateCommand()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = _
" SELECT [finish_time], [file_name], [transfer_status]" & _
" FROM dbo.[transfer_log]"
cmd.Notification = Nothing
cn.Open()
Dim columnSpec = New DataColumn()
With columnSpec
.DataType = GetType(System.String)
.ColumnName = "ClmFinishTime"
End With
Datatable1.Columns.Add(columnSpec)
Dim columnSpec2 = New DataColumn()
With columnSpec2
.DataType = GetType(System.String)
.ColumnName = "ClmFilename"
End With
Datatable1.Columns.Add(columnSpec2)
Dim columnSpec3 = New DataColumn()
With columnSpec3
.DataType = GetType(System.Byte())
.ColumnName = "ClmStatus"
End With
Datatable1.Columns.Add(columnSpec3)
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim row As DataRow = Datatable1.NewRow
row("ClmFinishTime") = dr.Item("finish_time")
row("ClmFilename") = dr.Item("file_name")
Select Case dr.Item("transfer_status")
Case 0
row("ClmStatus") = ConvertToByte(My.Resources.accept)
Case 1
row("ClmStatus") = ConvertToByte(My.Resources.remove)
End Select
Datatable1.Rows.Add(row)
End While
End Using
End Using
DataGridView2.AutoGenerateColumns = False
DataGridView2.DataSource = Datatable1
I fixed this by double buffering the control:
Public Shared Sub SetDoubleBuffered(ByVal control As Control)
GetType(Control).InvokeMember("DoubleBuffered", BindingFlags.SetProperty Or BindingFlags.Instance Or BindingFlags.NonPublic, Nothing, control, New Object() {True})
End Sub
My two cents on this. I had a DGV that was extremely slow, even with only 100 records. Running the query wasn't the issue -- it returned results in milliseconds.
I tried the various 'doublebuffer' techniques, to no avail.
With my DGV on a TabControl, I was thinking there was possibly an issue with TabControls + DGVs.
To troubleshoot this, I created a new form, added a DGV, and had it populate the DGV on the form load event. I was quite happy to see the data loaded instantly.
I then started going through each property I had set on my original DGV, changing only one at a time, then opening the form. The DGV loaded instantly, until I set the RowHeadersWidthSizeMode. The default setting for this is 'EnableResizing', whereas my original, slow DGV had been changed to 'AutoSizeToAllHeaders'.
vs.
Sure enough, setting this back to the default of 'EnableResizing' resolved my slow DGV issue. I'm able to reproduce this side-by-side. Leave the DGV # 'EnableResizing', DGV loads instantly. Change it to 'AutoSizeToAllHeaders' and it takes 1-2 seconds before the DGV loads.
Just thought I'd share my experience with this.
Alternatively to #madlan simply set the DoubleBuffered property in the constructor by inheriting the control.
public class DoubleBufferedDataGridView : DataGridView
{
public DoubleBufferedDataGridView() : base()
{
this.DoubleBuffered = true;
}
}
I had a similar problem due to placing the DataGridView object into a TableLayoutPanel. The default behavior in Visual Studio of a TableLayoutPanel has the following property:
Focus -> CausesValidation = True
Due to this, it was taking up to 10 minutes to populate the DataGridView from a large DataTable.
In the Forms Designer, I set this value to
Focus -> CausesValidation = False
My DataGridView now works properly, it redraws in a second or less, and its data source is linked to a DataTable containing 2,000 rows and 100 columns, some cells holding text of up to 32,767 characters. Its response to the user editing cells etc. has no apparent delay.