2011-05-31 183 views
0

有没有一种方法来存储来自DataList的字段?将datalist eval存储到变量中

string year = Eval("date"); 

我想要做的字符串操作一年,并且需要如果可能的话,将其存储在变量!

回答

2

如果你使用eval,我猜你正在做一个数据绑定表达式中的工作?如果是这样,那通常是错误的地方做数据的任何实际的后处理,但如果你必须这样做,你应该能够明确地投,像这样:

string year = (string)Eval("date") 

或者,如果变量ISN” T A字符串类型本身,

string year = Eval("date").ToString() 

更重要的是,添加到您的网页的功能,它接受一个对象参数和所进行的处理,像这样:

public string DoSomething(object value) 
{ 
    var year = value.ToString(); // or alterinately... 
    var year = value as string(); 

    if (!string.IsNullOrEmpty(year)) 
    { 
     // do something to the year 
     return year; 
    } 

    return ""; // default in case you can't process the value 
} 

然后,在你的ASP.NET页面,每当你正在做数据绑定...

<%# DoSomething(Eval("date")) %> 
1
<asp:Label ID="Label1" runat="server" Text='<%# GetLabelText(Eval("date")) %>' /> 

string GetLabelText(object date) 
{ 
    if (date != null) 
    { 
     ... 
     // here you can cast date to appropriate type (possibly DateTime) and 
     // store that in a variable, manipulate it and return a text that would be 
     // displayed by Label1 
    } 
} 
+0

是唯一的方法吗?有没有办法简单地把它直接放入一个变量? – AlanFoster 2011-05-31 18:27:50

+0

您可以在某种程度上按照标记操作,但不能在其中引入变量。 – 2011-05-31 18:29:53