Name a column in datagridview - vb.net

I came up with following code that adds number of columns based on user input in textbox1, but how to add names to these columns? (Columns added should have names like, A1,A2,A3.......on the top most row)
Dim t As Integer
t = Val(TextBox1.Text)
For i = 1 To t
Form2.DataGridView1.ColumnCount = i
Next
Also can we freeze specific cells in a datagridview i.e. cells which user cannot edit?

Try this
DataGridView1.Columns(i).Name = String.Format("A{0}", i)
Once you have access to Columns(i) you can view available properties from the intellisense
DataGridView1.Columns(0).Frozen = True;

The DataGridView only has methods for freezing Rows or Columns, in order to block editing of a specific cell you can try adding a handler for the CellBeginEdit event then check for the Row and Column of the Cell(s) that you want to prevent editing of then cancel the event.
something like this:
Private Sub DataGridView1_CellBeginEdit(sender As Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
If e.ColumnIndex = 0 And e.RowIndex = 0 Then
e.Cancel = True
End If
End Sub

this.dataGridView1.Columns["StudentId"].ReadOnly = true;
from: http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/fef91d76-24c5-4b41-84d7-ba133de2d9a7#b2cb53ec-5b15-4385-b086-28a6dc93dfc9

Related

DataGridView live search data

I am trying to add a search function to a DataGridView in vb.net using this code
For i As Integer = 0 To ContactsList.RowCount - 1
For j As Integer = 0 To ContactsList.ColumnCount - 1
If ContactsList.Rows(i).Cells(j).Value.ToString.ToLower.Trim = ContactsListSearch.Text.ToLower.Trim Then
MsgBox("Item found " + i.ToString)
ContactsList.Rows(i).Visible = True
Else
ContactsList.Rows(i).Visible = False
End If
Next
Next
I'm seeing the MsgBox show when the value matches, but the rows are not showing, it just hides all rows
Another possible option is to load data into a DataTable, create a BindingSource, set the BindingSource DataSource property to the DataTable. Set the DataGridView DataSource property to the BindingSource.
The following example works against a column in the DataTable. If the user clears the TextBox the filter is removed while if there is text filter with trim.
Private Sub SearchButton_Click(sender As Object, e As EventArgs) _
Handles SearchButton.Click
If String.IsNullOrWhiteSpace(SearchTextBox.Text) Then
bindingSource.Filter = ""
Else
Dim currentRowCount = bindingSource.Count
bindingSource.Filter = $"TRIM(LastName) = '{SearchTextBox.Text}'"
MessageBox.Show($"Before: {currentRowCount} Now: {bindingSource.Count}")
End If
End Sub
Edit If the column name might be variable consider loading a ComboBox with column names then adjust code as follows.
bindingSource.Filter = $"TRIM({FilterComboBox.Text}) = '{SearchTextBox.Text}'"
In most cases working against a data source is better than working against cells values as per the above recommendation.
I added 2 Exits in the IF statement when the value matches as it's searching each column as well, so it was causing them to be hidden as it loops columns too
For i As Integer = 0 To ContactsList.RowCount - 1
For j As Integer = 0 To ContactsList.ColumnCount - 1
If ContactsList.Rows(i).Cells(j).Value.ToString.ToLower.Trim = ContactsListSearch.Text.ToLower.Trim Then
MsgBox("Item found " + i.ToString)
ContactsList.Rows(i).Visible = True
Else
ContactsList.Rows(i).Visible = False
End If
Next
Next

RowIndex in CellValueChanged event of my DataGridView is -1

I need to change some data before showing into a DataGridView and I'm using CellValueChanged event. The problem is that e.RowIndex is -1 when datagridview is filling with a datasource.
Private Sub dgvList_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvList.CellValueChanged
' Convert date to Persian if the edited cell has date
If dgvList.Rows(e.RowIndex).Cells.Item(e.ColumnIndex).ValueType.ToString = "" Then
' Do something
End If
End Sub
I update values using it's data source. I change DataTable and the DataGridView updates automatically:
Dim MyRow = dstList.Tables("list").NewRow
MyRow.Item("date_reported") = PersianDateTime.Parse(txtDateReport.Text).ToDateTime
MyRow.Item("description") = txtDescription.Text
MyRow.Item("duration") = txtDuration.Text
MyRow.Item("coworkers") = txtCoworkers.Text
MyRow.Item("progress") = numProgress.Value
MyRow.Item("problems") = txtProblems.Text
MyRow.Item("date_created") = Now.Date
' Add this row to the dataset
dstList.Tables("list").Rows.Add(MyRow)
' Apply changes to database
UpdateList()
That's normal. I think it's when the column headers are set. You just have to add an If statement to the event handler to filter that out.
If e.RowIndex <> -1 Then
'It's a valid cell.
End If
If e.RowIndex > -1 AndAlso e.ColumnIndex > -1 Then
Debug.Print(dgvList(e.ColumnIndex, e.RowIndex).ValueType.ToString)
Debug.Print(dgvList(e.ColumnIndex, e.RowIndex).Value.ToString)
End If
Works fine for me.
How are you changing values?
Also post part of the code that changes it. As source of change gives the index not the result (the code you posted).

Add calculated value to DatagridView from getting value from another datagridview in vb.net

I have an vb.net windows application that has some values which i entered through textbox.
And two datagridviews, in that in first datagridview ,when i enter values in all columns, i have a formula which takes value from Textboxes and DatagridView1 column values. These calculated value should display in second datagridview columns.
For this i tried two ways but both showing problem.
First try:
//First Datagridview -LogCalcEnter , Second Datagrid - LogCalValue
Private Sub LogCalcEnter_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles LogCalcEnter.CellValueChanged
LogCalValue.Rows(intRow).Cells(0).Value = LogCalcEnter.Rows(iRow).Cells(0).Value * fPorCutoff.Text
LogCalValue.Rows(intRow).Cells(1).Value = LogCalcEnter.Rows(iRow).Cells(1).Value * fSWCutoff.Text
End Sub
When executing the application,before showing the form below error occurs at
Me.MainForm = Global.LogCalculation.Form1 in OnCreateMainForm().
Additional information: An error occurred creating the form. See
Exception.InnerException for details. The error is: Index was out of
range. Must be non-negative and less than the size of the collection.
Parameter name: index
So i tried another option i have button in form, when i press button,then depends on number of rows in first grid view i will set the values for second datagrid.
But it works if i have one row in Datagridview1. If more than one row, it shows error at second row.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim oLog As New Log
oLog.sWellName = tWellname.Text
oLog.fPoroCutoff = fPorCutoff.Text
oLog.fSWCutOff = fSWCutoff.Text
oLog.fN = fN.Text
oLog.fM = fM.Text
oLog.fA = fA.Text
oLog.fRW = fRW.Text
For iRow = 0 To LogCalcEnter.Rows.Count - 1
If (Trim(LogCalcEnter.Rows(iRow).Cells(0).Value) <> "" And Trim(LogCalcEnter.Rows(iRow).Cells(1).Value) <> "" And Trim(LogCalcEnter.Rows(iRow).Cells(2).Value) <> "") Then
LogCalValue.Rows(iRow).Cells(0).Value = LogCalcEnter.Rows(iRow).Cells(0).Value * oLog.fPoroCutoff
LogCalValue.Rows(iRow).Cells(1).Value = LogCalcEnter.Rows(iRow).Cells(1).Value * oLog.fSWCutOff
LogCalValue.Rows(iRow).Cells(2).Value = LogCalcEnter.Rows(iRow).Cells(2).Value * oLog.fN
End If
Next iRow
End Sub
Actually i want the first option only. But here these two cases get failed.
In the first event, your intRow & iRow may not be defined.
Try this instead,
LogCalValue.Item(0, e.RowIndex).Value = LogCalcEnter.Item(0, e.RowIndex).Value * fPorCutoff.Text
LogCalValue.Item(1, e.RowIndex).Value = LogCalcEnter.Item(1, e.RowIndex).Value * fSWCutoff.Text

Changing double clicking activation on Combo box cell to single click?

I have a setup in my code where there is a datagridview. For each row I have a combo box cell that I have a separate combo box cell since I want a different selection of items for each cell.
Problem : The cell only drops down when the arrow is double clicked. How can I change the cell formatting, or possibly a cell click event, so that the cell response to just one click?
Here's my cell creation code. Frankly, I didn't start any other code since I didn't know what event to touch or call. Is there a property I can edit?
Code:
'add items to combobox list
Dim comboCell As New DataGridViewComboBoxCell
comboCell.FlatStyle = FlatStyle.Flat
Dim resolutionList As New List(Of cmbStruct)
Dim currentResIndex As Integer = 0
'create list of resolutions
For j As Integer = 0 To resolutions.Length - 1
Dim resClass As New cmbStruct
resClass.Name = resolutions(j)
resClass.ID = resolutions(j)
resolutionList.Add(resClass)
comboCell.Items.Add(resolutions(j))
Next
'set combocell values
comboCell.DisplayMember = "Name"
comboCell.ValueMember = "ID"
'set the default value to the current resolution index
Try
comboCell.Value = resolutions(currentResIndex)
Catch ex As Exception
End Try
comboCell.ValueType = GetType(cmbStruct)
comboCell.DataSource = resolutionList
editCameraTable("Resolution", i) = comboCell
Next
Change the EditMode property:
DataGridView1.EditMode = DataGridViewEditMode.EditOnEnter
There seems to be a nearly identical question and a very good answer. It involves using the click_event. Here is the link:
How to manually drop down a DataGridViewComboBoxColumn?
In the link:
Private Sub cell_Click(ByVal sender As System.Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
DataGridView1.BeginEdit(True)
If DataGridView1.Rows(e.RowIndex).Cells(ddl.Name).Selected = True Then
DirectCast(DataGridView1.EditingControl, DataGridViewComboBoxEditingControl).DroppedDown = True
End If
End Sub

VB DataGridView 1 Row selection

I have a problem . When I load my form with my datagridview , I want the data to be transferred to the text fields when I click on the > at the most left of the datagridview.
Now, I have to select the content in the rows itself to select a row. How do I set it so it selects row based on the most left row selector? instead of having me click on the contents of the row ? dtguser_CellContentClick makes me select based on the content click right? What should it be if I want to select by entire row?
Private Sub dtguser_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dtguser.CellContentClick
If GroupBox3.Enabled = False Then
Else
'this code will simply pass the value from the specific row selected by the user
lblid.Text = dtguser.CurrentRow.Cells(0).Value
serial.Text = dtguser.CurrentRow.Cells(0).Value
fname.Text = dtguser.CurrentRow.Cells(1).Value
lname.Text = dtguser.CurrentRow.Cells(2).Value
gender.Text = dtguser.CurrentRow.Cells(3).Value
address.Text = dtguser.CurrentRow.Cells(4).Value
contact.Text = dtguser.CurrentRow.Cells(5).Value
course.Text = dtguser.CurrentRow.Cells(6).Value
datestart.Text = dtguser.CurrentRow.Cells(7).Value
datecomplete.Text = dtguser.CurrentRow.Cells(8).Value
datecertify.Text = dtguser.CurrentRow.Cells(9).Value
nationality.Text = dtguser.CurrentRow.Cells(10).Value
email.Text = dtguser.CurrentRow.Cells(11).Value
certification.Text = dtguser.CurrentRow.Cells(12).Value
End If
End Sub
If you want to select the entire row set the selection mode to FullRowSelect.
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
If you want to get the data when you click the RowHeader (> button) then subscribe to the RowHeaderMouseClick event.
dataGridView1.RowHeaderMouseClick += new DataGridViewCellMouseEventHandler(dataGridView1_RowHeaderMouseClick);
Private Sub dataGridView1_RowHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs)
// put your code for copying row data into the textboxes.
End Sub