Winforms - Datagridview dynamically change linkbutton text - vb.net

I am using Winforms datagridview (n-tier architecture) to populate from a dataset. I want to have a linkbutton as the last column which should change its text based on the value of two columns. While I have managed to get the linkbutton, I cannot get the value to change. I need the value to change so that when the linkbutton is clicked, it should open up different windows. My code is as below
Private Sub ShowProductRequisitionsInListView(ByVal data As DataSet, ByVal dgv As DataGridView)
dgvRequisitionDetails.Columns.Clear()
dgvRequisitionDetails.DataSource = Nothing
dgvRequisitionDetails.DataSource = data.Tables(0)
dgvRequisitionDetails.Columns(0).Width = 80
dgvRequisitionDetails.Columns(0).HeaderText = "Product Code"
dgvRequisitionDetails.Columns(1).Width = 180
dgvRequisitionDetails.Columns(1).HeaderText = "Product Name"
dgvRequisitionDetails.Columns(2).Width = 150
dgvRequisitionDetails.Columns(2).HeaderText = "Sales UOM"
dgvRequisitionDetails.Columns(3).Width = 60
dgvRequisitionDetails.Columns(3).HeaderText = "Qty. Reqd."
dgvRequisitionDetails.Columns(3).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvRequisitionDetails.Columns(3).DefaultCellStyle.Format = "N3"
dgvRequisitionDetails.Columns(4).Width = 105
dgvRequisitionDetails.Columns(4).HeaderText = "Qty. In Stock"
dgvRequisitionDetails.Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgvRequisitionDetails.Columns(4).DefaultCellStyle.Format = "N3"
Dim lnk As DataGridViewLinkColumn = New DataGridViewLinkColumn
dgvRequisitionDetails.Columns.Add(lnk)
lnk.HeaderText = "Action"
lnk.Text = "Click Here"
lnk.Name = "lnkAction"
lnk.UseColumnTextForLinkValue = True
End Sub
If the difference between the QtyReqd and QtyInStock is a negative value, the link button should read as "Not Available" and if there is enough stock it should read as "Available". Based on these two values different windows will open upon clicking the link
I tried to check the condition in the DataBindingComplete event, but its not working. What am I doing wrong here?
CL

I think that the easiest way is to add a computed column to the data table and use this as the data bound item for the link column. Something like this:
Dim expr As String = "IFF((([QtyInStock] - [QtyReqd]) >= 0), 'Available', 'Not Available')"
data.Tables(0).Columns.Add("Action", GetType(String), expr)

In the datagrid designer add a handler for: OnRowDataBound="someEvent_RowDataBound"
In the code behind you will have a function:
protected void someEvent_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
If(e.Row.RowType == DataControlRowType.DataRow){
((linkbutton)e.Row.Cells[someindex].controls(0)).Text = "somevalue";
}
}

Related

Access VBA Public Function - Variable for Control and Field?

I want to set up a public function like the following:
(A)
Public Function CheckYNField(chkControl As Control, chkField As String)
If chkField = "Y" Then
chkControl = -1
ElseIf chkField = "N" Then
chkControl = 0
Else: chkControl = 0
End If
End Function
(B)
Public Function CheckYNFlipper(chkControl As Control, chkField As String)
If chkField = "Y" Then
chkField = "N"
chkControl = 0
ElseIf chkField = "N" Then
chkField = "Y"
chkControl = -1
Else: chkField = "Y"
chkControl = -1
End If
End Function
The reason for this is, that I have a form, which has an underlying SQL table. I have no control over the data, but I must represent it, for the ability to maintain it. I have 10 fields, in the underlying table, which have a Y or N as their values. The data types are actually nvarchar(10). At the same time, I have to show these fields as checkbox controls, on the form, for ease of use.
The above code, is an attempt I am making to A - set the checkbox control to align with the current value in the table--> -1 = Y and 0 = N, and to B - update the table value, and switch the check box to checked or unchecked, from what it was, to the opposite, based on the onclick event of that control.
I want to make chkField and chkControl variables to the public function, that would be the table-field, and the form-control. I can't seem to get the right syntax, and was hoping someone might have clarification on how to do this.
for the form load and current, I tried this:
CheckYNField Forms("frmFormNameA").Controls(chkCheckNameA), tblTableName.FieldA
for the on click, I tried this:
CheckYNFlipper Forms("frmFormNameA").Controls(chkCheckNameA), tblTableName.FieldA
I've tried some other methods, but doesn't seem to be working. I'm doing something wrong, but I can't tell what. Appreciate any tips!
Edit/Update:
I tried Kostas K.'s solution, abandoning the idea of making a public functions with parameters for the fields and controls. I put the following, on load and on current:
With Me
If .txtfieldboundtablefieldA.Value = "Y" Then
.unboundchkA.Value = True
ElseIf .txtfieldboundtablefieldA.Value = "N" Then
.unboundchkA.Value = False
Else: .unboundchkA.Value = False
End If
End With
This is on a continuous form, so that it can show like a giant grid. There are the identifying bound field controls, and then a series of these checkboxes, to display the Y/N true/false status of each of these particular fields. I can't bound the checkboxes to the fields, because it changes the field value in the table to -1 or 0, and we need it to stay Y or N. I added a bound text field, to hold the table/field value for each row (hence the call to a text box control in the above revised code). The checkbox is unbound, and is there to display the field value, and allow the user to check and uncheck, so I can use on-click code to change the table field value between Y and N.
The above code is not seeming to show the correct checkbox value for each bound text field, based on each row. It shows based on the row that currently has focus. If I click on a row, where the table field is Y, all rows checkboxes on the form show true. If I move to a row, where the table field is N, all checkboxes for all rows change to false. I am struggling to just initially get 1 checkbox to show accurately, on every row of the continuous form, based on every record in the table. This is a small table, like 30 records. I really didn't think it would be so difficult to present this the way we need to.
Any ideas, how I could better do this?
Edit:
Set the Control Source of the checkbox to:
= IIf([YourYesNoField] = "Y", -1, 0)
In order to update when clicked:
Private Sub chkCheckNameA_Click()
Dim yesNo As String
yesNo = IIf(Me.chkCheckNameA.Value = 0, "Y", "N") 'reverse value
CurrentDb.Execute "Update [YourTable] SET [YourYesNoField]='" & yesNo & "' WHERE [ID]=" & Me![ID], dbFailOnError
Me.Requery
End Sub
You could try something this.
Check the Y/N field and assign the function's boolean return value to the checkbox (A).
On the checkbox click event, check its value and update the Y/N field (B).
'Form Load
Private Sub Form_Load()
With Me
.chkCheckNameA.Value = CheckYNField(![FieldA])
End With
End Sub
'Click
Private Sub chkCheckNameA_Click()
With Me
![FieldA] = IIf(.chkCheckNameA.Value = 0, "N", "Y")
End With
End Sub
'True returns -1, False returns 0
Private Function CheckYNField(ByVal chkField As String) As Boolean
CheckYNField = (chkField = "Y")
End Function
chkControl is a Control, so you need to access a property of that control. Try changing your code to:
Public Function CheckYNField(chkControl As Control, chkField As String)
If chkField = "Y" Then
chkControl.Value = -1
ElseIf chkField = "N" Then
chkControl.Value = 0
Else: chkControl.Value = 0
End If
End Function
and then the same idea in your other function.

Capturing an event such as mouse click in Datagridview in VB

Update 5/21/17. Thank you for the suggestion of using a Table. That was helpful. I actually figured it out. I made myinputable a global variable by declaring the Dim statement at the top and making it a Datagridview type. Now I can turn it off in the other event that I needed to do it.
I am a novice. I have created a Datagridview in VB 2015 to capture a bunch of data from the use. When the user is finished with the data entry, I want to store the cell values in my variables. I do not know how to capture any event from my dynamically created datagridview "myinputable." My code is below. Please help.
Private Sub inputmodel()
Dim prompt As String
Dim k As Integer
'
' first get the problem title and the number of objectives and alternatives
'
prompt = "Enter problem title: "
title = InputBox(prompt)
prompt = "Enter number of criteria: "
nobj = InputBox(prompt)
prompt = "Enter number of alternatives: "
nalt = InputBox(prompt)
'
' now create the table
'
Dim Myinputable As New DataGridView
Dim combocol As New DataGridViewComboBoxColumn
combocol.Items.AddRange("Increasing", "Decreaing", "Threashold")
For k = 1 To 6
If k <> 2 Then
Dim nc As New DataGridViewTextBoxColumn
nc.Name = ""
Myinputable.Columns.Add(nc)
Else
Myinputable.Columns.AddRange(combocol)
End If
Next k
' now add the rows and place the spreadsheet on the form
Myinputable.Rows.Add(nobj - 1)
Myinputable.Location = New Point(25, 50)
Myinputable.AutoSize = True
Me.Controls.Add(Myinputable)
FlowLayoutPanel1.Visible = True
Myinputable.Columns(0).Name = "Name"
Myinputable.Columns(0).HeaderText = "Name"
Myinputable.Columns(1).Name = "Type"
Myinputable.Columns(1).HeaderText = "Type"
Myinputable.Columns(2).Name = "LThresh"
Myinputable.Columns(2).HeaderText = "Lower Threshold"
'Myinputable.Columns(2).ValueType = co
Myinputable.Columns(3).Name = "UThresh"
Myinputable.Columns(3).HeaderText = "Upper Threshold"
Myinputable.Columns(4).Name = "ABMin"
Myinputable.Columns(4).HeaderText = "Abs. Minimum"
Myinputable.Columns(5).Name = "ABMax"
Myinputable.Columns(5).HeaderText = "Abs. Maximum "
Myinputable.Rows(0).Cells(0).Value = "Help"
If Myinputable.Capture = True Then
MsgBox(" damn ")
End If
End Sub
As #Plutonix suggests, you should start by creating a DataTable. Add columns of the appropriate types to the DataTable and then bind it to the grid, i.e. assign it to the DataSource of your grid, e.g.
Dim table As New DataTable
With table.Columns
.Add("ID", GetType(Integer))
.Add("Name", GetType(String))
End With
DataGridView1.DataSource = table
That will automatically add the appropriate columns to the grid if it doesn't already have any, or you can add the columns in the designer and set their DataPropertyName to tell them which DataColumn to bind to. As the user makes changes in the grid, the data will be automatically pushed to the underlying DataTable.
When you're done, you can access the data via the DataTable and even save the lot to a database with a single call to the Update method of a data adapter if you wish.

Retrieving an item from a list based on selected value

The function retrieveFixtureReport() returns a list of Report, each of which contains a PlayerID. I'm trying to set my labels to reflect the selected Report chosen from cmbSelectedPlayer. Each Report within the list contains a unique PlayerID. I've tried a variety of different ways to access the properties of the selected Report, including LINQ, but have been unsuccessful so far. A For Each loop doesn't seem to be the right option to select just one Report, it also prevents me from selecting other PlayerID's from cmbSelectedPlayer (only the last Report in the list is shown). The code is shown below:
Public Sub setFixtureReport()
'If UC_Menu_Scout1.cmbSelectedPlayer.SelectedItem IsNot Nothing Then
If UC_Menu_Scout1.cmbSelectedPlayer.Items.Count > 0 Then
Dim getPlayerReport = _
(From rpt As Report In retrieveFixtureReport() _
Where rpt.PlayerID = UC_Menu_Scout1.cmbSelectedPlayer.SelectedItem.PlayerID) '.AsEnumerable
'For Each rpt As Report In getPlayerReport()
'For Each rpt As Report In retrieveFixtureReport.Where(Function(x) x.PlayerID = UC_Menu_Scout1.cmbSelectedPlayer.SelectedItem.PlayerID)
'Dim rpt As Report = getPlayerReport 'retrieveFixtureReport(0)
'*****General Information
UC_Menu_Scout1.lblRptPosition.Text = rpt.PositionPlayed
UC_Menu_Scout1.lblFoot.Text = rpt.PreferredFoot
UC_Menu_Scout1.txtComments.Text = rpt.Comments
UC_Menu_Scout1.lblStatus.Text = rpt.MonitorStatus
'Next
setColours()
'End If
End If
End Sub
The combobox cmbSelectedPlayer is filled from playerList (this is added to in retrieveFixxtureReport as well):
UC_Menu_Scout1.cmbSelectedPlayer.DataSource = playerList
UC_Menu_Scout1.cmbSelectedPlayer.DisplayMember = "PlayerFullName"
UC_Menu_Scout1.cmbSelectedPlayer.ValueMember = "PlayerID"
Any suggestions would be appreciated.
If your combobox was bound to a List(Of Player) then all you would need to do is cast the SelectedItem to it's type:
Dim player = TryCast(UC_Menu_Scout1.cmbSelectedPlayer.SelectedItem, Player)
If Not player Is Nothing Then
Dim getPlayerReport = (From rpt As Report In retrieveFixtureReport()
Where rpt.PlayerID = player.PlayerID).FirstOrDefault()
If Not getPlayerReport Is Nothing Then
UC_Menu_Scout1.lblRptPosition.Text = getPlayerReport.PositionPlayed
UC_Menu_Scout1.lblFoot.Text = getPlayerReport.PreferredFoot
UC_Menu_Scout1.txtComments.Text = getPlayerReport.Comments
UC_Menu_Scout1.lblStatus.Text = getPlayerReport.MonitorStatus
End If
End If

VB 2008 Transferring stored values to textbox after initial textbox value is cleared

Self teaching VB beginner here.
I have a data entry section that includes...
2 comboboxes(cbx_TruckType, cbx_DoorNumber)
-------cbx_TruckType having 2 options (Inbound, Outbound)
-------cbx_DoorNumber having 3 options (Door 1, Door 2, Door 3)
2 textboxes (txb_CustomerName, txb_OrderNumber)
-------txb_CustomerName will hold a customer name
-------txb_OrderNumber will hold an order number
and finally...
a button(btn_EnterTruck) that transfers the text from the comboxes and textboxes to the following...
2 Tabs
The 1st tab has
2 buttons(btn_Door1, btn_Door2)
btn_Door1 has 3 corresponding textboxes
-------txb_TruckTypeDoor1, txb_CustomerNameDoor1, txb_OrderNumberDoor1
btn_Door2 has 3 corresponding textboxes
-------txb_TruckTypeDoor2, txb_CustomerNameDoor2, txb_OrderNumberDoor2
The 2nd tab has
1 button(btn_Door3)
btn_Door1 has 3 corresponding textboxes
-------txb_TruckTypeDoor3, txb_CustomerNameDoor3, txb_OrderNumberDoor3
Currently, I have code (that works thanks to another question I had!) that, upon btn_EnterTruck.click, will transfer the text to the corresponding textboxes.
Here's my problem...
I've coded a msgbox to pop-up (when Inbound is selected from the cbx_TruckType) asking if there is an Outbound. If I click "Yes", an inputbox pops-up and asks for an order number. The button then transfers the Inbound information to the textboxes and stores the Outbound order number.
When I click btn_Door1(or 2 or 3), it clears the text from its corresponding textboxes. (Using me.controls)
( I would add code for all of the above, but I figure its a moot point, because it works)
What I want to happen...
I want to have the stored Outbound number to be saved with a reference to which door number it corresponds to. Then upon btn_DoorX click, it will fill that order number into the corresponding textbox. I don't need the text stored/saved when the app is closed.
And I have no idea how to do that.
*After some tooling, I've done the following, but it does not work"
I declared these at the class level.
Dim str_SameTruckPODoor1, str_SameTruckPODoor2, str_SameTruckPODoor3 As String
This code is in the btn_EnterTruck event
Dim str_ErrOutDoorName As String = cbx_DoorNumber.Text
Dim str_OutboundDoorName As String = str_ErrOutDoorName.Replace(" ", "")
Dim ArrayForPONumbers As Control() = Me.Controls.Find("str_SameTruckPO" & str_OutboundDoorName, True)
If cbx_TruckType.Text = "Inbound" Then
Dim OutboundMsg = "Is there an Outbound with this truck information?"
Dim Title = "Outbound?"
Dim style = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or _
MsgBoxStyle.Question
Dim response = MsgBox(OutboundMsg, style, Title)
If response = MsgBoxResult.Yes Then
Dim NeedPOMessage, NeedPOTitle, defaultValue As String
Dim PONumberOutbound As String
' Set prompt.
NeedPOMessage = "Enter the PO Number"
' Set title.
NeedPOTitle = "PO# For Outbound"
defaultValue = "?" ' Set default value.
' Display message, title, and default value.
PONumberOutbound = InputBox(NeedPOMessage, NeedPOTitle, defaultValue)
' If user has clicked Cancel, set myValue to defaultValue
If PONumberOutbound Is "" Then PONumberOutbound = defaultValue
ArrayForPONumbers(0) = PONumberOutbound
End If
End If
I'm getting an error message on
ArrayForPONumbers(0) = PONumberOutbound ' Cannot convert string to .controls
And I have the following code in the btn_Door1 event - it handles btn_Door2, btn_Door3
Dim WhichButton As Button = CType(sender, Button)
Dim str_ErrDoorName As String = WhichButton.Name
Dim str_DoorName As String = str_ErrDoorName.Replace("btn_", "")
Dim str_DoorType As Control() = Me.Controls.Find("txb_" & str_DoorName & "Type", True)
Dim str_Customer As Control() = Me.Controls.Find("txb_" & str_DoorName & "Customer", True)
Dim str_OrderNumber As Control() = Me.Controls.Find("txb_" & str_DoorName & "OrderNumber", True)
Dim SecondArrayForPONumbers As Control() = Me.Controls.Find("str_SameTruckPO" & str_DoorName, True)
If str_DoorType(0).Text = "Outbound" Then
str_DoorType(0).Text = ""
str_Customer(0).Text = ""
str_OrderNumber(0).Text = ""
ElseIf SecondArrayForPONumbers(0).Text.Length > 0 Then
str_DoorType(0).Text = "Outbound"
str_OrderNumber(0).Text = Me.Controls("str_SameTruckPO" & str_DoorName).Text
End If
Any help is appreciated. If I'm not clear on what I'm asking or haven't given enough details, please let me know.
Edit: Added info based on comment, Added code, Changed Title
How long do you want this data to be stored? IE: longer than the life of the open application? If the application is closed is it alright if the data is lost? If not, you may want to consider writing this data to an external database.

DataGridView column order does not seem to work

I have a DataGridView bound to a list of business objects:
Dim template As New IncidentTemplate
Dim temps As List(Of IncidentTemplate) = template.LoadAll
Dim bs As New BindingSource
If Not temps Is Nothing Then
bs.DataSource = temps
Me.dgvTemplates.DataSource = bs
End If
I then add an unbound button column and make some of the bound columns invisible:
Dim BtnCol As New DataGridViewButtonColumn
With BtnCol
.Name = "Edit"
.Text = "Edit"
.HeaderText = String.Empty
.ToolTipText = "Edit this Template"
.UseColumnTextForButtonValue = True
End With
.Columns.Add(BtnCol)
BtnCol = Nothing
For Each col As DataGridViewColumn In Me.dgvTemplates.Columns
Select Case col.Name
Case "Name"
col.DisplayIndex = 0
col.FillWeight = 100
col.Visible = True
Case "Description"
col.DisplayIndex = 1
col.FillWeight = 100
col.Visible = True
Case "Created"
col.DisplayIndex = 3
col.HeaderText = "Created On"
col.DefaultCellStyle.Format = "d"
col.FillWeight = 75
col.Visible = True
Case "CreatedBy"
col.DisplayIndex = 2
col.HeaderText = "Created By"
col.FillWeight = 75
col.Visible = True
Case "Edit"
col.DisplayIndex = 4
col.HeaderText = ""
col.FillWeight = 30
col.Visible = True
Case Else
col.Visible = False
End Select
Next
This seems to work reasonably well except no matter what I do the button column (Edit) always displays in the middle of the other columns instead of at the end. I've tried both DGV.Columns.Add and DGV.Columns.Insert as well as setting the DisplayIndex of the column (this works for all other columns) but I am unable to make the button column display in the correct location. I've also tried adding the button column both before and after setting the rest of the columns but this seems to make no difference Can anyone suggest what I am doing wrong? It's driving me crazy....
I stumbled on your post while looking to solve a similar problem. I finally tracked it down by doing as you mention (using the DisplayIndex property) and setting the AutoGenerateColumns property of the DataGridView to false. This property is not visible in the designer, so I just added it to the constructor for my form. Be sure to do this before setting the data source for your grid.
Hope this helps...
The AutoCreateColumn is the problem. The following article gives an example for how to fix it.
From DataDridView DisplayOrder Not Working
When setting the column’s DisplayIndex in a data grid view, some columns were out of order. To fix the issue, I had to set AutoGenerateColumns to true before setting the data source, and to FALSE after.
For Example:
dgvReservedStalls.AutoGenerateColumns = True
dgvReservedStalls.DataSource = clsReservedStalls.LoadDataTable()
dgvReservedStalls.AutoGenerateColumns = False
Same problem here, and after searching for a while, I found out that by setting the DisplayIndexes in Ascending order made it for me.
It's counter-intuitive, because it's a number, but I still had to set them in order.
This works:
With customersDataGridView
.Columns("ContactName").DisplayIndex = 0
.Columns("ContactTitle").DisplayIndex = 1
.Columns("City").DisplayIndex = 2
.Columns("Country").DisplayIndex = 3
.Columns("CompanyName").DisplayIndex = 4
End With
While this did not:
With customersDataGridView
.Columns("ContactName").DisplayIndex = 0
.Columns("CompanyName").DisplayIndex = 4
.Columns("Country").DisplayIndex = 3
.Columns("ContactTitle").DisplayIndex = 1
.Columns("City").DisplayIndex = 2
End With
I tried the above solutions without success. Then I found this article: It made it all better.
http://msdn.microsoft.com/en-us/library/vstudio/wkfe535h(v=vs.100).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1