Add calculated value to DatagridView from getting value from another datagridview in vb.net - 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

Related

How I can set the index of Datagridview to 0

How I can set the index of DataGridView to 0?
I developed a pharmacy software where I want to add values from TextBoxes into DataGridView with adding a new row. It is working but the problem is when I clear the value of DataGridView by using this code
dgvSoldMedicineInfo.Rows.Clear()
then when I try the previous procedure it show this error in VB.NET
Index was out of range, Must be non-negative and less than the size of the collection. Parameter name:index
Code:
Dim rowcounter As Integer = 0
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
dgvSoldMedicineInfo.Rows.Add()
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnBarcodeNo").Value = txtBarcodeNo.Text
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnName").Value = dgvSale.CurrentRow.Cells(2).Value
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnQuantity").Value = txtQuantity.Text
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnSalePrice").Value = txtSalePrice.Text
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnAmount").Value = txtTotalAmount.Text
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnReject").Value = "Reject"
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnStockID").Value = dgvSale.CurrentRow.Cells(0).Value
dgvSoldMedicineInfo.Rows(rowcounter).Cells("ColumnStockQuantity").Value = dgvSale.CurrentRow.Cells(3).Value
System.Math.Max(System.Threading.Interlocked.Increment(rowcounter), rowcounter - 1)
End Sub
There's really no point to that rowcounter variable in that context and it's bad form to keep using dgvSoldMedicineInfo.Rows(rowcounter) over and over again. The proper way to do that would be like so:
Dim rowIndex = dgvSoldMedicineInfo.Rows.Add()
Dim row = dgvSoldMedicineInfo.Rows(rowIndex)
Dim cells = row.Cells
cells("ColumnBarcodeNo").Value = txtBarcodeNo.Text
cells("ColumnName").Value = dgvSale.CurrentRow.Cells(2).Value
'etc.
That said, why do that when the Add method is overloaded and will accept all the cell values up front?
dgvSoldMedicineInfo.Rows.Add(txtBarcodeNo.Text,
dgvSale.CurrentRow.Cells(2).Value,
...)

Pass values from Numeric control into corresponding cells in DataGridView control with a button

I want to move the values from each of four Numeric Up/Down controls into the DataGridView columns/rows with a button. For instance, the operator sets the values in the up/down numeric controls and then clicks the button. The program should then add a new row to the DataGridView and pass whatever values that are in the Numeric Up/Down controls into the new cells of the new row. As of now, I have the adding new rows part of it working as well as the delete button working (delete last row of the DataGridView). Now, how to pass the Numeric control values into the cell of the new row of the DataGridView with the button? Each new row created of the DatGridView has four cells to correspond to the four Numeric up/down controls. Thank you.
Private Sub addStep_btn_Click(sender As Object, e As EventArgs) Handles addStep_btn.Click
LftMtr_Data_Grid.ColumnCount = 4
LftMtr_Data_Grid.RowCount = LftMtr_Data_Grid.RowCount + 1
LftMtr_Data_Grid.Columns(0).HeaderText = " Spindle Speed (rpm)"
LftMtr_Data_Grid.Columns(1).HeaderText = " Accel Rate (rpm/S)"
LftMtr_Data_Grid.Columns(2).HeaderText = " Decel Rate (rpm/S)"
LftMtr_Data_Grid.Columns(3).HeaderText = " Time (S)"
For Each c As DataGridViewColumn In LftMtr_Data_Grid.Columns
c.Width = 120
Next
Dim rowNumber As Integer = 1
For Each row As DataGridViewRow In LftMtr_Data_Grid.Rows
If row.IsNewRow Then Continue For
row.HeaderCell.Value = "Step " & rowNumber
rowNumber = rowNumber + 1
Next
LftMtr_Data_Grid.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
rowCount1 = LftMtr_Data_Grid.RowCount
txtBox1.Text = rowCount1
End Sub
Try something like below. Note that you don't need to setup the column headers everytime, just once in the Load() event would do!
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LftMtr_Data_Grid.ColumnCount = 4
LftMtr_Data_Grid.Columns(0).HeaderText = " Spindle Speed (rpm)"
LftMtr_Data_Grid.Columns(1).HeaderText = " Accel Rate (rpm/S)"
LftMtr_Data_Grid.Columns(2).HeaderText = " Decel Rate (rpm/S)"
LftMtr_Data_Grid.Columns(3).HeaderText = " Time (S)"
For Each c As DataGridViewColumn In LftMtr_Data_Grid.Columns
c.Width = 120
Next
LftMtr_Data_Grid.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
End Sub
Private Sub addStep_btn_Click(sender As Object, e As EventArgs) Handles addStep_btn.Click
Dim values() As Object = {NumericUpDown1.Value, NumericUpDown2.Value, NumericUpDown3.Value, NumericUpDown4.Value}
Dim index As Integer = LftMtr_Data_Grid.Rows.Add(values)
LftMtr_Data_Grid.Rows(index).HeaderCell.Value = "Step " & (index + 1)
LftMtr_Data_Grid.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
End Sub
Private Sub delStep_btn_Click(sender As Object, e As EventArgs) Handles delStep_btn.Click
If LftMtr_Data_Grid.Rows.Count > 0 Then
LftMtr_Data_Grid.Rows.RemoveAt(LftMtr_Data_Grid.Rows.Count - 1)
End If
End Sub
End Class
I figured it out on my own. Here is what I came up with:
Dim rowNumber As Integer = 1
For Each row As DataGridViewRow In LftMtr_Data_Grid.Rows
If row.IsNewRow Then Continue For
row.HeaderCell.Value = "Step " & rowNumber
LftMtr_Data_Grid.CurrentCell = LftMtr_Data_Grid.Rows(LftMtr_Data_Grid.RowCount - 1).Cells(0)
LftMtr_Data_Grid.CurrentRow.Cells(0).Value = LftMtr_Speed_Incr.Value
LftMtr_Data_Grid.CurrentRow.Cells(1).Value = LftMtr_Accel_Incr.Value
LftMtr_Data_Grid.CurrentRow.Cells(2).Value = LftMtr_Decel_Incr.Value
LftMtr_Data_Grid.CurrentRow.Cells(3).Value = test_Time_Incr1.Value
rowNumber = rowNumber + 1
Next
This application works with an empty or partially filled dataGridView. When the user clicks the button, the code creates a new row in the dataGridView, makes the new row the selected row, and then finally populates each of the cells in the new row with the values that are in the four Numeric Up/down controls (could be a text box too depending on your application). This is code copied directly from my specific application. Yours may differ slightly with variable names, label text, etc.

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

Name a column in datagridview

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

Datagridview in vb.net [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
DataGridView - Validating for Cell
hi...i have a requirement. i dont know how to get the data from the datagrid after the user entered data in textboxcolumn. i also want to validate the entered text in datagrid cell.
This may answer your question:
Suppose there are:
2 textboxes named "txt_X_Values" (gets the values for column "x") and "txt_Y_Values" (that gets the user input for column Y);
a button named "btnAdd_2_Table" (click to add data from textboxes to table);
a datagridview control named "dgv_RawData"; and
(of course) a form that will contain the controls/components mentioned above..
With the following codes, when the button is clicked, the button will store the data input from the textboxes to their respective arrays. In here, i have declared an array named "Column_X" that stores values from txt_X_Values.text and Column_Y for txt_Y_Values.text.
After the values are stored, i may now put/display them in the datagridview cells (codes are shown below..with the comment " ' add columns/rows to datagridview"). With such process, you can add filters/validators or whatever you would call it. You may declare a new sub or function for that.
Here are the codes:
Private Sub btnAdd_2_Table_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd_2_Table.Click
If Blank_Input(txt_X_Values.Text, txt_Y_Values.Text) Then
MessageBox.Show("You cannot have a blank data. Please provide numeric values to both columns.", _
"ERROR ON INPUT", MessageBoxButtons.OK, MessageBoxIcon.Error)
If txt_X_Values.Text = "" Or txt_X_Values.Text = " " Then
txt_X_Values.Focus()
Else
txt_Y_Values.Focus()
End If
Else
Data_InputProc()
Display_Table_Proc()
' add columns to datagridview
If rowCounter - 1 = 0 Then
dgv_RawData.Columns.Add("Column_X", x_Title)
dgv_RawData.Columns.Add("Column_Y", y_Title)
End If
' add rows to datagridview
dgv_RawData.Rows.Add(x_Column(rowCounter - 1), y_Column(rowCounter - 1))
' enable reset
btnReset.Enabled = True
' reset dot counters
dotCountX = 0
dotCountY = 0
End If
btnSave_Data.Enabled = True
End Sub
Here are the codes for the functions that I have made:
*Note that I am only filtering/validating numeric values with these codes.
(function to store data from textbox to arrays)
Public Sub Data_InputProc()
' resize array
ReDim Preserve x_Column(total_Rows), y_Column(total_Rows)
' engine
x_Column(rowCounter) = CDbl(txt_X_Values.Text)
y_Column(rowCounter) = CDbl(txt_Y_Values.Text)
'' next row
rowCounter += 1
total_Rows = rowCounter
' ready value textbox for another input from user
txt_X_Values.Clear()
txt_Y_Values.Clear()
txt_X_Values.Focus()
End Sub
(function/sub to validate numeric values...actually this code only allows the use of 1 dot per numeric entry)
' keypress handler
Public Sub NumericOnly(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles _
txt_X_Values.KeyPress, txt_Y_Values.KeyPress
' do not allow non-numeric characters but allow backspace and dot
If Not e.KeyChar Like "[0-9.]" And Asc(e.KeyChar) <> 8 Then
e.KeyChar = Nothing
ToolTip_Universal.Show("Only NUMERIC values are valid.", grpDataEntry, 300, 100, 1500)
' do not allow multiple dots
ElseIf sender Is txt_X_Values And e.KeyChar Like "." Then
dotCountX += 1
If dotCountX > 1 And e.KeyChar Like "." Then _
e.KeyChar = Nothing
ToolTip_Universal.Show("Only ONE DOT is allowed.", txt_X_Values, 130, 20, 1500)
ElseIf sender Is txt_Y_Values And e.KeyChar Like "." Then
dotCountY += 1
If dotCountY > 1 And e.KeyChar Like "." Then _
e.KeyChar = Nothing
ToolTip_Universal.Show("Only ONE DOT is allowed.", txt_X_Values, 130, 20, 1500)
End If
End Sub
I hope this one helps you out with your problem:
I built a simple program that lets the user put values to the datagridview control. After that, a button is pressed to get the values from that table and store it to a 2D array. The array may then be used to manipulate data as you wish.
Code:
' declare array for storage of all values
Dim array_of_all_values(,) As Object
' number of columns and rows from the datagridview control
Dim Num_of_Columns, Num_of_Rows As Integer
' this block of code asks the user to how many columns does he want to add to the DGV
Private Sub btnNo_of_Columns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNo_of_Columns.Click
Num_of_Columns = txtCol_Num.Text
For columnCount = 1 To Num_of_Columns
dgv_Test.Columns.Add("Column_" & columnCount, InputBox("What is the header of Column " & columnCount & "?" & vbCrLf, "Column Header", "no header"))
Next
btnNo_of_Columns.Enabled = False
txtCol_Num.Clear()
dgv_Test.Focus()
End Sub
Private Sub btnGetSpecific_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetSpecific.Click
' this code gets the specific value of the cell that is selected by the user (selection by mouse <left> click)
rtb_TestResult.Text = dgv_Test.Item(dgv_Test.CurrentCellAddress.X, dgv_Test.CurrentCellAddress.Y).Value
' you may now insert the value of the cell into a variable
' you may code for the specific validation that you require/desire
End Sub
Private Sub btnGetAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetAll.Click
Dim rowValue As String
' this code will get values of all cells and record it to an array
Num_of_Rows = dgv_Test.RowCount - 1
ReDim Preserve array_of_all_values(Num_of_Rows, Num_of_Columns)
For dgvColumnIndex = 0 To Num_of_Columns - 1
For dgvRowIndex = 0 To Num_of_Rows - 1
array_of_all_values(dgvRowIndex, dgvColumnIndex) = dgv_Test.Item(dgvColumnIndex, dgvRowIndex).Value
Next
Next
' you may now manipulate the inputs using the 2d array
' you may now construct validation codes
' this code displays the array values in table form
' this is useful in checking arrays
For arr_X_index = 0 To UBound(array_of_all_values, 1)
For arr_Y_index = 0 To UBound(array_of_all_values, 2)
rowValue &= array_of_all_values(arr_X_index, arr_Y_index) & vbTab
Next
rtb_TestResult.Text &= rowValue & vbCrLf
rowValue = ""
Next
End Sub
Sample of how the program worked:
Hope that answers your problem.. please be specific next time. :D