2012-12-07 157 views
1

我试图使用从我的Web窗体上的下拉列表中选择的值创建到期日期,但是我无法连接Month变量值和Year变量值。我收到错误:错误操作符'&'未为'String'和System.Web.UI.WebControls.ListItem'类型定义。我也尝试过使用“+”,但得到相同的错误。连接变量

这里是我的代码:

Dim Month = monthDropDownList.SelectedValue 
Dim Year = yearDropDownList.SelectedItem 
Dim MonthYear = Month & Year 
Dim ExpirationDate As Date = MonthYear 

任何帮助将不胜感激。

+0

yearDropDownList.SelectedItem.ToString() – Steve

+0

是固定的错误。谁知道这很简单。非常感谢您的帮助。 – Stizz1e

回答

5

你不想要SelectedItem。你想要SelectedValue。你也应该明确地声明你的变量。您也不能以这种方式创建日期。你需要使用整数。

Dim Month As Integer= Convert.ToInt32(monthDropDownList.SelectedValue) 
Dim Year as Integer = Convert.ToInt32(yearDropDownList.SelectedValue) 
Dim ExpirationDate As Date = New Date(Year, Month, 1) 

随着轻微的 “干净” 的方式做到这一点,我会用:

Dim Month as Integer 
Dim Year As Integer 
Dim ExpirationDate As Date 

Integer.TryParse(monthDropDownList.SelectedValue, Month) 
Integer.TryParse(yearDropDownList.SelectedValue, Year) 
If (Month > 0 AndAlso Year > 0) Then 
    ExpirationDate = New Date(Year, Month, 1) 
End If 
+0

下个月的“1”是什么? – Stizz1e

+0

@ Stizz1e:走出内存(所以我可能是错的),但我相信Date的构造函数需要Day的值。由于OP不使用白天,1是一个很好的保证默认值。 –

+0

Joel谢谢,这很有道理,你的代码也更清晰了,尽管编译器不喜欢它,但我不得不删除第二个'&'。 – Stizz1e