TextBoxes using parent control BindingContexts don't display data value - vb.net

I am having a problem when I try to bind to text boxes to separate BindingContexts (via a container control such as a GroupBox). The textboxes don't display the bound value. (This example is based on the bindingcontext documentation here)
Here is the code:
Dim ds As New DataSet1
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
BindControls()
GetData()
End Sub
Private Sub BindControls()
Dim bcG1 As New BindingContext()
Dim bcG2 As New BindingContext()
GroupBox1.BindingContext = bcG1
'GroupBox2.BindingContext = bcG2
TextBox1.DataBindings.Add("Text", ds, "Orders.OrderKey") ' groupbox1
TextBox2.DataBindings.Add("Text", ds, "Orders.OrderKey") ' groupbox2
TextBox3.DataBindings.Add("Text", ds, "Orders.OrderKey") ' form
End Sub
When I run the form Textbox3 (at the form level) and textbox2 (in GroupBox2) are synchronized as expected and TextBox2 displays the value of OrderKey. However, Textbox1 (in GroupBox1) does not show any values. I have determined that GroupBox1 is indeed using a separate BindingContext and position commands do move to new rows independent of the form. If I comment out setting GroupBox1's BindingContext it behaves as Texbox2, synchronized at the form level. If I uncomment setting Groupbox2's BindingContext, it behaves as Textbox1, unsynchronized but doesn't display any values in the textbox.
Can anybody see what I'm missing?
Here is the full code:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim ds As New DataSet1
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
BindControls()
GetData()
End Sub
Private Sub BindControls()
Dim bcG1 As New BindingContext()
Dim bcG2 As New BindingContext()
GroupBox1.BindingContext = bcG1
'GroupBox2.BindingContext = bcG2
TextBox1.DataBindings.Add("Text", ds, "Orders.OrderKey") ' groupbox1
TextBox2.DataBindings.Add("Text", ds, "Orders.OrderKey") ' groupbox2
TextBox3.DataBindings.Add("Text", ds, "Orders.OrderKey") ' form
End Sub
' ** groupbox1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
GroupBox1.BindingContext(ds, "Orders").Position -= 1
Dim drv As DataRowView = CType(GroupBox1.BindingContext(ds, "Orders").Current, DataRowView)
TextBox5.Text = drv("OrderKey")
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
GroupBox1.BindingContext(ds, "Orders").Position += 1
Dim drv As DataRowView = CType(GroupBox1.BindingContext(ds, "Orders").Current, DataRowView)
TextBox5.Text = drv("OrderKey")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
GroupBox2.BindingContext(ds, "Orders").Position -= 1
Dim drv As DataRowView = CType(GroupBox2.BindingContext(ds, "Orders").Current, DataRowView)
TextBox6.Text = drv("OrderKey")
End Sub
' ** groupbox2
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
GroupBox2.BindingContext(ds, "Orders").Position += 1
Dim drv As DataRowView = CType(GroupBox2.BindingContext(ds, "Orders").Current, DataRowView)
TextBox6.Text = drv("OrderKey")
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Me.BindingContext(ds, "Orders").Position -= 1
Dim drv As DataRowView = CType(Me.BindingContext(ds, "Orders").Current, DataRowView)
TextBox4.Text = drv("OrderKey")
End Sub
' ** Form
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Me.BindingContext(ds, "Orders").Position += 1
Dim drv As DataRowView = CType(Me.BindingContext(ds, "Orders").Current, DataRowView)
TextBox4.Text = drv("OrderKey")
End Sub
Private Sub GetDataButton_Click(sender As Object, e As EventArgs) Handles GetDataButton.Click
GetData()
End Sub
Public Sub GetData()
ds.Clear()
Dim ota As New DataSet1TableAdapters.OrdersTableAdapter
ota.Adapter.SelectCommand = New SqlCommand("SELECT OrderKey, CustomerFK, OrderDate, DeliveryMethod, Special_Instr, " & _
"TotalOrderAmount " & _
"FROM Orders ", ota.Connection)
ota.Adapter.Fill(ds)
End Sub
End Class

Microsoft declined to address the bug report at this time but I did find that I could use BindingSources to accomplish what I was trying to do. Important note: To set the filter the BindingSource.DataSource property needs to be set to a new DataView. By default it uses the DataTable's default view so setting the filter on one instance of the BindingSource sets it for the other. The DataSource assignment would be similar to this:
BindingSource1.DataSource = New DataView(DataSource1.DataTable1)
Here is the revised code:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1BindingSource
Dim ds As New DataSet1
Dim bsForm As BindingSource
Dim bsG1 As BindingSource
Dim bsG2 As BindingSource
Dim BindingSource1 As BindingSource
Private _OcConnectionString As String
Public Property OcConnectionString() As String
Get
Return _OcConnectionString
End Get
Set(ByVal value As String)
_OcConnectionString = value
End Set
End Property
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
BindControls()
GetData()
End Sub
Public Sub New(strConnection As String)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
OcConnectionString = strConnection
BindControls()
GetData()
End Sub
Private Sub BindControls()
bsForm = New BindingSource
bsG1 = New BindingSource
bsG2 = New BindingSource
bsForm.DataSource = ds
bsG1.DataSource = ds
bsG2.DataSource = ds
bsForm.DataMember = "Orders"
bsG1.DataMember = "Orders"
bsG2.DataMember = "Orders"
'BindingSource1 = New BindingSource(ds, "Orders")
BindingSource1 = New BindingSource
BindingSource1.DataSource = ds
BindingSource1.DataMember = "Orders"
Me.DataGridView1.DataSource = BindingSource1
TextBox1.DataBindings.Add("Text", bsG1, "OrderKey") ' groupbox1
TextBox2.DataBindings.Add("Text", bsG2, "OrderKey") ' groupbox2
TextBox3.DataBindings.Add("Text", BindingSource1, "OrderKey") ' form
TextBox8.DataBindings.Add("Text", BindingSource1, "OrderKey") ' Groupbox3
End Sub
' ** groupbox1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
bsG1.MovePrevious()
'GroupBox1.BindingContext(ds, "Orders").Position -= 1
Dim drv As DataRowView = CType(bsG1.Current, DataRowView)
TextBox5.Text = drv("OrderKey")
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
bsG1.MoveNext()
'GroupBox1.BindingContext(ds, "Orders").Position += 1
Dim drv As DataRowView = CType(bsG1.Current, DataRowView)
TextBox5.Text = drv("OrderKey")
End Sub
' ** groupbox2
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
bsG2.MovePrevious()
'GroupBox2.BindingContext(ds, "Orders").Position -= 1
Dim drv As DataRowView = CType(bsG2.Current, DataRowView)
TextBox6.Text = drv("OrderKey")
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
bsG2.MoveNext()
'GroupBox2.BindingContext(ds, "Orders").Position += 1
Dim drv As DataRowView = CType(bsG2.Current, DataRowView)
TextBox6.Text = drv("OrderKey")
End Sub
'** form level
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
bsForm.MovePrevious()
'Me.BindingContext(ds, "Orders").Position -= 1
Dim drv As DataRowView = CType(bsForm.Current, DataRowView)
TextBox4.Text = drv("OrderKey")
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
bsForm.MoveNext()
'Me.BindingContext(ds, "Orders").Position += 1
Dim drv As DataRowView = CType(bsForm.Current, DataRowView)
TextBox4.Text = drv("OrderKey")
End Sub
'** Groupbox3
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
bsForm.MovePrevious()
'GroupBox3.BindingContext(ds, "Orders").Position -= 1
Dim drv As DataRowView = CType(bsForm.Current, DataRowView)
TextBox8.Text = drv("OrderKey")
End Sub
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
bsForm.MoveNext()
'GroupBox3.BindingContext(ds, "Orders").Position += 1
Dim drv As DataRowView = CType(bsForm.Current, DataRowView)
TextBox8.Text = drv("OrderKey")
End Sub
Private Sub GetDataButton_Click(sender As Object, e As EventArgs) Handles GetDataButton.Click
GetData()
End Sub
Public Sub GetData()
Try
Dim ota As New DataSet1TableAdapters.OrdersTableAdapter
If OcConnectionString IsNot Nothing Then
ota.Connection.ConnectionString = OcConnectionString
End If
ds.Clear()
ota.Adapter.SelectCommand = New SqlCommand("SELECT OrderKey, CustomerFK, OrderDate, DeliveryMethod, Special_Instr, " & _
"TotalOrderAmount " & _
"FROM Orders ", ota.Connection)
ota.Adapter.Fill(ds)
Catch exp As Exception
MsgBox(exp.Message)
End Try
End Sub
End Class
Carl

Related

How to update an Access DB from a DataGridView in Visual Basic

I am creating an inventory application which runs off of an Access DB in visual studio, using visual basic. I can populate my data grid view just fine, but when I try to add new information into the data grid view, it does not number correctly and it does not append my database.
I have tried binding and updating using the table adapter.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CustomersBindingSource.AddNew()
Me.Validate()
Me.CustomersTableAdapter.Update(Me.Database1DataSet.Customers)
Me.CustomersBindingSource.EndEdit()
End Sub
Here is my code:
Public Class Form1
Private Sub enterbtn_Click(sender As Object, e As EventArgs) Handles enterbtn.Click
If username.Text = "Tanner" And password.Text = "bmis365" Then
GroupBox1.Visible = False
Else
MsgBox("Incorrect Username or Password, please try again.")
username.Clear()
password.Clear()
username.Focus()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.CurrentCell = Nothing
'This line of code loads data into the 'Database1DataSet.Customers' table. You can move, or remove it, as needed.
Me.CustomersTableAdapter.Fill(Me.Database1DataSet.Customers)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'This is where my new info is to be appended into the database, once the button is clicked.
CustomersBindingSource.AddNew()
Me.Validate()
Me.CustomersTableAdapter.Update(Me.Database1DataSet.Customers)
Me.CustomersBindingSource.EndEdit()
End Sub
Private Sub searchbtn_Click(sender As Object, e As EventArgs) Handles searchbtn.Click
'The Following Code is from https://social.msdn.microsoft.com/Forums/vstudio/en-US/36c54726-4f49-4e15-9597-7b201ec13ae7/search-in-datagrid-using-textbox-vbnet-without-data-connectivity?forum=vbgeneral
For Each row As DataGridViewRow In DataGridView2.Rows
For Each cell As DataGridViewCell In row.Cells
If Not IsNothing(cell.Value) Then
If cell.Value.ToString.StartsWith(searchbar.Text, StringComparison.InvariantCultureIgnoreCase) Then
cell.Selected = True
DataGridView2.CurrentCell = DataGridView2.SelectedCells(0)
End If
End If
Next
Next
End Sub
End Class
My output initially has 3 rows(numbered 1, 2, and 3) but any that are added through the application have the numbers -1, -2, -3 and so on. Also, when I close the program and restart it, my original rows (1, 2, and 3) are still there from when I entered them in the DB file, but any that were added through my application are gone.
Here is one way to do an Update, as well as a few other common SQL manipulations/operations.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class

Moving between DataGridView rows via code and show through textboxes

I'm not an experienced programmer and I must have made some misconceptions.
I have two forms, one for the search (FormSearch) and one to show the results (FormMain).
The question is: how can I populate the textboxes with the previous results (click on the btnPrev button) or the next results (click on the btnNext button)?
FormSearch
Imports System.Data.SqlClient
Public Class FormSearch
Private Sub btnsearch_Click(sender As Object, e As EventArgs) Handles btnsearch.Click
Dim con As New SqlConnection("Data Source=" & Form1.server & "," & Form1.port & "; Initial Catalog=" & Form1.database & "; User Id=" & Form1.txtUsername.Text & "; Password=" & Form1.txtPassword.Text & ";")
Dim cmd As New SqlCommand("select * FROM dbo.customers;", con)
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable
adapter.Fill(table)
DataGridView1.DataSource = table
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
FormMain.TextBox1.Text = row.Cells("Name").Value.ToString
FormMain.TextBox2.Text = row.Cells("Surname").Value.ToString
FormMain.TextBox3.Text = row.Cells("Age").Value.ToString
Me.Hide()
FormMain.Show()
End If
End Sub
End Class
FormMain
Public Class FormMain
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
FormSearch.Show()
Me.Hide()
End Sub
Private Sub btnPrev_Click(sender As Object, e As EventArgs) Handles btnPrev.Click
'Show prev result
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
'Show next result
End Sub
End Class
Try this:
1) Apply the code below in FormMain
Public Class FormMain
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
FormSearch.Show()
Me.Hide()
End Sub
Private Sub btnPrev_Click(sender As Object, e As EventArgs) Handles btnPrev.Click
BS.Position = BS.Position - 1
DisplayRecords()
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
BS.Position = BS.Position + 1
DisplayRecords()
End Sub
End Class
2) Apply the code below in FormSearch
Imports System.Data.SqlClient
Public Class FormSearch
Private Sub btnsearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim con As New SqlConnection("Data Source=" & Form1.server & "," & Form1.port & "; Initial Catalog=" & Form1.database & "; User Id=" & Form1.txtUsername.Text & "; Password=" & Form1.txtPassword.Text & ";")
Dim adapter As New SqlDataAdapter("select * FROM [dbo.customers]", con)
adapter.Fill(DS, "myTableNane")
BS.DataSource = DS
BS.DataMember = "myTableNane"
DataGridView1.DataSource = BS
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.RowIndex >= 0 Then
BS.Position = e.RowIndex
Me.Hide()
FormMain.Show()
End If
End Sub
End Class
2) Create a Module and place the below code.
Module Module1
Public DS As New DataSet
Public WithEvents BS As New BindingSource
Sub DisplayRecords(Optional ByVal table As String = "myTableNane")
FormMain.TextBox1.Text = DS.Tables(table).Rows(BS.Position)("Name").ToString
FormMain.TextBox2.Text = DS.Tables(table).Rows(BS.Position)("Surename").ToString
FormMain.TextBox3.Text = DS.Tables(table).Rows(BS.Position)("Age").ToString
End Sub
End Module
Hope you find it helpful and solved your problem.
Moiyd

DataGridView right click event and pass-through of parameters to sub

I read a lot of things here in the forum, but I can't find a solution for my problem.
I have a DataGridView with a ContextMenu.
My aim is to call a function from the context menu and pass through parameters e.g. linenumber of selected dgv row.
Here is my code, that contains a ContextMenu, but how I could pass-through some parameters to a function?
Private Sub dataGridView1_MouseClick(ByVal sender As DataGridView, ByVal e As MouseEventArgs) Handles DataGridView1.MouseClick
If e.Button = MouseButtons.Right Then
Dim m As New ContextMenu
m.MenuItems.Add(New MenuItem("Sub1"))
m.MenuItems.Add(New MenuItem("Sub2"))
Dim currentMouseOverRow As Integer = DataGridView1.HitTest(e.X, e.Y).RowIndex
m.Show(DataGridView1, New Point(e.X, e.Y))
End If
End Sub
EDIT
Now I have got a solution that works, but I think it is not the best solution and I can do a lot of improvement.
Maybe it would be possible to code custom events, that can pass through some datas of the gridview. I hope somebody is interested to give some input to improve the following (working) code to look something like professional.
Imports System
Imports System.IO
Public Class Form1
Public gpath As String = "D:\kvt.txt"
Public Sub New()
' This call is required by the designer.
InitializeComponent()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim file = System.IO.File.ReadAllLines("d:\kvt.txt")
Dim dt As New DataTable
dt.Columns.Add("Name")
For Each line As String In file
dt.Rows.Add(line)
Next
DataGridView1.DataSource = dt
DataGridView1.Show()
End Sub
Private Sub dataGridView1_MouseClick(ByVal sender As DataGridView, ByVal e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim cMenu As New ContextMenuStrip
Dim MenuItemClone As New System.Windows.Forms.ToolStripMenuItem
MenuItemClone.Text = "Clone"
cMenu.Items.Add(MenuItemClone)
If e.Button = MouseButtons.Right Then
Dim currentMouseOverRow As Integer = DataGridView1.HitTest(e.X, e.Y).RowIndex
cMenu.Show(DataGridView1, New Point(e.X, e.Y))
AddHandler MenuItemClone.Click, AddressOf CloneRepo
End If
End Sub
Private Sub CloneRepo(ByVal sender As Object, ByVal e As System.EventArgs)
Dim SelectedName As String = DataGridView1("Name", DataGridView1.CurrentCell.RowIndex).FormattedValue
End Sub
End Class
Here's an example of how you can right-click on a cell in a DataGridView and then perform an action relative to that cell when you click a menu item:
Private lastClickedCell As DataGridViewCell
Private Sub DataGridView1_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
If e.ColumnIndex >= 0 AndAlso
e.RowIndex >= 0 Then
lastClickedCell = DataGridView1.Item(e.ColumnIndex, e.RowIndex)
End If
End Sub
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
If e.Button = MouseButtons.Right AndAlso
DataGridView1.HitTest(e.X, e.Y).Type = DataGridViewHitTestType.Cell Then
'Display the menu when right-clicking on a cell.
ContextMenuStrip1.Show(DataGridView1, e.Location)
End If
End Sub
Private Sub ClearToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ClearToolStripMenuItem.Click
'Clear the cell that was right-clicked.
lastClickedCell.Value = Nothing
End Sub
The ContextMenuStrip was created in the designer for this example. I would recommend doing that in your case too, even if you need to choose items dynamically. You can clear the menu and add and/or remove items in the CellMouseClick or MouseClick event handlers of the grid, or the Opening event handler of the menu.
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim col As New DataGridTextBoxColumn
If e.Button = MouseButtons.Right Then
Dim m As New ContextMenuStrip
col.TextBox.ContextMenuStrip = m
Dim tsp As New ToolStripMenuItem("Sub1", Nothing, New EventHandler(AddressOf TestMessage))
Dim tsp1 As New ToolStripMenuItem("Sub2", Nothing, New EventHandler(AddressOf TestMessage))
m.Name = "Menulist"
m.Items.Add(tsp)
m.Items.Add(tsp1)
Dim currentMouseOverRow As Integer = DataGridView1.HitTest(e.X, e.Y).RowIndex
m.Show(DataGridView1, New Point(e.X, e.Y))
End If
End Sub
Private Sub TestMessage()
MessageBox.Show("Clicked")
End Sub
try this and use 'Tag':
Dim currentMouseOverRow As Integer
Structure MyStructure
Public x As Integer
Public y As Integer
End Structure
Private Sub DataGridView1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseClick
Dim Mystruct As MyStructure
If e.Button = Windows.Forms.MouseButtons.Right Then
Dim m As New System.Windows.Forms.ContextMenuStrip
Dim MymenuToolStripMenuItem1 As New System.Windows.Forms.ToolStripMenuItem
MymenuToolStripMenuItem1.Text = "menu1"
AddHandler MymenuToolStripMenuItem1.Click, AddressOf MymenuToolStripMenuItem1_Click
m.Items.Add(MymenuToolStripMenuItem1)
Dim MymenuToolStripMenuItem2 As New System.Windows.Forms.ToolStripMenuItem
MymenuToolStripMenuItem2.Text = "menu2"
AddHandler MymenuToolStripMenuItem2.Click, AddressOf MymenuToolStripMenuItem2_Click
m.Items.Add(MymenuToolStripMenuItem2)
Mystruct.x = e.X
Mystruct.x = e.X
MymenuToolStripMenuItem2.Tag = Mystruct
currentMouseOverRow = DataGridView1.HitTest(e.X, e.Y).RowIndex
m.Show(DataGridView1, New Point(e.X, e.Y))
End If
End Sub
Private Sub MymenuToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
MessageBox.Show("click Menu1:" & currentMouseOverRow)
End Sub
Private Sub MymenuToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim Mystruct As MyStructure
Mystruct = CType(CType(sender, System.Windows.Forms.ToolStripMenuItem).Tag, MyStructure)
MessageBox.Show("click Menu2:" & currentMouseOverRow & " x:" & Mystruct.x & " y:" & Mystruct.y)
End Sub

How to color specific cell in Datagridview vb.net

I am trying to color a specific cell in a data gridview that has the content "50" using the following code, but is not working.
Imports System.Data.SqlClient
Public Class Form1
Private ds As New DataSet
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim strConn As String
strConn = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\smdData.mdf;Integrated Security=True;User Instance=True"
Dim conn As New SqlConnection(strConn)
Dim da As New SqlDataAdapter("select Model from smdTable", conn)
da.Fill(ds, "Model")
DataGridView1.DataSource = ds.Tables("Model")
End Sub
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
Dim drv As DataRowView
If e.RowIndex >= 0 Then
If e.RowIndex <= ds.Tables("smdTable").Rows.Count - 1 Then
drv = ds.Tables("smdTable").DefaultView.Item(e.RowIndex)
Dim c As Color
If drv.Item("Model").ToString = "50" Then
c = Color.LightBlue
Else
c = Color.Pink
End If
Me.DataGridView1.Rows(e.RowIndex).Cells("Model").Style.BackColor = c
End If
End If
End Sub
End Class
You need Rowprepaint ..
Private Sub DataGridView1_RowPrePaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
Dim dgv As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
If dgv.Cells("Model").Value = "50" Then
DataGridView1.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Red
Else
DataGridView1.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Black
End If
End Sub
Input the cell value that you want to check if it has a value of 50. I added a quote "INPUT CELL NO. HERE"
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
For Each rw As DataGridViewRow In dgvStocks.Rows
If rw.Cells(INPUT CELL NO. HERE!).Value = 50 Then
rw.DefaultCellStyle.BackColor = Color.Red
rw.DefaultCellStyle.ForeColor = Color.White
Else
rw.DefaultCellStyle.BackColor = Color.DarkGreen
rw.DefaultCellStyle.ForeColor = Color.Yellow
End If
Next
End Sub

How can I make a Window Form return value of selected button

I am making a graphical representation of a movie cinema room on a windows form. Each seat is represented as a button.
I have another button on another form that is used to book a seat. This button initiates the cinema room form and if the user clicks on any button, the text on that button should be returned and displayed.
The Cinema room class (Graphical Representation)
Imports System.Data.SqlClient
Public Class Cinema1Seats
Dim seat As String = vbNull
Private Sub Cinema1Seats_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
con = getconnect()
con.Open()
Dim comm As New SqlClient.SqlCommand
comm = New System.Data.SqlClient.SqlCommand("select * from seats ", con)
' comm.Parameters.Add("#id", SqlDbType.VarChar).Value = ticketNumber
Dim sqlReader As System.Data.SqlClient.SqlDataReader
sqlReader = comm.ExecuteReader
Do While sqlReader.Read
Dim seat As String = sqlReader.GetString(0)
Dim seatbtn As New Button
seatbtn.Width = 50
seatbtn.Height = 20
seatbtn.Text = seat
AddHandler seatbtn.Click, AddressOf Me.Button_Click ' Again from answer by Reed.
Me.FlowLayoutPanel1.Controls.Add(seatbtn)
Loop
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim asas As String = (CType(sender, System.Windows.Forms.Button).Text)
MsgBox(asas)
End Sub
Public Function getseat() As String
If (seat = vbNull) Then
Else
Return seat
Me.Close()
End If
End Function
End Class
The Second form which has the button
Public Class SampleSeat_vb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim flag As Integer = 0
Dim i As Integer = 0
While i < Application.OpenForms.Count And flag = 0
If Application.OpenForms(i).Name = "Cinema1Seats" Then
flag = 1
End If
i += 1
End While
If flag Then
Application.OpenForms("Cinema1Seats").BringToFront()
Else
Dim str As New Cinema1Seats
str.Show()
Dim we As String = str.getseat
MsgBox("You selected : " + we)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SampleSeat_vb_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
It is not enitrely clear to me what you are trying to achieve but in order to find the text of the button that was clicked you can do something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim btn As Button = CType(sender, Button)
MessageBox.Show("You clicked on " + btn.Text")
End Sub