2012-05-22 22 views
0

我是VB.net(編程)的新手。我需要關於Gridview控件的建議。在GridView單元格/列中提取數據

我有一個gridview加載兩列 - 一列(名稱)與一些文本,另一個(價格)是空的。

我有一個文本框的名稱和價格的數據。

現在,我想遍歷文本框,查看GridView控件的Column(Name)的Data/symbols是否與Textbox中的Data匹配。

如果GridView的第一列數據的名稱與文本框的名稱匹配,則應該在GridView的第二列(價格)中獲取價格數據。

爲了使它更清楚,說:

我在文本框下面的數據:

名稱 - 價格

AB- 50

DE-80

而且我在GridView中有兩列,提供以下設置:

名(列1) - 價格(列2)

AB-空
DE-空

現在,我怎麼能得到文本框的價格數據,並把它們取到的GridView的列2匹配的名稱列1。所以,在GridView的輸出應該是:

名稱(列1) - 價格(列2)

AB- 50
DE-80

到目前爲止,我已經能夠只是通過循環GridView的第一列... ..我不確定如何從Textbox獲取數據並將數據提取到GridView的Column2中。

任何建議將不勝感激。

公共類Form1中

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 

    'Data of GridView 
    Dim dt As New DataTable() 
    dt.Columns.Add("Name") 
    dt.Columns.Add("Price") 
    dt.Rows.Add(New [Object]() {"AB"}) 
    dt.Rows.Add(New [Object]() {"DE"}) 
    Me.DataGridView1.DataSource = dt 


    'Data of Textbox 
    TextBox1.Text = "AB, 50" & vbNewLine & "DE, 100" 


End Sub 




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    'loop through the gridview 
    Dim marketvalue As String 
    For Each r As DataGridViewRow In Me.DataGridView1.Rows 
     marketvalue = r.Cells(0).Value 
     MessageBox.Show(marketvalue) 
    Next 
End Sub End Class 

回答

0

我會用一個單獨的功能,從您的文本框

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    'loop through the gridview 
    Dim marketvalue As String 
    Dim price As String 
    For Each r As DataGridViewRow In Me.DataGridView1.Rows 

     marketvalue = r.Cells(0).Value 
     MessageBox.Show(marketvalue) 

     'Get the price by calling a function and update it back to the DataGrid 
     price = get_price(marketvalue) 
     r.Cell(1).Value = price 
    Next 
End Sub 

以下功能可以通過將名稱返回你的價格得到的價格參數,否則爲空如果名稱未找到

Private Function get_price(ByVal strName As String) As String 

    Dim string_array() As String = TextBox1.Text.Split(System.Environment.vbNewLine) 
    For Each s As String In string_array 
     Dim string_detail() As String = s.Split(",") 
     If string_detail(0) = strName Then 
      Return Trim(string_detail(1)) 
     End If 
    Next 

    Return "" 
End Function 
+0

嗨,尼克,感謝您的反饋。我只是在你的幫助下解決了我的問題。我是你的救星,我的朋友。我的問題解決了!非常感謝你的幫助。 –

相關問題