2013-07-03 28 views
0

我在一個字段中有一個數據庫,如下面的222-225。我嘗試進行拆分以讀取該函數的值。只是簡單的函數a = 225 b = 222那麼總數=(a-b)+1。這裏我的代碼如何在vb.net中通過拆分獲得值2005

Dgv.CellClick 
'Dim x As Boolean 
Dim a As Double 
Dim total As Double 

a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value) 
Split(a, "-") 
total = (a) - (a) 
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total 

我的問題是這是行不通的。我無法獲得我分裂的價值。任何想法如何解決這個問題?

注:我用VB.NET 2005

回答

1

可能會有這種幫助。試試這個...

Dim a As String 
      a = "" 
      Dim x As String 
      Dim total As Double 
      a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString 
      Dim ary() As String 
      x = a 
      ary = x.Split("-") 
      total = CInt(ary(1)) - CInt(ary(0)) 

      Dgv.Item(9, Dgv.CurrentRow.Index).Value = total 
2

如果你想total=(a-b)+1 ..這應該是

dim b = a.Split("-") 

total = val(b(1)) - val(b(2)) + 1 
+0

仍然錯誤「表達式不是一個數組或梅索德水溼的參數列表」 – Andriansyah

+0

@AndriansyahAndri ..有一些錯誤..它已經更新 – matzone

0

分割返回數組。像這樣的東西。 VB.Net不是我的主要語言,但這應該有所幫助。

dim arr = a.Split(New Char(){"-"}) 
total = ctype(arr(0), double) - ctype(arr(1),double) 
1

像其他人說,Split()返回String陣列,像這樣:

Dim SplitValue() As String = Split(a, "-") 
total = (CType(SplitValue(1), Double) - CType(SplitValue(0), Double)) + 1 
+0

錯誤「索引範圍之外 到錯誤「 – Andriansyah

+0

然後你的值沒有」 - 「來分割。檢查你是否得到正確的值 – SysDragon

0

試試這個:

Dim aux() As String = a.Split("-"c) 

total = CDbl(aux(0)) - CDbl(aux(1)) + 1 
0
Dim a As string 
Dim x As String 
Dim total As Double 

a = Dgv.Item(8, Dgv.CurrentRow.Index).Value 

Dim ary() As String 
x = a 

ary() = x.Split("-") 
total = CInt(ary(1)) - CInt(ary(0)) 

Dgv.Item(9, Dgv.CurrentRow.Index).Value = total 
+0

錯誤表示「對象引用未設置爲對象的實例。」 錯誤「 – Andriansyah

+0

@AndriansyahAndri - 哪行發生錯誤? – Tim

+0

請注意'ary()= x.Split(「 - 」)不會編譯。 – Tim

1

如果我正確地讀你的問題,值你正在尋找的是222-225,並且該值位於Dgv的指定單元格中(我猜測它是一個DataG ridView)。如果我的理解是正確的,那麼有一些事情正在進行。

首先,我不知道爲什麼你試圖將該值轉換爲雙用下面的代碼行:

a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value) 

一個DataGridView的Item屬性包含DataGridViewCellValueDataGridViewCell的財產返回Object。試圖將222-225轉換爲雙精度型,我相信會失敗(儘管因爲這是VB.NET,所以它可能不會取決於您設置的選項 - 我對VB.NET並不像我一樣熟悉與C#)。

即使它成功工作(我不確定輸出是什麼),Split需要一個字符串。我會將該行代碼更改爲以下內容:

a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString() 

現在您有一個字符串,您可以使用Split。您在發佈的代碼中擁有的Split似乎是Visual Basic(pre-.NET)Split方法Split Function (Visual Basic)。正如其他人所說的,Split根據分隔符返回一個字符串數組。在您的代碼中,您不會將Split的結果分配給任何內容,因此您無法獲取值。

我會建議使用分體式的.NET版本(String.Split Method) - 有幾種方法你可以打電話String.Split,但對你的代碼的目的,我會使用這樣的:

Dim splits As String() = a.Split(New Char() { "-" }) 

凡是上面選定的DataGridViewCell的字符串值。這將給你一個2元素陣列:

splits(0) = "222" 
splits(1) = "225" 

最後一部分是你的公式。既然你有一個字符串,你需要將它們轉換爲數字數據類型:

total = (CDbl(splits(1)) - CDbl(splits(0))) + 1 

,這已經成爲(225 - 222)+ 1 = 4

把它完全會是這個樣子:

Dim a As String 
Dim total As Double 
Dim splits() As String 

a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString() 

splits = a.Split(New Char() { "-" }) 

total = (CDbl(splits(1)) - CDbl(splits(0))) + 1 

Dgv.Item(9, Dgv.CurrentRow.Index).Value = total