我一直在尋找對我的問題的答案,但不幸的是沒有取得任何成功。使用內部和外部for循環填充datagridview的困難
首先,這裏是我的代碼:
For x = 0 To (NumberOfRows - 1)
For y = 0 To (NumberOfColumns - 1)
DataGridView1.Rows(x).Cells(y).Value = TrimmedData(ArrayIndex)
ArrayIndex = ArrayIndex + 1
Next
Next
我已經預先設定的行爲的DataGridView的列數和數量。上面的代碼然後遍歷兩個for循環,試圖用字符串數組中的數據填充datagridview。
問題是這條線的位置:
DataGridView1.Rows(x).Cells(y).Value = TrimmedData(ArrayIndex)
它不喜歡它,當我有變量x和y(確定行和單元格位置),它工作正常,如果我剛纔的變量x或者只是變量y(,另一個是一個固定的數,例如該代碼是罰款:
DataGridView1.Rows(x).Cells(0).Value = TrimmedData(ArrayIndex)
任何一個能放下架子,我怎麼能去約在一個循環中填充數據,如本?
提前謝謝。
編輯,這裏是全子程序代碼:
Private Sub ExtractData()
Dim x As Decimal = 0
Dim y As Decimal = 0
Dim GetData As String = " StartOfData ,10,03,John Smith,8207176,a,c,d,b,d,a,b,d,c,b,Bill McBill,8109871,b,d,c,b,a,d,c,b,d,a,Amy Bunton,8212345,a,d,c,a,d,b,c,d,b,c, EndOfData "
Dim TrimmedData() As String = GetData.Split(",")
' we need to find where the start of our data is (we do this because we may have recieved the same data, multiple times.)
While TrimmedData(x) <> " StartOfData "
x = x + 1
End While
Dim StartOfArrayData As Decimal = (x + 1) 'we have just found where StartOfData is written, so we add one to go to the actual start of our data
Dim ArrayIndex As Decimal = StartOfArrayData
Dim NumberOfColumns As Decimal = TrimmedData(ArrayIndex) + 2 'the first number in the array tells us how many questions there are in the exam. We add 2 because we need the student name and ID number
ArrayIndex = ArrayIndex + 1 ' now we are at the location where it tells us how many students there are.
Dim NumberOfRows As Decimal = TrimmedData(ArrayIndex) + 1 ' we need to add one extra row because we have a certain number of rows for our student names + one extra for the headings
ArrayIndex = ArrayIndex + 1
DataGridView1.ColumnCount = NumberOfColumns
DataGridView1.RowCount = NumberOfRows
' and now we need to know where the end of our data is
While TrimmedData(x) <> " EndOfData "
x = x + 1
End While
Dim EndOfArrayData As Decimal = (x - 1) 'we have just found where EndOfData is written, so we minus one to go to the actual end of our data
For x = 0 To (NumberOfRows - 1) ' we minus one because we are starting from 0 and not 1
For y = 0 To (NumberOfColumns - 1) ' we minus one because we are starting from 0 and not 1
DataGridView1.Rows(x).Cells(y).Value = TrimmedData(ArrayIndex)
ArrayIndex = ArrayIndex + 1
Next
Next
End Sub
有關背景信息 - 我剛開始學習製作考試系統,讓學生有一個小的無線設備與他們五個按鈕標記ABCD和提交,學生將在數據投影儀上顯示問題,然後按下其中一個ABCD按鈕,然後提交。這個答案將被髮送到連接到計算機的基於微控制器的設備。一旦提交了所有問題的所有答案,它就會將數據串行發送到計算機程序(我正在使用這個Visual Basic程序),這些數據將被用於我的代碼中 - 目前我只是通過將數據在一些默認數據IE中
Dim GetData As String = " StartOfData ,10,03,John Smith,8207176,a,c,d,b,d,a,b,d,c,b,Bill McBill,8109871,b,d,c,b,a,d,c,b,d,a,Amy Bunton,8212345,a,d,c,a,d,b,c,d,b,c, EndOfData "
希望幫助:)
請告訴我的錯誤信息您收到? – PGallagher
好點,它讀取「重載解析失敗,因爲沒有可訪問的'項目'可以調用沒有縮小轉換。」 – BradSlattery
什麼類型是你的列...例如...我已經測試了三個DataGridViewTextBoxColumn的上述...儘管我不得不在內部循環中添加一個新的行,使其工作;-)我懷疑也許你的在另一個地方使用另一個列類型? – PGallagher