I'm using a DataGrid with TabControl. When I move to the 2nd tab my data is not displaying in the datagridview. My 2nd IF statement is not getting executed, I'm not sure why either. Only the 1st statement is being execute in selectedIndex 0. Please help me out.
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
If TabControl1.SelectedIndex = 0 Then
MyCn.Open()
MyDatAdp = New SqlDataAdapter("select * from Books", MyCn)
MyCmdBld = New SqlCommandBuilder(MyDatAdp)
MyDatAdp.Fill(MyDataTbl)
DataGridView1.DataSource = MyDataTbl
MyCn.Close()
If TabControl1.SelectedIndex = 1 Then
MyCn.Open()
MyDatAdp = New SqlDataAdapter("select * from Orders", MyCn)
MyCmdBld = New SqlCommandBuilder(MyDatAdp)
MyDatAdp.Fill(MyDt2)
DataGridView2.DataSource = MyDt2
MyCn.Close()
End If
End If
End Sub
Try to change the If TabControl1.SelectedIndex To If TabControl1.SelectedTab is yourTabPage Then
And see this Link for your reference.
Related
I've been having some trouble trying to get this to work, I am trying to enter a code in the top bar, press 'Go' and it show up in the ListBox on the left. I hope one of you can help me with this, I have attached the code below for entering data from the table 'stock' from my database into the list box, however I'm stuck with narrowing it down with a search function. I have also attached an image of my form.
https://i.stack.imgur.com/zD9EZ.png
Private Sub LoadStockFromDb()
Dim stockInfo As DataRow = Nothing
Dim sql As String = "SELECT * FROM stock;"
Try
Dim current_index As Int16 = lb_stock.SelectedIndex
Using conn As New SQLiteConnection(connectionString.ToString)
Using cmd As New SQLiteCommand(conn)
cmd.CommandText = sql
conn.Open()
Using da As New SQLiteDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count > 0 Then
lb_stock.DisplayMember = "int_code"
lb_stock.ValueMember = "entry_id"
lb_stock.DataSource = dt
End If
End Using
End Using
End Using
If current_index > 0 Then
lb_stock.SelectedIndex = current_index
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I created an Autocomplete Textbox column in DataGridView (Works Fine).
See this image. This is what I have
Now there is no problem until the text size is small but when the text gets longer it doesn't get wrapped in the column, the text gets trimmed.
This is the Problem
If I set the WRAP property of the column to TRUE then the textbox stops Autocompleting.
SO, its like either auto-completing or WRAPPING, but I need both...
I am putting my code below if anything can be done within it, have a look -
Private Sub DataGridView2_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView2.EditingControlShowing
DataGridView2.BeginEdit(True)
Dim autoText As TextBox = TryCast(e.Control, TextBox)
If autoText IsNot Nothing Then
autoText.AutoCompleteMode = AutoCompleteMode.SuggestAppend
autoText.AutoCompleteCustomSource = AutoCompleteLoad()
autoText.AutoCompleteSource = AutoCompleteSource.CustomSource
End If
End Sub
Public Function AutoCompleteLoad() As AutoCompleteStringCollection
Dim str As AutoCompleteStringCollection = New AutoCompleteStringCollection()
Dim ConnectionString As SqlConnection = New SqlConnection("data source=ADMIN-PC\SQLEXPRESS; database=billdev;Trusted_Connection=yes;")
Dim strSQL As String = "SELECT particulars from bill;"
Dim SQLcommand As New SqlCommand(strSQL, ConnectionString)
ConnectionString.Open()
Dim reader As SqlDataReader
reader = SQLcommand.ExecuteReader()
While reader.Read()
str.Add(reader.Item(0))
End While
Return str
End Function
[SOLVED]
Maybe it has a bug in datagridview control.
we can do one cheat method to solve this issue.
in Datagridview_CellBegainEdit, set rowsDefaultcellstyle wrapmode = false
in DatagridView_CellEndEdit, set rowsDefaultcellstyle wrapmode = true
Example:
DGV.RowsDefaultCellStyle.WrapMode = DataGridViewTriState.False (CellBegainEdit)
DGV.RowsDefaultCellStyle.WrapMode = DataGridViewTriState.True (CellEndEdit)
Its working for me.
I'm having a hard time in DataGridView ComboBox DropDown. Can someone enlighten me on how i bind data in a custom ComboBox with a special condition in a datagridview?
something like, If the database table was read and then in a particular column "Status" was populated with 0 or 1. And then in datagridview combobox drop down it should display unattended instead of 0 and currently attended instead of 1 and then in running the program when i click attended it should be updated in database as 1.
Any advice, recommendation or tips will be greatly appreciated.
Here is my code:
Private Sub loadDataGrid()
Try
Dim TQry As String
TQry = "Select TQ.Que_No, TS.Step_Remarks, T.Trans_Name, TS.Step_No, O.Office_Name, TQ.Date_Arrive, TQ.Time_Arrive, TQ.STATUS FROM TRANS_QUEUE TQ LEFT JOIN TRANS_STEP TS ON TQ.Trans_Step_ID = TS.Trans_STep_ID LEFT JOIN TRANSACTIONS T ON TQ.Trans_ID = T.Trans_ID LEFT JOIN OFFICE O ON TQ.Office_ID = O.Office_ID"
Dim TCmd As New SqlCommand(TQry, MysqlConn)
TCmd.CommandType = CommandType.Text
Dim TDa As New SqlDataAdapter(TCmd)
Dim TDt As New DataTable
TDa.Fill(TDt)
Dim TBs As New BindingSource
TBs.DataSource = TDt
Dim comboboxColumn As New DataGridViewComboBoxColumn
Dim Status_Data() As String = New String() {"Attended", "Unattended"}
comboboxColumn.Items.AddRange(Status_Data)
comboboxColumn.Name = "Status"
comboboxColumn.MaxDropDownItems = 2
comboboxColumn.FlatStyle = ComboBoxStyle.DropDown
comboboxColumn.Resizable = DataGridViewTriState.True
DataGridView1.DataSource = TBs
DataGridView1.Columns.Remove("Status")
DataGridView1.Columns.Insert(7, comboboxColumn)
Dim CountCols As Integer
CountCols = DataGridView1.ColumnCount - 2
For index As Integer = 0 To CountCols
DataGridView1.Columns(index).ReadOnly = True
Next
Me.DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Me.DataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Catch ex As Exception
MessageBox.Show(ex.Message + " #Function GetTD()", _
"Important Note", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation, _
MessageBoxDefaultButton.Button1)
Me.Close()
End Try
End Sub
Screenshots:
Output
Database Table
i come up on this kind of sol. I discard the combobox dropdown idea and switch to normal button to make the function works and tweak the query.
in query
TQry = "Select TQ.Que_No as Queue, TS.Step_Remarks as Remarks, T.Trans_Name as Transactions, TS.Step_No as Steps, O.Office_Name as Office, TQ.Date_Arrive as Date, TQ.Time_Arrive as Time, case TQ.STATUS when 0 then 'unattended' else 'attended' end as Status FROM TRANS_QUEUE TQ LEFT JOIN TRANS_STEP TS ON TQ.Trans_Step_ID = TS.Trans_STep_ID LEFT JOIN TRANSACTIONS T ON TQ.Trans_ID = T.Trans_ID LEFT JOIN OFFICE O ON TQ.Office_ID = O.Office_ID"
in Start button
Private Sub Start_Btn_Click(sender As Object, e As EventArgs) Handles Start_Btn.Click
Dim RowSelected As Integer = Me.DataGridView1.CurrentRow.Cells(0).Value
MsgBox(RowSelected)
SelectedRow("SELECT * FROM TRANS_QUEUE WHERE Que_No like '%" & RowSelected & "%'") 'kwaon ang Que ID sa selected col
UpQuery("Update TRANS_QUEUE set Status = 1 WHERE Que_No = " & RowSelected & "") 'I update ang status sa selected col
End Sub
Public Sub SelectedRow(ByVal SQCommand As String)
MysqlConn.ConnectionString = "server=BOSS;user=sa;password=pass2017;database=DB_CFSys"
MysqlConn.Open()
Dim Cmpr_EMPLogIn As String = Login.UIDTextBox.Text
Dim SQCmd As New SqlCommand(SQCommand, MysqlConn)
Dim SQDr As SqlDataReader
SQDr = SQCmd.ExecuteReader()
SQDr.Read()
If SQDr.HasRows Then
MsgBox(SQDr.Item("Date_Arrive"))
MsgBox(SQDr.Item("Time_Arrive").ToString)
End If
MysqlConn.Close()
End Sub
Public Sub UpQuery(ByVal SQCommand As String)
MysqlConn.ConnectionString = "server=BOSS;user=sa;password=pass2017;database=DB_CFSys"
Dim SQLCMD As New SqlCommand(SQCommand, MysqlConn)
MysqlConn.Open()
SQLCMD.ExecuteNonQuery()
MsgBox("Successfully Updated")
MysqlConn.Close()
End Sub
In a switch(unattended/attended) button
Private Sub Status_Btn_Click(sender As Object, e As EventArgs) Handles Status_Btn.Click
If count_click = 1 Then
count_click = 2
Me.Status_Btn.Text = "Unattended"
loadDataGridAttended()
ElseIf count_click = 2 Then
count_click = 1
Me.Status_Btn.Text = "Attended"
loadDataGrid()
End If
End Sub
I have connected my DataGridView to a database but I can't implement the search function.
The flow of the program would be when I click one column of the DataGridView and I type in the search box, I can only get results from that same column not the other columns beside it.
It should also search letter by letter so basically a TextChanged event.
This is how i would do it
First, to have two variable to store your original datatable from database, and also a string variable to store your selected dgv column headertext (which will be used to do the filter later on).
Private oriDataTable As New DataTable
Private columnToFilter As String = String.Empty
My test on some dummy data
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'dummy datatable
oriDataTable.Columns.Add(New DataColumn("ID"))
oriDataTable.Columns.Add(New DataColumn("FirstName"))
oriDataTable.Columns.Add(New DataColumn("LastName"))
For i = 0 To 5
Dim dr As DataRow = oriDataTable.NewRow()
dr.Item("ID") = i
dr.Item("FirstName") = "fn type1 " & i
dr.Item("LastName") = "ln type1 " & i
oriDataTable.Rows.Add(dr)
Next
For i = 6 To 10
Dim dr As DataRow = oriDataTable.NewRow()
dr.Item("ID") = i
dr.Item("FirstName") = "fn type2" & i
dr.Item("LastName") = "ln type2" & i
oriDataTable.Rows.Add(dr)
Next
'Since you already connected to database
'i assume that you could fill a datatable and bind to dgv
dgvToFilter.DataSource = oriDataTable
columnToFilter = "ID" 'Assign any default column name
End Sub
Then add a ColumnHeaderMouseClick event handler on your dgv, update the columnToFilter each time when user click on it.
Private Sub dgvToFilter_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvToFilter.ColumnHeaderMouseClick
Dim clickedColumn As DataGridViewColumn = dgvToFilter.Columns(e.ColumnIndex)
'Note:HeaderText must match with your datatable column name
columnToFilter = clickedColumn.HeaderText
lblHeaderSelected.Text = columnToFilter
End Sub
And lastly the TextChaged Event. Use the DataTable.Select method to filter the datatable and update the result, if any, to the dgv.
Private Sub txtFilterText_TextChanged(sender As Object, e As EventArgs) Handles txtFilterText.TextChanged
If txtFilterText.Text.Length <= 0 Then dgvToFilter.DataSource = oriDataTable
Dim filterString = String.Format("{0} LIKE '{1}%'", columnToFilter, txtFilterText.Text)
Dim dataRows As DataRow() = oriDataTable.Select(filterString)
'Choose what you wan to do if no row is found. I bind back the oriDataTable.
dgvToFilter.DataSource = If(dataRows.Count > 0, dataRows.CopyToDataTable(), oriDataTable)
End Sub
You can try this.
Private Sub txtUname_TextChanged(sender As Object, e As EventArgs) Handles txtUname.TextChanged
dtaAdap = New SqlDataAdapter("Select * from tbl_user where Fname like '%" & txtUname.Text & "%'" & vbCrLf &
" OR Lname like '%" & txtUname.Text & "%'", con)
dt = New DataTable
dtaAdap.Fill(dt)
DataGridView1.DataSource = dt
End Sub
The query in SQLAdapter goes a little something like this:
Select * from <tbl_name> where <firstparametercolumnname> like '%"& <your searchtexboxname.text here> &"%'
OR <secondparametercolumnname> like '%"& <your searchtexboxname.text here> &"%'
and so on depending on the number of fields you want to look at. Note: "con" is my SQLConnection.
This whole code snippet will fill your DatagridView with the result of the query everytime the user key in something on your searchtextbox.
I am a Vb nooby and I have trouble to add specific Items to my Listview from a database.
I would like to compare the value of a combobox with a column value of a table.
To proof if they are equal like apple = apple
When they are equal the whole data set should be added to my ListView. (Only data sets which have the equal value like the selected item of the combobox)
Please Help !!
Thanks a lot and best regards
You can try below code..
Imports System.Data.SqlClient
Public Class Form1
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
conn = New SqlConnection("Data Source=SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;User ID=id;Password=pass")
Dim strQ As String = String.Empty
strQ = "SELECT * FROM Northwind.dbo.Products"
cmd = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
Me.ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
End Sub
End Class
You can try this link.
Thanks for your help.
In my solution, I just set a parameter into the sql statement.
Public Function getRahmenvertrag**(ByVal costumerID As Integer)** As List(Of Rahmenvertrag)
Dim sqlCom As New SqlServerCe.SqlCeCommand
sqlCom.CommandText = **"SELECT * FROM Rahmenvertrag LEFT OUTER JOIN Kunde ON Kunden_FID = Kunden_ID WHERE Kunden_ID = #Kunde "**
**sqlCom.Parameters.AddWithValue("Kunde", costumerID)**
Private Sub ComboBox1_Click(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
ListView4.DataBindings.Clear()
ListView4.Items.Clear()
If IsNothing(ComboBox1.SelectedItem) = False Then
For Each Rahmenvertrag As Rahmenvertrag In controller.getRahmenvertrag(ComboBox1.SelectedItem.kunde_ID)
With ListView4.Items.Add(Rahmenvertrag.bezeichnung)
.SubItems.Add(Rahmenvertrag.inhalt)
End With
Next
End If
End Sub