Highlight a row in Datagridview based on textbox value - vb.net

Good Evening.
I have a program in VB.Net that refreshes datagridview after you edit some data my problem here is im populating over 1000 records.
Let say Im editing row 999 and after i click update the data will refresh causing the datagridview to return at the top (The blue highlighter)
My goal here is how can I maintain it to its current position after update?
My solution here is highlight the data where Textbox1 = value
Is this possible like this?
'SAMPLE CODE
Datagridview1.Column(0).value.BlueHighLighter = Textbox1.text
Pls see my code on how i refresh DGV
Dim con11 As MySqlConnection = New MySqlConnection("server=192.168.2.87;userid=root;password=admin1950;database=inventory")
Dim sql1 As MySqlCommand = New MySqlCommand("select PONo,ItemCode,Description,QtyPack,PackUoM,QtyStan,StanUoM,UnitPrice,Total,Remarks,ExpiryDate from Receiving where RINo = '" & Add_Receiving_Items.TextBox1.Text & "';", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
Add_Receiving_Items.DataGridView1.DataSource = ds1.Tables(0)
con1.close()
With Add_Receiving_Items.DataGridView1()
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "PO No"
.Columns(1).HeaderCell.Value = "Item Code"
.Columns(2).HeaderCell.Value = "Description"
.Columns(3).HeaderCell.Value = "Quantity/Pack"
.Columns(4).HeaderCell.Value = "Packaging UoM"
.Columns(5).HeaderCell.Value = "Quantity/Pc"
.Columns(6).HeaderCell.Value = "Standard UoM"
.Columns(7).HeaderCell.Value = "Unit Price"
.Columns(8).HeaderCell.Value = "Total"
.Columns(9).HeaderCell.Value = "Remarks"
.Columns(10).HeaderCell.Value = "Expiry Date"
End With
Add_Receiving_Items.DataGridView1.Columns.Item(0).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(1).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(2).Width = 120
Add_Receiving_Items.DataGridView1.Columns.Item(3).Width = 86
Add_Receiving_Items.DataGridView1.Columns.Item(4).Width = 68
Add_Receiving_Items.DataGridView1.Columns.Item(5).Width = 75
Add_Receiving_Items.DataGridView1.Columns.Item(6).Width = 68
Add_Receiving_Items.DataGridView1.Columns.Item(7).Width = 70
Add_Receiving_Items.DataGridView1.Columns.Item(8).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(9).Width = 105
Add_Receiving_Items.DataGridView1.Columns.Item(10).Width = 63
Add_Receiving_Items.DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Add_Receiving_Items.DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
With Add_Receiving_Items.DataGridView1
.RowsDefaultCellStyle.BackColor = Color.WhiteSmoke
.AlternatingRowsDefaultCellStyle.BackColor = Color.Lavender
End With
TYSM for future help

Use DataGridView.CurrentRow property. But please be aware that CurrentRow is ReadOnly, you must use CurrentCell
Before refreshing your data store Dim oldIndex = DataGridView.CurrentRow.Index and after the refresh set DataGridView.CurrentCell = DataGridView.Rows(oldIndex).Cells(0)
EDIT:
How to test the Code
Create a form with a Button1 and a DataGridView1 with two columns and paste the following code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i = 1 To 5
DataGridView1.Rows.Add("foo" & i, "bar" & i)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim currentIndex = DataGridView1.CurrentRow.Index
currentIndex += 1
If currentIndex >= DataGridView1.Rows.Count Then currentIndex = 0
DataGridView1.CurrentCell = DataGridView1.Rows(currentIndex).Cells(0)
End Sub
End Class
EDIT:
Dim oldIndex = DataGridView.CurrentRow.Index
'Put your code here on how you refresh your data
DataGridView.CurrentCell = DataGridView.Rows(oldIndex).Cells(0)

Related

Display image from filename in a database record to a datagridview

I want to display the picture found in the file location that is in the field "Picture" I have this code that shows the fields in the datagridview but I cannot figure how to properly code image from file.
Update - this below code works fine
enter code here
Imports System.Data.OleDb
Public Class test
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Private Sub test_Load(sender As Object, e As EventArgs) Handles MyBase.Load
getthedata() ' this does a query and adds a column to the query data datatable
Filldatagrid() ' This fills the datagridview named DG1
End Sub
Sub getthedata()
sel = "select * from dog"
DataConnection()
cmd = New OleDbCommand(sel, con)
ds.Tables.Add(dt)
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
Dim imageColumn As New DataColumn
imageColumn.ColumnName = "Picture"
imageColumn.DataType = GetType(System.Drawing.Image)
dt.Columns.Add(imageColumn)
For Each row As DataRow In dt.Rows
row("Picture") = System.Drawing.Image.FromFile(row("pic"))
Next
dt.AcceptChanges()
con.Close()
End Sub
Sub Filldatagrid()
dg1.AutoGenerateColumns = False
dg1.RowTemplate.Height = 150 ' this is the larger size to accomodate the image
dg1.ColumnCount = 4
dg1.DataSource = dt
dg1.Columns(0).DataPropertyName = "ID"
dg1.Columns(0).Visible = False
dg1.Columns(1).HeaderText = "Name"
dg1.Columns(1).DefaultCellStyle.Font = New Font("Tahoma", 15)
dg1.Columns(1).DefaultCellStyle.ForeColor = Color.DarkGreen
dg1.Columns(1).DataPropertyName = "Nam"
dg1.Columns(1).Width = 100
dg1.Columns(2).HeaderText = "Birthday"
dg1.Columns(2).DefaultCellStyle.Font = New Font("Tahoma", 15)
dg1.Columns(2).DataPropertyName = "Birth"
dg1.Columns(2).Width = 150
dg1.Columns(3).DataPropertyName = "Pic"
dg1.Columns(3).Visible = False
Dim dgvImageColumn As New DataGridViewImageColumn
dgvImageColumn.DataPropertyName = "Picture"
dgvImageColumn.Width = 150
dgvImageColumn.ImageLayout = DataGridViewImageCellLayout.Zoom
dg1.Columns.Add(dgvImageColumn)
End Sub
End Class
The database records are:
Id Nam Birth Pic Comments
1 Brody 5/15/2015 C:\Users\JRS89\Dropbox\Photos\dogs\Brody\Brody.jpg
2 Bella 5/1/2015 C:\Users\JRS89\Dropbox\Photos\dogs\Bella\Bella.jpg
3 Benji 5/15/2016 C:\Users\JRS89\Dropbox\Photos\dogs\Benji\Benji.jpg

DataGridView moves rows to bottom when cell is updated with Unbound data

I have a DataGridView that is styled with code and is using data from a SQLite Database
The Database is NOT bound to the DataGridView. A number of events are triggered when I click on a row.
First the Database is updated with today's date.
And the cell that contain's that date reflects the change.
I then call a sort on the column based on the cells value. With this code
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
The process works as expected with no issues IF I omit these lines of code from the Sub Routine ViewSearches() that populates the DataGridView.
If rowCount <= 25 Then
maxRowCount = 25 - rowCount
For iA = 1 To maxRowCount
dgvLinks.Rows.Add(" ")
Next
End If
I can use these empty rows if I make a call to repopulate the DataGridView with ViewSearches()
I am trying to avoid this design as it seems like a over use of resource.
The ERROR that is happening is the 4 rows that contain data are moved to the bottom of the DataGridView and above these 4 rows with data are the empty rows. I will post the relevant code below.
My question How can I keep the empty rows and populate DataGridView so the rows with data are at the top of the DataGridView?
Here is a Screen Shot after I selected LID 2. It is updated and bubbled to the bottom of the DGV.
Private Sub ViewSearches()
Dim intID As Integer
Dim strChannelName As String
Dim strLinkAddress As String
Dim strLastVisit As String
Dim strLinkType As String
Dim rowCount As Integer
Dim maxRowCount As Integer
'Dim emptyStr As String = " "
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand("", conn)
'cmd.CommandText = "SELECT * FROM LinkTable"
' Line of CODE Above works with If statement in While rdr
'==========================================================
'cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = 'News'"
cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = #site"
cmd.Parameters.Add("#site", DbType.String).Value = gvSLT
Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
'dgvLinks.DataSource = rdr
'Statement Above use when DB is bound to dgvLinks
'=================================================
While rdr.Read()
intID = CInt((rdr("LID")))
strChannelName = rdr("ytChannelName").ToString
strLinkAddress = rdr("ytLinkAddress").ToString
strLastVisit = rdr("ytLastVisit").ToString
strLinkType = rdr("ytSiteType").ToString
'If strLinkType = gvSLT Then
dgvLinks.Rows.Add(intID, strChannelName, strLinkAddress, strLastVisit)
rowCount = rowCount + 1
'End If
End While
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
End Using
If rowCount <= 25 Then
maxRowCount = 25 - rowCount
For iA = 1 To maxRowCount
dgvLinks.Rows.Add(" ")
Next
End If
End Using
End Using
'FindEmpty()
End Sub
Click Event with Update to Database
Private Sub dgvLinks_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvLinks.CellClick
selRow = e.RowIndex
If e.RowIndex = -1 Then
gvalertType = "4"
frmAlert.ShowDialog()
Exit Sub
End If
'Dim col As DataGridViewColumn = Me.dgvLinks.Columns(e.ColumnIndex)
Dim row As DataGridViewRow = Me.dgvLinks.Rows(e.RowIndex)
If row.Cells(2).Value Is Nothing Then
gvalertType = "5"
frmAlert.ShowDialog()
Return
Exit Sub
ElseIf gvTxType = "View" Then
webPAGE = row.Cells(2).Value.ToString()
siteID = CInt(row.Cells(0).Value.ToString())
UpdateSiteData()
''MsgBox("Stop " & selRow)
'dgvLinks.ClearSelection()
'dgvLinks.Refresh()
'dgvLinks.RefreshEdit()
Process.Start(webPAGE)
'dgvLinks.Columns.Clear()
''dgvLinks.Rows.Clear()
''ViewSearches()
ElseIf gvTxType = "Delete" Or gvTxType = "Update" Then
gvID = CInt(row.Cells(0).Value)
gvSiteName = row.Cells(1).Value.ToString
gvSiteURL = row.Cells(2).Value.ToString
frmADE.Show()
Close()
End If
End Sub
Update Routine
Public Sub UpdateSiteData()
Dim dateToday = Date.Today
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;"),
cmd As New SQLiteCommand("UPDATE LinkTable SET ytLastVisit = #ytLastVisit WHERE LID =" & siteID, conn)
conn.Open()
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.ExecuteNonQuery()
dgvLinks.Rows(selRow).Cells(3).Value = dateToday.ToString("M-d-yyyy")
'Line of code above INSERTS value in Last Visit Column at the correct ROW
'NOT needed if you reload data from the database
'=========================================================================
'dgvLinks.Refresh()
'dgvLinks.RefreshEdit()
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
End Using
End Sub
You will see a number of things I have tried commented out.
As I said I can FIX the issue if I make a call to the ViewSearches() Sub Routine.
Private Sub StyleDGV()
'Sets Design of the DataGridView
'===============================
dgvLinks.DefaultCellStyle.Font = New Font("Times New Roman", 13.0F, FontStyle.Bold)
dgvLinks.ColumnCount = 4
dgvLinks.Columns(0).Width = 60 'ID
dgvLinks.Columns(1).Width = 325 'Site Name 325
dgvLinks.Columns(2).Width = 860 'Site Url 860
dgvLinks.Columns(3).Width = 154 'LastVisit 140
'Option with no blank rows increase col count to 5
'OR increase width of col(3) WHY? because the scroll bar is not showing
' TOTAL Width 1450 Height 488
'=============================
'To Set Col Header Size Mode = Enabled
'To Set Col Header Default Cell Styles DO in Properties
'dgvLinks.Columns(6).DefaultCellStyle.Format = "c"
dgvLinks.ColumnHeadersHeight = 10 'Sans Serif 'Tahoma
dgvLinks.ColumnHeadersDefaultCellStyle.Font = New Font("Sans Serif", 12.0F, FontStyle.Bold)
dgvLinks.ColumnHeadersDefaultCellStyle.ForeColor = Color.Blue
dgvLinks.DefaultCellStyle.BackColor = Color.LightGoldenrodYellow
'DGV Header Names
dgvLinks.Columns(0).Name = "LID"
dgvLinks.Columns(1).Name = "Site Name"
dgvLinks.Columns(2).Name = "Site URL"
dgvLinks.Columns(3).Name = "Last Visit"
dgvLinks.Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(2).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(3).SortMode = DataGridViewColumnSortMode.NotSortable
End Sub
Any one following this question the FIX that permitted keeping the empty rows was to just omit the sort command in the Update to Database Sub Routine
As far as getting the data from the SQLite DB into the grid… you almost have it in the ViewSearches method. The command text looks good; however you are using an SQLiteDataReader. This is resorting to reading the data line by line.
I suggest you use the SQLiteDataAdapter instead. With it you can get the DataTable from the DB in one shot. First create and initialize a DataSet, then create a new SQLiteDataAdapter then add your command to the data adapter something like…
DataSet ds = new DataSet();
using (SQLiteDataAdapter sqlDA = new SQLiteDataAdapter()) {
conn.Open();
sqlDA.SelectCommand = cmd.CommanText;
sqlDA.Fill(ds, “tableName”);
if (ds.Tables.Count > 0) {
//return ds.Tables[“tableName”];
dgvLinks.DataSource = ds.Tables[“tableName”];
}
}
This will add a DataTable to the DataSet ds called “tableName” if the query succeeded.
Then simply use that DataTable as a DataSource to the grid… something like…
dgvLinks.DataSource = ds.Tables[“tableName”];

How to change row color in datagridview by comparing two columns from different tables using vb.net?

No success!
If user of tblcon with billmonth of tbltrns exists in tbltrns then highlight the rows of tblcon with red color
Code:
Private Sub checkexist()
For Each row As DataGridViewRow In DataGridView1.Rows
ConObj = New SqlConnection(ConStr)
ConObj.Open()
Dim qry As String = "SELECT * FROM tblTrns WHERE userName=#userName and bill_month=#bill_month"
CmdObj = New SqlCommand(qry, ConObj)
CmdObj.Parameters.AddWithValue("#bill_month", DateTimePicker1.Text)
CmdObj.Parameters.AddWithValue("#userName", (row.Cells("User").Value.ToString))
drObj = CmdObj.ExecuteReader()
If drObj.HasRows Then
row.DefaultCellStyle.BackColor = Color.Red
End If
Next
ConObj.Close()
End Sub
Query for the Grid
Public Function GetData() As DataView
ConObj = New SqlConnection(ConStr)
ConObj.Open()
CmdObj = New SqlCommand
dsObj = New DataSet
daObj = New SqlDataAdapter()
Dim SelectQry = "SELECT UserName[User],doj[Connection Date],packagename[Package],profilename[Profile],billing[Payment],fees[Fees],connectionstatus[Status] from TblCon"
CmdObj.CommandText = SelectQry
CmdObj.Connection = ConObj
daObj.SelectCommand = CmdObj
daObj.Fill(dsObj)
TvObj = dsObj.Tables(0).DefaultView
Return TvObj
ConObj.Close()
End Function
Query Changed in getdata but no success. Please guide ...........................................................................................................................................................................................................................................
Public Function GetData() As DataView
ConObj = New SqlConnection(ConStr)
ConObj.Open()
CmdObj = New SqlCommand
dsObj = New DataSet
daObj = New SqlDataAdapter()
Dim SelectQry = Dim SelectQry = "SELECT UserName[User],doj[Connection Date],packagename[Package],profilename[Profile],billing[Payment],fees[Fees],conn‌​‌​‌​ectionstatus[Status], (SELECT ISNULL(COUNT(*), 0) FROM tblTrns WHERE tblTrns.userName = tblCon.UserName AND bill_month = '" & DateTimePicker1.Text & "') [Comparison] from TblCon"
CmdObj.CommandText = SelectQry
CmdObj.Connection = ConObj
daObj.SelectCommand = CmdObj
daObj.Fill(dsObj)
TvObj = dsObj.Tables(0).DefaultView
Return TvObj
ConObj.Close()
End Function
I recommend you to fill a new column in your grid with a value for comparison and set it's visibility to false.
You can do that by a subselect or a left join on the second table (if you wish an example just post the query that fills your grid).
Based on your comparison column you can use the CellPainting event of the GridView. Like this:
Private Sub grdGridView_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles grdGridView.CellPainting
If e.RowIndex >= 0 Then
If grdGridView.Rows(e.RowIndex).Cells("colComparison").Value <> "0" And Not IsNothing(grdGridView.Rows(e.RowIndex).Cells("colComparison").Value) Then
e.CellStyle.BackColor = Color.OrangeRed
e.CellStyle.SelectionBackColor = Color.IndianRed
End If
End If
End Sub

Populate a VB combo box from a MS Access database row

Im trying to add in a column entire row into a combobox.
When i try it either shows only the last row of the column or it shows only the last row 35 times.
What am i missing? this is driving me crazy. i apologize for the commented lines, i was experimenting with some different coding.
Option Strict On
Imports System.Data.OleDb
Imports ShadowLogin.GlobalVariables
Public Class DeptNewSch
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
ShadowMain.Show()
End Sub
Private Sub DeptNewSch_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim CourseArray(35, 2) As String
Using cnnOLEDB = New OleDbConnection(strConnectionString)
Dim NewSchDS As DataSet
Dim NewSchTables As DataTableCollection
Dim NewSchsource1 As New BindingSource
NewSchDS = New DataSet
NewSchTables = NewSchDS.Tables
Using cmd As New OleDbCommand("SELECT ClassSection.CourseTitle AS Course, ClassSection.SectionNumber AS [Section Number], ClassSection.ScheduleNumber AS [Schedule Number], Course.ShortTitle AS [Course Title], Course.Units, ClassSection.Type AS Format, ClassSection.TimeSlot AS [Days / Time], ClassSection.RoomID AS Location, Faculty.[First Name], Faculty.[Last Name], Classroom.MaxCapacity AS Seats FROM [Classroom], [ClassSection], [Faculty], [Course] WHERE (ClassSection.FRedID = Faculty.FRedID) AND Course.CourseTitle = ClassSection.CourseTitle AND Classroom.RoomID = ClassSection.RoomID AND ClassSection.ScheduleYear=#Year AND ClassSection.Semester=#Semester;", cnnOLEDB)
cmd.Parameters.Add("#Year", OleDbType.VarWChar).Value = Convert.ToInt32(strYear.ToString())
cmd.Parameters.Add("#Semester", OleDbType.VarWChar).Value = strSemester.ToString()
Using NewSchDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
NewSchDA.Fill(NewSchDS, "New Semester") 'Change items to your database name
Dim view As New DataView(NewSchTables(0))
NewSchsource1.DataSource = view
dgNewSch.DataSource = view
Me.dgNewSch.Columns("Course").Width = 60
Me.dgNewSch.Columns("Section Number").Width = 50
Me.dgNewSch.Columns("Schedule Number").Width = 60
Me.dgNewSch.Columns("Course Title").Width = 190
Me.dgNewSch.Columns("Units").Width = 40
Me.dgNewSch.Columns("Format").Width = 70
Me.dgNewSch.Columns("Days / Time").Width = 100
Me.dgNewSch.Columns("Location").Width = 70
Me.dgNewSch.Columns("First Name").Width = 80
Me.dgNewSch.Columns("Last Name").Width = 80
Me.dgNewSch.Columns("Seats").Width = 50
End Using
End Using
End Using
'Connect to Database and get the registration information
Using cnnOLEDB = New OleDbConnection(strConnectionString)
' Query the classschedule table for start of semester datas
Using cmdOleDB = New OleDbCommand("SELECT [CourseTitle], [ShortTitle],[Units] FROM [Course] WHERE rownumber =#row", cnnOLEDB)
cnnOLEDB.Open()
Using rdrOLEDB = cmdOleDB.ExecuteReader
While rdrOLEDB.Read
Dim l As Integer
For l = 0 To 35
'cmdOleDB.Parameters.Add("#row", OleDbType.VarWChar).Value = l
CourseArray(l, 0) = rdrOLEDB.Item(0).ToString
CourseArray(l, 1) = rdrOLEDB.Item(1).ToString
CourseArray(l, 2) = rdrOLEDB.Item(2).ToString
Next
' CboFormat.Items.Add()
' CboDayTime.Items.Add()
' CboLocation.Items.Add()
' CboName.Items.Add()
End While
End Using
End Using
End Using
For z As Integer = 0 To 35
CboCourse.Items.Insert(z, CourseArray(z, 0).ToString)
Next
End Sub
End Class
As you can guess this is the code that ive been working on.
Any help would be great if what im trying to do is at all possible.
Your 0 to 35 loop runs each time you read a record in the datasource.
While rdrOLEDB.Read
Dim l As Integer
For l = 0 To 35
'cmdOleDB.Parameters.Add("#row", OleDbType.VarWChar).Value = l
CourseArray(l, 0) = rdrOLEDB.Item(0).ToString
CourseArray(l, 1) = rdrOLEDB.Item(1).ToString
CourseArray(l, 2) = rdrOLEDB.Item(2).ToString
Next
Name.Items.Add()
End While

Set selectedindex for comboboxcell in datagridview vb.net

I am trying to set the selectedindex for my datagridviewcomboboxcell through cellvaluechanged event,i.e when i change some value in my datagrid row, this column should get automatically changed. here's the code.
Private Sub DataGridView1_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
Try
If Me.DataGridView1.Rows(e.RowIndex).Cells(2).Value.ToString <> Nothing Then
Me.DataGridView1("unit_code", e.RowIndex).Value = "1"
MsgBox(Me.DataGridView1.Rows(e.RowIndex).Cells(6).Value)
End If
Else
Exit Sub
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
my datagridview is bound to dataset. Searched many sites and did all research, got the above solution where we need to set the valuemember to .value part. Even after doing that it givessystem.formatexception:datagridviewcomboboxcell value is not valid.
Please help me.
[EDIT]
table structure
unit_code descp
0 -
1 nos
2 kgs
3 gms
[EDIT 2]
query = "select Switch(qty=0,'2',qty<=rcvd_qty,'1',rcvd_qty=0,'2',qty>rcvd_qty,'3') as Status,item_type,catalogue,name,pd.rate,qty,pd.unit_code" _
& " from pur_det pd,itemhead th where pd.item_code=th.itemcode and order_no=0 order by catalogue"
adap1 = New OleDbDataAdapter(query, conn)
Dim saldet As New DataSet
adap1.Fill(saldet, "puritems")
Me.DataGridView1.DataSource = saldet.Tables(0)
DataGridView1.Columns.Item(0).HeaderText = "STATUS"
DataGridView1.Columns.Item(0).Width = 68
DataGridView1.Columns.Item(1).HeaderText = "TYPE"
DataGridView1.Columns.Item(1).Width = 60
DataGridView1.Columns.Item(2).HeaderText = "CATALOGUE"
DataGridView1.Columns.Item(2).Width = 140
DataGridView1.Columns.Item(3).HeaderText = "DESCRIPTION"
DataGridView1.Columns.Item(3).Width = 300
DataGridView1.Columns.Item(4).HeaderText = "RATE"
DataGridView1.Columns.Item(4).Width = 60
DataGridView1.Columns.Item(5).HeaderText = "QUANTITY"
DataGridView1.Columns.Item(5).Width = 84
DataGridView1.Columns.Item(6).HeaderText = "UNIT" ' this column is removed below because it only had primary key values of this table("unitmast").
DataGridView1.Columns.Item(6).Width = 70
adap1 = New OleDbDataAdapter("select * from unitmast order by unitcode ASC", conn)
Dim unitc As New DataSet
adap1.Fill(unitc, "unitmast")
Me.DataGridView1.Columns.RemoveAt(6) 'here the same is added with display member to view its actual value
Dim uncol As New DataGridViewComboBoxColumn
With uncol
.Name = "unit_code"
.DataPropertyName = "unit_code"
.DataSource = unitc.Tables(0)
.ValueMember = "unitcode"
.DisplayMember = "desc"
.HeaderText = "UNIT"
.FlatStyle = FlatStyle.Flat
.DropDownWidth = 160
.Width = 70
End With
Me.DataGridView1.Columns.Insert(6, uncol)
A DataGridViewComboBoxCell has no SelectedIndex or SelectedValue property.
You can set the value directly like this:
CType(Me.DataGridView1("unit_code", e.RowIndex), DataGridViewComboBoxCell).Value = "your value string"
Or using the index of the items collection: (this works only if you have not set ValueMember and DisplayMember properties)
Dim combo As DataGridViewComboBoxCell
combo = CType(Me.DataGridView1("unit_code", e.RowIndex), DataGridViewComboBoxCell)
combo.Value = combo.Items('your index')
You can also check a value for nothing like this:
If Not Me.DataGridView1.Rows(e.RowIndex).Cells(2).Value Is Nothing Then
'Your code
End If
I Write and Test that Code For You Good Luck:
Dim Dt As New DataTable
Sub CreateDT()
Dt.Columns.Add("Col1")
Dt.Columns.Add("Col2")
Dt.Rows.Add(New Object(1) {"1", "A"})
Dt.Rows.Add(New Object(1) {"2", "B"})
Dt.Rows.Add(New Object(1) {"3", "C"})
End Sub
Private Sub ChildRibbonForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CreateDT()
'
'Dim CellCol As DataGridViewComboBoxColumn = CType(DataGridView1.Columns(0), DataGridViewComboBoxColumn)
Dim CellCol As New DataGridViewComboBoxColumn
CellCol.Items.Add("Test1")
CellCol.Items.Add("Test2")
CellCol.Items.Add("Test3")
Me.DataGridView1.DataSource = Dt
Me.DataGridView1.Columns.Insert(0, CellCol)
Dim CellBox As DataGridViewComboBoxCell = CType(DataGridView1.Rows(1).Cells(0), DataGridViewComboBoxCell)
'Select the Second Item
CellBox.Value = CellCol.Items(1)
End Sub
'Declare datatable
Dim cdt as new Datatable
'Add columns with types. It is important you specify the type for value member column
cdt.Columns.Add("vm", System.Type.GetType("System.Int32"))
cdt.Columns.Add("dm", System.Type.GetType("System.String"))
'Add items to table
cdt.Rows.Add
cdt.Rows(0).Item(0) = 1
cdt.Rows(0).Item(1) = "Red Cat"
cdt.Rows.Add
cdt.Rows(1).Item(0) = 2
cdt.Rows(1).Item(1) = "Black Cat"
'Add datasource to DataGridViewComboBoxColumn
Dim cc As DataGridViewComboBoxColumn
cc = datagridview1.Columns('colIndex')
cc.DataSource = cdt
cc.ValueMember = "vm"
cc.DisplayMember = "dm"
'Setting then selected value is thus:
Datagridview1.Rows('rowIndex').Cells('colIndex').Value = 2 '2 for black cat
This works for me