loop data in datalist - vb.net

How do i loop through each data in the datalist? Because i am currently getting one value from "Label8" which causes my "Label7" to show "No" for all.
Protected Sub DataList2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList2.ItemDataBound
For Each li As DataListItem In DataList2.Items
Dim labelasd As Label = DirectCast(e.Item.FindControl("**Label8**"), Label)
Dim reviewid As Integer = labelasd.Text
Dim connectionString As String = _
ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "Select Count(reviewYes) AS Expr1 From ProductReviewHelp Where ProductReviewID = " & reviewid & ""
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim countofreview As Integer = 0
Dim reviewcountboolean As Boolean
If (reader.Read()) Then
If (IsDBNull(reader.GetValue(0)) = False) Then
countofreview = reader.GetValue(0)
End If
End If
If countofreview = 0 Then
reviewcountboolean = False
Else
reviewcountboolean = True
End If
If (reviewcountboolean = True) Then
Dim label1 As Label = DirectCast(e.Item.FindControl(**"Label7"**), Label)
label1.Text = "Hello"
ElseIf (reviewcountboolean = False) Then
Dim label1 As Label = DirectCast(e.Item.FindControl(**"Label7"**), Label)
label1.Text = "No"
End If
Next
End Sub
How do i loop through each data in the datalist? Because i am currently getting one value from "Label8" which causes my "Label7" to show "No" for all.

You are looping on your DataList2 items but, at every loop, you update the label7 with the logic of the current item, effectively removing the result of the previous loop. This means that, when you reach the last item, the Label7 will reflect the string "Hello" or "No" depending on the logic applied to the last item in your loop.
Apart from this logical error, you have also numerous errors in the code shown.
The connection is never closed.
You use string concatenation instead of parameters.
You use ExecuteReader when in this case an ExecuteScalar is better
suited.

You can iterate through then using a loop here is an example
Try
readFromDL1 = DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
readFromQ = DirectCast(SqlDataSource7.Select(DataSourceSelectArguments.Empty), DataView)
Catch ex As Exception
End Try
'End
'datalist1
i = 0
_rowCount = DataList1.Items.Count
If _rowCount > 0 Then
_getCall = DataList1.Items.Item(i).FindControl("lnkEdit")
End If
For Each readr As DataRowView In readFromQ
findQNumber = readr(1).ToString()
For Each readfdlr1 As DataRowView In readFromDL1
findQNumber1 = readfdlr1(1).ToString
Try
indexofitems = DataList1.Items.Item(i1).ItemIndex
If findQNumber.ToString = findQNumber1.ToString Then
_getCall = DataList1.Items.Item(indexofitems).FindControl("lnkEdit")
_getCall.Text = "Called"
_getCall.Enabled = False
_getCall.ForeColor = Drawing.Color.Red
_getCall.BackColor = Drawing.Color.Yellow
End If
i1 = i1 + 1
Catch e As Exception
End Try
Next
i1 = 0
i = i + 1

Related

Image.FromStream is not a member of System.Windows.Forms.DataGridViewImageColumn

So I use this code to display my data in a DataGridView:
Sub display_Infodata()
DGUSERS.Rows.Clear()
Dim sql As New MySqlDataAdapter("select * from tbl_info", con)
Dim ds As New DataSet
DGUSERS.AllowUserToAddRows = False
DGUSERS.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DGUSERS.RowTemplate.Height = 40
sql.Fill(ds, 0)
For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim xx As Integer = DGUSERS.Rows.Add
Dim uid As String = ds.Tables(0).Rows(i).Item(0).ToString
Dim sqls As New MySqlDataAdapter("select * from tbl_other where userid='" & uid & "'", con)
Dim dss As New DataSet
sqls.Fill(dss, 0)
With DGUSERS.Rows(xx)
If dss.Tables(0).Rows.Count > 0 Then
.Cells(0).Value = uid
.Cells(1).Value = ds.Tables(0).Rows(i).Item(2).ToString
.Cells(2).Value = ds.Tables(0).Rows(i).Item(3).ToString
.Cells(3).Value = ds.Tables(0).Rows(i).Item(4).ToString
.Cells(4).Value = ds.Tables(0).Rows(i).Item(5).ToString
.Cells(5).Value = ds.Tables(0).Rows(i).Item(6).ToString
.Cells(6).Value = dss.Tables(0).Rows(0).Item(1).ToString
.Cells(7).Value = ds.Tables(0).Rows(0).Item(2).ToString
.Cells(8).Value = ds.Tables(0).Rows(0).Item(8).ToString
.Cells(9).Value = ds.Tables(0).Rows(0).Item("Image")
.Cells(10).Value = dss.Tables(0).Rows(0).Item(2).ToString
.Cells(11).Value = dss.Tables(0).Rows(0).Item(3).ToString
Else
End If
End With
Next
End Sub
It displays and works, but my problem is that when I try to display the data in the DataGridView of another form it shows the following error:
This is what I use:
Try
With View_Info
Dim index As Integer
Dim selectedRow As DataGridViewRow
selectedRow = DGUSERS.Rows(index)
.UserID.Text = DGUSERS.SelectedRows(0).Cells("UserID").Value
.UserType.Text = DGUSERS.SelectedRows(0).Cells("UserType").Value
.Fname.Text = DGUSERS.SelectedRows(0).Cells("Firstname").Value
.Mname.Text = DGUSERS.SelectedRows(0).Cells("Middlename").Value
.Lname.Text = DGUSERS.SelectedRows(0).Cells("Lastname").Value
.Contact.Text = DGUSERS.SelectedRows(0).Cells("Contact").Value
.Standing.Text = DGUSERS.SelectedRows(0).Cells("Standing").Value
.Guardian.Text = DGUSERS.SelectedRows(0).Cells("Guardian").Value
.ContactG.Text = DGUSERS.SelectedRows(0).Cells("GuardianContact").Value
.DPCreated.Text = DGUSERS.SelectedRows(0).Cells("DateCreated").Value
.DPValidity.Text = DGUSERS.SelectedRows(0).Cells("Validity").Value
Dim img As Byte()
img = DGUSERS.SelectedRows(0).Cells("Image").Value
Dim ms As New MemoryStream(img)
.UploadImage.Image = Image.FromStream(ms)
.Show()
.Focus()
End With
Catch ex As Exception
MsgBox(ex.Message & " Please select a corresponding records.", MsgBoxStyle.Exclamation)
End Try
Any help please?
It's hard to see the full picture, but the problem is most likely that you have created a DataGridViewImageColumn which you've chosen to call Image.
The compiler will always choose local variables, properties or classes over library/pre-imported namespace objects with the same name. Thus, your column by the name Image will be used rather than System.Drawing.Image because the former is "more local".
Try specifying the namespace as well and it should work:
.UploadImage.Image = System.Drawing.Image.FromStream(ms)
So what I did to solve this is by:
Dim pCell As New DataGridViewImageCell
pCell = Me.DGUSERS.Item("Picture", e.RowIndex)
.UploadImage.Image = byteArrayToImage(pCell.Value)
and using this function:
Private Function byteArrayToImage(ByVal byt As Byte()) As Image
Dim ms As New System.IO.MemoryStream()
Dim drwimg As Image = Nothing
Try
ms.Write(byt, 0, byt.Length)
drwimg = New Bitmap(ms)
Finally
ms.Close()
End Try
Return drwimg
End Function

data still saving on zero

in my code the data is saving if no.of days to complete=0.I want it should not happen
in my code a msg comes "time to complete and time to acknowledged can be only be posiitve" but still data saves.i dont want it to be saved !!
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Try
Dim i As Integer
If gvBanckmark.Rows.Count > 0 Then
For i = 0 To gvBanckmark.Rows.Count - 1
Dim lblBenchMarkID As Label = CType(gvBanckmark.Rows(i).FindControl("lblBenchMarkID"), Label)
Dim lblSubCategoryId As Label = CType(gvBanckmark.Rows(i).FindControl("lblSubCategoryId"), Label)
Dim ddlFrequencyTypeAcknowledge As DropDownList = CType(gvBanckmark.Rows(i).FindControl("ddlFrequencyTypeAcknowledge"), DropDownList)
Dim ddlFrequencyTypeComplete As DropDownList = CType(gvBanckmark.Rows(i).FindControl("ddlFrequencyTypeComplete"), DropDownList)
Dim txtTimeToAcknowledge As TextBox = CType(gvBanckmark.Rows(i).FindControl("txtTimeToAcknowledge"), TextBox)
Dim txtTimeToComplete As TextBox = CType(gvBanckmark.Rows(i).FindControl("txtTimeToComplete"), TextBox)
Dim objBenchMark As BO.BenchMark = New BO.BenchMark()
objBenchMark.BuildingID = Convert.ToInt32(ddlBuilding.SelectedValue)
objBenchMark.CategoryID = Convert.ToInt32(ddlCategory.SelectedValue)
objBenchMark.SubCategoryID = Convert.ToInt32(lblSubCategoryId.Text.ToString())
objBenchMark.FrequencyTypeToAcknowledge = ddlFrequencyTypeAcknowledge.SelectedValue.ToString()
objBenchMark.FrequencyTypeToComplete = ddlFrequencyTypeComplete.SelectedValue.ToString()
objBenchMark.TimeToAcknowledge = Convert.ToInt32(txtTimeToAcknowledge.Text.ToString())
objBenchMark.TimeToComplete = Convert.ToInt32(txtTimeToComplete.Text.ToString())
If lblBenchMarkID.Text.ToString() = 0 Then
objBenchMark.BenchMarkID = 0
objBenchMark.CreateByUserId = UserWrapper.GetCurrentUser().ContactID
BO.BenchMark.InsertBechMarkData(objBenchMark)
Else
objBenchMark.BenchMarkID = Convert.ToInt32(lblBenchMarkID.Text.ToString())
objBenchMark.ModifiedByUserId = UserWrapper.GetCurrentUser().ContactID
BO.BenchMark.UpdateBechMarkData(objBenchMark)
End If
Next i
End If
lblError.Visible = True
lblError.Text = "<a cssClass=""messageGood"">Benchmark data has been saved sucessfully.</a>"
Catch ex As Exception
lblError.Text = ex.Message
lblError.Visible = True
End Try
End Sub
Your data is not being saved, but the message telling you the data has been saved is being presented, despite it's saved or not.
Move thses lines inside the if-end if:
lblError.Visible = True
lblError.Text = "<a cssClass=""messageGood"">Benchmark data has been saved sucessfully.</a>"

multiple SQL queries stored as vb.net variable

I know there are a few other posts about putting sql results into a vb.net variable but I just couldn't wrap my head around how they did it and how I could do it in my project.
So what I'm trying to do is query my database for 4 different values and then display each value in a certain part of the form. I was going to store the each value into a variable and then do an textbox1.text = i
Updated code for 10/5/2014
Private Sub LBmembers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBmembers.SelectedIndexChanged
Dim i As String = LBmembers.SelectedItem
Dim dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource = "Data Source= C:\members.mdb "
Dim SqlQuery As String = "SELECT StartTime, EndTime, ShipCode, CycleTime, WorkPercent, Share FROM tblMembers WHERE Member = #ID;"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(SqlQuery, con)
con.Open()
cmd.Parameters.AddWithValue("#ID", OleDb.OleDbType.VarWChar).Value = i
Using reader = cmd.ExecuteReader()
If reader.Read() Then
TBtimestart.Text = reader.ToString(0)
TBtimeend.Text = reader.ToString(1)
Dim j = Convert.ToInt32(reader.ToString(2))
TBtimecycle.Text = reader.GetInt32(3).ToString
TBmemberpercent.Text = reader.GetInt32(4)
TBmembershare.Text = reader.GetInt32(5)
If j = 1 Then
RBpro.Checked = True
ElseIf j = 2 Then
RBret.Checked = True
ElseIf j = 3 Then
RBcov.Checked = True
ElseIf j = 4 Then
RBskiff.Checked = True
ElseIf j = 5 Then
RBmack.Checked = True
ElseIf j = 6 Then
RBhulk.Checked = True
Else
RBpro.Checked = False
RBret.Checked = False
RBcov.Checked = False
RBskiff.Checked = False
RBmack.Checked = False
RBhulk.Checked = False
Exit Sub
End If
End If
End Using
con.Close()
End Using
End Using
End Sub
The exception
InvalidCastException was unhandled Specified cast is not valid.
Pops up on the line TBtimecycle.text = reader.GetInt32(3).ToString
The reader is also reading "System.Data.OleDb.OleDbDataReader" when I insert the test code "TBgrossisk.Text = reader.ToString()" into the using statement
If you look carefully to the syntax of the SELECT statement you will see that you can request any column of the table with just one query.
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBmembers.SelectedIndexChanged
if string.IsNullOrWitheSpace(ListBox1.SelectedItem.ToString()) Then
MessageBox.Show("Select an item from the Listbox")
End If
Dim member As String = ListBox1.SelectedItem
Dim dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource = "Data Source= C:\members.mdb "
Dim SqlQuery As String = "SELECT StartTime, EndTime, ShipCode, CycleTime " & _
"FROM tblMembers WHERE Member = #ID;"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(SqlQuery, con)
con.Open()
cmd.Parameters.AddWithValue("#ID", OleDb.OleDbType.VarWChar).Value = member
Using reader = cmd.ExecuteReader
if reader.Read() Then
TextBox1.Text = reader.GetString(0)
TextBox2.Text = reader.GetString(1)
Dim j = reader.GetInt32(2)
If j = 1 Then
Radio1.Checked = True
ElseIf j = 2 Then
Radio2.Checked = True
ElseIf j = 3 Then
Radio3.Checked = True
ElseIf j = 4 Then
Radio4.Checked = True
ElseIf j = 5 Then
Radio5.Checked = True
ElseIf j = 6 Then
Radio6.Checked = True
Else
Exit Sub
End If
TextBox4.Text = reader.GetInt32(3).ToString()
Else
MessageBox.Show("The search for '" & member & "' doesn't find any data")
End If
End Using
End Using
End Using
End Sub
Instead of using ExecuteScalar that returns just the first column of the first row retrieved you could use an OleDbDataReader returned by the method ExecuteReader. This object allows to access the various column in the current record using an index (or the column name). Read more about OleDbDataReader in MSDN

DataGridView Multiple Row Selection Issue

I am trying to check for multiple selections in a DataGridView with a For... Next Loop, but even though I have selected multiple rows, the only row with the property Selected=True is the first row in the selection. Is there a way around this?
MultiSelect is true on the DataGridView.
My code is as follows:
For Each dr As DataGridViewRow In dgv.Rows
If dr.Selected = True Then
intSelectedRow = dr.Index
SetTime("KeyEntry", dgv.Name, intSelectedRow)
End If
Next
Thanks
Try this:
Dim selectedItems As DataGridViewSelectedRowCollection = dgv.SelectedRows
For Each selectedItem As DataGridViewRow In selectedItems
'Add code to handle whatever you want for each row
Next
End Sub
Dim Message As String = String.Empty
Dim FNL As FinalRpt = New FinalRpt()
For Each ItemRow As DataGridViewRow In DGVItems.Rows
Dim ISSelected As Boolean = Convert.ToBoolean(ItemRow.Cells("MyChkBox").Value)
If ISSelected Then
Message &= Environment.NewLine
Message &= ItemRow.Cells("I_ID").Value.ToString()
Dim SelectedRow As Integer = DGVItems.Rows.GetRowCount(DataGridViewElementStates.Selected)
Dim RPTItemsDA As OleDbDataAdapter
Dim RPTItemsDS As DataSet
Dim I As Integer
For I = 0 To SelectedRow Step 1
RPTItemsDA = New OleDbDataAdapter("Select Distinct * From stkrpt Where I_ID = " & DGVItems.SelectedRows(I).Index.ToString() & "", DBConnect)
RPTItemsDS = New DataSet
RPTItemsDA.Fill(RPTItemsDS, "stkrpt")
FNL.DGVReport.DataSource = RPTItemsDS
FNL.DGVReport.DataMember = "stkrpt"
Next
FNL.MdiParent = MDIParent1
FNL.StartPosition = FormStartPosition.CenterScreen
FNL.WindowState = FormWindowState.Maximized
Me.Hide()
FNL.Show()
ISSelected = False
End If
Next
MessageBox.Show(Message)

Need to populate a Dropdown combo box in Gridview, (unbound column)

I'm having difficulty populating a dropdown list in my gridview.
I have created the column with the code below:
If Not Me.GridViewIsConstructed Then
gv.Columns.Add(createComboBoxWithDDL(Me.ddlGPField.Items, "Bank_GP_Field_Name", "GPField"))
gv.Columns.Add(createComboBoxWithDDL(Me.ddlBankField.Items, "Bank_Bank_Field_Name", "BankField"))
End IF
Private Function createComboBoxWithDDL(ByVal obj As Object, ByVal nDataFieldName As String, ByVal nColName As String) As DataGridViewComboBoxColumn
Dim combo As New DataGridViewComboBoxColumn
combo.DataSource = obj
combo.DataPropertyName = nDataFieldName
combo.Name = nColName
Return combo
End Function
The problem is that I cannot get the formatting handle to populate the combo box with the index that I need. here is my code attempts for the BankField DropDown List.
If e.ColumnIndex = gv.Columns("BankField").Index Then
e.FormattingApplied = True
Dim _row = gv.Rows(e.RowIndex)
Dim _cell As New DataGridViewComboBoxColumn
fillGPFieldList(_cell)
_cell.DisplayIndex = 1
_cell.DisplayMember = "Credit"
_cell.ValueMember = "Credit"
_cell.DataSource = _cell.Items
e.Value = _cell
End If
If e.ColumnIndex = gv.Columns("TrxType").Index Then
e.FormattingApplied = True
e.Value = "BAL"
End If
The Gridview displays the dropdown object just fine, its just always set to index -1.
Please help
V*********** Addendum Edit ***********V
Unfortunately, no one answered my question. So I worked around the entire problem. Its ugly and I would greatly appreciate any feedback.
I was never able to get the ComboBox to bind to the data source. I tried everything until I turned blue. So I went to the basics and coded all the automatic stuff. I'm curious as to why the automatic binding didn't work. Perhaps its because my gridview datasource was LINQ.
Here is how I pulled it off. I hope someone down the road benefits from the last 48 hours of my delima:
First of all, know that I have two drop down lists on my form, one is the GPField and the other is the BankField. These are already populated DDLs that are static. So I used them to cheat on the values instead of using enums.
I don't think it matters, but here is how I fill the GPField and BankField:
Sub fillGPFieldListDDL(ByVal obj As Object)
Dim db As New CompanyDataDataContext
Dim myConn As New Connection With {.ConnCls = ConnCls}
myConn.dbConnect(db)
'Setup the GP Field list
obj.Items.Clear()
For Each fld In db.getGPFieldList(Me.ddlImportID.SelectedItem, ddlImportTypes.BNKREC_IMPORTS_WORK)
obj.Items.Add(fld.Trim)
Next
db.Connection.Close()
db.Connection.Dispose()
db.Dispose()
End Sub
Sub fillBankFieldListDDL(ByVal obj As Object)
If String.IsNullOrEmpty(ddlImportID.Text) Then
Return
End If
Dim db As New CompanyDataDataContext
Dim myConn As New Connection With {.ConnCls = ConnCls}
myConn.dbConnect(db)
'Setup the Bank Field list
obj.Items.Clear()
For Each fld In db.getImportIDVirtualFields(Me.ddlImportID.Text, ddlImportTypes.BNKREC_IMPORTS_WORK)
obj.Items.Add(fld.Trim)
Next
db.Connection.Close()
db.Connection.Dispose()
db.Dispose()
End Sub
Next, based on a selection from the user, I populate my grid with the following function:
Function fillToleranceFieldsGridView(ByVal nTrxType As String) As Integer
Dim myConn As New Connection With {.ConnCls = ConnCls}
Try
Using db As New CompanyDataDataContext
myConn.dbConnect(db)
'Dim _query As IEnumerable(Of TWO_Tolerance_Field) = (From tf In db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord) _
' Select tf)
'Dim _query2 As IEnumerable(Of TWO_Tolerance_Field) = db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord)
Dim _query3 = (From t In db.TWO_Tolerance_Fields _
Where t.TRXTYPESTRING = nTrxType And t.RCRDTYPE = BankToleranceRecordTypes.MasterRecord _
Select t.Bank_Bank_Field_Number, t.Bank_GP_Field_Name, t.TRXTYPESTRING)
Dim gv = Me.DataGridViewX1
gv.AutoGenerateColumns = False
gv.AllowUserToAddRows = False
gv.AllowUserToDeleteRows = False
gv.AllowUserToResizeRows = False
gv.AutoSize = True
gv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
'gv.DataSource = _query3
If Not Me.GridViewIsConstructed Then
'Add in the combo box for GPField Names
Dim _comboCol As DataGridViewComboBoxColumn
_comboCol = CreateComboBoxColumn(Me.ddlGPField.Items, _
ColumnNameData.Bank_GP_Field_Name.ToString, _
FieldNames.GPField.ToString)
gv.Columns.Add(_comboCol)
_comboCol = CreateComboBoxColumn(Me.ddlBankField.Items, _
ColumnNameData.Bank_Bank_Field_Number.ToString, _
FieldNames.BankField.ToString)
gv.Columns.Add(_comboCol)
Dim col As DataGridViewColumn = _
New DataGridViewTextBoxColumn()
Dim _cell = New DataGridViewTextBoxCell
Dim _coll = New DataGridViewColumn(_cell)
Dim _colIndex As Integer = 0
''Bind to an existing column Left in for easy access for a simple text box
'_coll = New DataGridViewColumn(_cell)
'_coll.Name = ColumnNameData.Bank_GP_Field_Name.ToString
'_coll.ReadOnly = True
'_coll.HeaderText = ColumnNameData.Bank_GP_Field_Name.ToString
'_colIndex = gv.Columns.Add(_coll)
'gv.Columns(_colIndex).DataPropertyName = ColumnNameData.Bank_GP_Field_Name.ToString
Me.GridViewIsConstructed = True
End If
gv.Rows.Clear()
Dim ri As Integer = 0
For Each r In _query3
Dim _row As New DataGridViewRow
_row.CreateCells(gv)
_row.Cells(FieldNames.GPField).Value = r.Bank_GP_Field_Name.ToString.Trim
_row.Cells(FieldNames.BankField).Value = ddlBankField.Items(r.Bank_Bank_Field_Number - 1).ToString.Trim
gv.Rows.Add(_row)
ri += 1
Next
db.Connection.Close()
db.Connection.Dispose()
End Using
Return 0
Catch ex As Exception
Throw ex
Finally
myConn.Dispose()
End Try
End Function
So, the unanswered questions are:
1). I couldn't use the _query or _query2 as datasources for the gridview, but _query3 did work for simple textboxes.
2). If using _query3 as the gv.datasource, why would my combobox throw "bank_gp_field_name" not found error when the gv.Columns.Add(_comboCol) was executed
3). I understand the reason I couldn't do a gv bind to _query3 because of the data in Bank_Bank_field_number is an integer and the DDL values don't have a translation between the integer and the string value. But I commented out that field expecting the GPField to operate on a standard bind. I still got the "Field called "Bank_GP_Field_Name" does not exist on gv.Columns.Add(_comboCol)
So, summed up, why doesn't the code below work whereas the one above does?
Function fillToleranceFieldsGridView(ByVal nTrxType As String) As Integer
Dim myConn As New Connection With {.ConnCls = ConnCls}
Try
Using db As New CompanyDataDataContext
myConn.dbConnect(db)
'Dim _query As IEnumerable(Of TWO_Tolerance_Field) = (From tf In db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord) _
' Select tf)
'Dim _query2 As IEnumerable(Of TWO_Tolerance_Field) = db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord)
Dim _query3 = (From t In db.TWO_Tolerance_Fields _
Where t.TRXTYPESTRING = nTrxType And t.RCRDTYPE = BankToleranceRecordTypes.MasterRecord _
Select t.Bank_Bank_Field_Number, t.Bank_GP_Field_Name, t.TRXTYPESTRING)
Dim gv = Me.DataGridViewX1
gv.AutoGenerateColumns = False
gv.AllowUserToAddRows = False
gv.AllowUserToDeleteRows = False
gv.AllowUserToResizeRows = False
gv.AutoSize = True
gv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
gv.DataSource = _query3
If Not Me.GridViewIsConstructed Then
'Add in the combo box for GPField Names
Dim _comboCol As DataGridViewComboBoxColumn
_comboCol = CreateComboBoxColumn(Me.ddlGPField.Items, _
ColumnNameData.Bank_GP_Field_Name.ToString, _
FieldNames.GPField.ToString)
gv.Columns.Add(_comboCol)
'_comboCol = CreateComboBoxColumn(Me.ddlBankField.Items, _
' ColumnNameData.Bank_Bank_Field_Number.ToString, _
' FieldNames.BankField.ToString)
'gv.Columns.Add(_comboCol)
Dim col As DataGridViewColumn = _
New DataGridViewTextBoxColumn()
Dim _cell = New DataGridViewTextBoxCell
Dim _coll = New DataGridViewColumn(_cell)
Dim _colIndex As Integer = 0
''Bind to an existing column Left in for easy access for a simple text box
'_coll = New DataGridViewColumn(_cell)
'_coll.Name = ColumnNameData.Bank_GP_Field_Name.ToString
'_coll.ReadOnly = True
'_coll.HeaderText = ColumnNameData.Bank_GP_Field_Name.ToString
'_colIndex = gv.Columns.Add(_coll)
'gv.Columns(_colIndex).DataPropertyName = ColumnNameData.Bank_GP_Field_Name.ToString
Me.GridViewIsConstructed = True
End If
'gv.Rows.Clear()
'Dim ri As Integer = 0
'For Each r In _query3
' Dim _row As New DataGridViewRow
' _row.CreateCells(gv)
' _row.Cells(FieldNames.GPField).Value = r.Bank_GP_Field_Name.ToString.Trim
' _row.Cells(FieldNames.BankField).Value = ddlBankField.Items(r.Bank_Bank_Field_Number - 1).ToString.Trim
' gv.Rows.Add(_row)
' ri += 1
'Next
db.Connection.Close()
db.Connection.Dispose()
End Using
Return 0
Catch ex As Exception
Throw ex
Finally
myConn.Dispose()
End Try
End Function
Private Function CreateComboBoxColumn(ByVal obj As ComboBox.ObjectCollection, ByVal nDataFieldName As String, ByVal nColName As String) _
As DataGridViewComboBoxColumn
Dim column As New DataGridViewComboBoxColumn()
With (column)
.HeaderText = nColName
.DropDownWidth = 160
.Width = 90
.MaxDropDownItems = 3
.FlatStyle = FlatStyle.Flat
.DataSource = obj
.DataPropertyName = nDataFieldName
.Name = nColName
.ValueMember = nDataFieldName
.DisplayMember = .ValueMember
End With
Return column
End Function
Sorry if I've misunderstood or over simplified this but from what I gather the combox is binding fine you just cant set the index to 1? Is this because there is no underlying data for that cell?
Have you tried setting the default value of the column? From what I've read DataGridViewComboBoxColumn doesn't have a cell DefaultValue but works with column default.
Columns("ColumName").DefaultValue = 1
http://msdn.microsoft.com/en-us/library/system.data.datacolumn.defaultvalue.aspx
You could also try handling DefaultValuesNeeded
Private Sub gv_DefaultValuesNeeded(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) _
Handles gv.DefaultValuesNeeded
With e.Row
.Cells("GPField") = 1
.Cells("BankField") = 1
End With
End Sub
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.defaultvaluesneeded(v=vs.110).aspx