Adding item in combobox - vb.net

I want to add a item to combobox which already in bounded with some data.
Code:
Public Sub showSection()
sb = New StringBuilder()
sb.Remove(0, sb.Length)
sb.Append("SELECT DISTINCT Section ")
sb.Append(" FROM Employee ")
sb.Append(" ORDER BY Section")
Dim sqlSection As String = sb.ToString()
da = New SqlDataAdapter(sqlSection, Conn)
da.Fill(ds, "Section")
dt = ds.Tables("Section")
bs.DataSource = dt
With cbSection
.DisplayMember = "Section"
.ValueMember = "Section"
.DataSource = ds.Tables("Section")
.DataBindings.Add("SelectedValue", bs, "Section")
End With
End Sub
But I want add item, like "---All---", so this is should be the output.
---All---
HR
Store
Packing
Training
Qc
Qa
Stock

Here's the simple solution
Dim dr As DataRow = dt.NewRow()
dr("Section") = "---All---"
dr("SectionId") = 0
dt.Rows.InsertAt(dr, 0)
With cbSection
.DisplayMember = "Section"
.ValueMember = "SectionId"
.DataSource = ds.Tables("Section")
.DataBindings.Add("SelectedValue", bs, "Section")
End With
cbSection.SelectedIndex = 0

Related

Display image in Datagridview

I am trying to display image in datagridview using ms-access and vb.net 2012.
my database in store image path does not image directly so when try to retrieve image in datagridview it shows the image path, not the image.
so how can I fix it?
Private Sub design_list_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Design_managementDataSet.design_details' table. You can move, or remove it, as needed.
'Me.Design_detailsTableAdapter.Fill(Me.Design_managementDataSet.design_details)
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Design Management\Database\design_management.accdb"
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
designDatagridShow()
End Sub
Private Sub designDatagridShow()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("select * from design_details", cnn)
da.Fill(dt)
design_datagridview.AutoGenerateColumns = False
Dim ColImage As New DataGridViewImageColumn
Dim Img As New DataGridViewImageCell
design_datagridview.ColumnCount = 3
design_datagridview.Columns(0).Name = "design_number"
design_datagridview.Columns(0).HeaderText = "Design Number"
design_datagridview.Columns(0).DataPropertyName = "design_number"
design_datagridview.Columns(1).Name = "design_collection"
design_datagridview.Columns(1).HeaderText = "Design Collection"
design_datagridview.Columns(1).DataPropertyName = "design_collection"
design_datagridview.Columns(2).Name = "price"
design_datagridview.Columns(2).HeaderText = "Design Price"
design_datagridview.Columns(2).DataPropertyName = "price"
design_datagridview.Columns(3).Name = "design_image"
design_datagridview.Columns(3).HeaderText = "Design Image"
design_datagridview.Columns(3).DataPropertyName = "design_image"
design_datagridview.DataSource = dt
Dim value As String
value = design_datagridview.Columns(3).HeaderText = "design_image"
Label1.Text = value
cnn.Close()
End Sub
Update 1:
Thanks.
Add another column that is of System.Drawing.Image datatype, then set the image based on your image column's path using System.Drawing.Image.FromFile(...) like the following:
Dim imageColumn As New DataColumn
imageColumn.ColumnName = "ActualImage"
imageColumn.DataType = GetType(System.Drawing.Image)
dt.Columns.Add(ImageColumn)
For Each row As DataRow in dt.Rows
row("ActualImage") = System.Drawing.Image.FromFile(row("design_image"))
Next
dt.AcceptChanges()
Dim dgvImageColumn As New DataGridViewImageColumn
dgvImageColumn.DataPropertyName = "ActualImage"
dgvImageColumn.Name = "ActualImage"
dgvImageColumn.ImageLayout = DataGridViewImageCellLayout.Zoom
design_datagridview.Columns.Add(dgvImageColumn)
design_datagridview.DataSource = dt

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

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

while filling data grid view using sql reader application getting slow

I have a windows form...i am trying to fill my data grid view using sql datareader,,
while clicking button i try to fill my data grid view..
i wrote one function for filling grid view..
Sub filldgv()
DGVReleased.Rows.Clear()
Dim carid As String
Dim VehicleNo As String
Dim DriverID As String
Dim krrt As Integer
Dim Dt As Integer
Dim cmd As New SqlCommand("IBS_fetchresleaseVehicle", con.connect)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#locid", SqlDbType.Int).Value = Glocid
dr = cmd.ExecuteReader
While dr.Read
If dr("TBarcode") Is DBNull.Value Then
carid = ""
Else
carid = dr("TBarcode")
End If
If dr("PlateNo") Is DBNull.Value Then
VehicleNo = ""
Else
VehicleNo = dr("PlateNo")
End If
If dr("DelEcode") Is DBNull.Value Then
DriverID = ""
Else
DriverID = dr("DelEcode")
End If
If dr("KRRT") Is DBNull.Value Then
Else
krrt = dr("KRRT")
End If
If dr("DT") Is DBNull.Value Then
Else
Dt = dr("DT")
End If
Dim row0 As String() = {carid, VehicleNo, DriverID, krrt, Dt}
DGVReleased.Rows.Insert(0, row0)
End While
dr.Close()
con.disconnect()
End Sub
then i am calling this function in my button click event.here first am removing all records from grid view then i am filling..while coming more records to data grid view my system is getting hang..is there any way to do this very simple manner..any help is very appreciable..
use DataGridView.Rows.AddRange. Collect data in List(Of DataGridViewRow), then only after the loop add them to the DataGridView:
Sub filldgv()
Dim ListRows As New List(Of DataGridViewRow)()
Dim cmd = New SqlCommand("IBS_fetchresleaseVehicle")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = con.connect
cmd.Parameters.Add("#locid", SqlDbType.Int).Value = Glocid
Dim dr = cmd.ExecuteReader
Dim ListRows As New List(Of DataGridViewRow)()
While dr.Read
Dim DgvRow = New DataGridViewRow
Dim o = {dr("TBarcode").ToString(),
dr("PlateNo").ToString(),
dr("DelEcode").ToString(),
If(IsDBNull(dr("KRRT")), 0, dr("KRRT")),
If(IsDBNull(dr("DT")), 0, dr("DT")) }
DgvRow.CreateCells(o)
ListRows.Add(DgvRow)
End While
dr.Close()
con.disconnect()
Dim SavedBool = DGVReleased.AllowUserToAddRows
DGVReleased.AllowUserToAddRows = False
DGVReleased.Rows.AddRange(ListRows.ToArray())
DGVReleased.AllowUserToAddRows = SavedBool
End Sub
Use DataTable & DataBinding, then populate DataTable in Background-Thread:
Sub filldgv()
Dim dt As New DataTable
dt.Columns.Add("", GetType(String))
dt.Columns.Add("", GetType(String))
dt.Columns.Add("", GetType(String))
dt.Columns.Add("", GetType(Integer))
dt.Columns.Add("", GetType(Integer))
DGVReleased.DataSource = dt
Task.Factory.StartNew(Sub() Populate(dt))
''you can replace last line with this:
'Dim bgw = New BackgroundWorker()
'AddHandler bgw.DoWork, Sub() Populate(dt)
'bgw.RunWorkerAsync()
End Sub
Sub Populate(dt As DataTable)
Dim cmd = New SqlCommand("IBS_fetchresleaseVehicle")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = con.connect
cmd.Parameters.Add("#locid", SqlDbType.Int).Value = Glocid
Dim dr = cmd.ExecuteReader
While dr.Read
Dim o = {dr("TBarcode").ToString(),
dr("PlateNo").ToString(),
dr("DelEcode").ToString(),
If(IsDBNull(dr("KRRT")), 0, dr("KRRT")),
If(IsDBNull(dr("DT")), 0, dr("DT")) }
dt.Rows.Add(o)
End While
dr.Close()
con.disconnect()
End Sub
Tip:
instead the if conditions, you can use shortly If Operator:
So instead:
If IsDBNull(dr("TBarcode") Then
carid = 0
Else
carid = dr("TBarcode")
End If
Written:
carid = If(IsDBNull(dr("TBarcode")), 0, dr("TBarcode"))
Thanks to #SSS: For String Fields you can simply:
carid = dr("TBarcode").ToString()

Visual basic, fill a combobox

This code gives me system.data.datarowview show in combobox.But I want to fill the combo box with data. whats the error?
Dim adclasstecher As New SqlDataAdapter
Dim tbclassteacher As New DataTable
If cnSchool.State = ConnectionState.Closed Then cnSchool.Open()
cmclassteacher.Connection = cnSchool
cmclassteacher.CommandText = "SELECT * FROM Teachers"
cmclassteacher.ExecuteNonQuery()
adclasstecher.SelectCommand = cmclassteacher
adclasstecher.Fill(tbclassteacher)
With cmbclzteachr
.DataSource = tbclassteacher
.DisplayMember = "ClassTeacher"
.SelectedIndex = 0
End With
cnSchool.Close()
Dim adclasstecher As New SqlDataAdapter
Dim tbclassteacher As New DataTable
If cnSchool.State = ConnectionState.Closed Then cnSchool.Open()
cmclassteacher.Connection = cnSchool
cmclassteacher.CommandText = "SELECT * FROM Teachers"
cmclassteacher.ExecuteNonQuery()
adclasstecher.SelectCommand = cmclassteacher
adclasstecher.Fill(tbclassteacher)
With cmbclzteachr
.DataSource = tbclassteacher
.DisplayMember = "ClassTeacher"
.SelectedIndex = 0
.databind() //you need to bind the data after providing datasource
End With
cnSchool.Close()