2009-02-02 29 views

回答

4

您不能,唯一的屬性System.String具有長度,並且DataKeyName需要您綁定到的對象的屬性。爲了回答第二個問題,下面是從GridViewRow獲取字符串值的示例。

在您的ASPX文件:

<asp:GridView ID="GridView1" runat="server" 
    OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false"> 
    <Columns> 
     <asp:TemplateField HeaderText="String Value"> 
      <ItemTemplate> 
       <%# Container.DataItem %> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

在您的代碼隱藏:

protected void Page_Load(object sender, EventArgs e) { 
    string[] arrayOfStrings = new string[] { "first", "second", "third" }; 
    GridView1.DataSource = arrayOfStrings; 
    GridView1.DataBind(); 
} 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { 
    if (e.Row.RowType == DataControlRowType.DataRow) { 
     // e.Row is of type GridViewRow 
     // e.Row.DataItem contains the original value that was bound, 
     // but it is of type object so you'll need to cast it to a string. 
     string value = (string)e.Row.DataItem; 
    } 
} 

唯一合理的解決辦法的問題是創建具有特性的包裝類。或者,如果您使用的是.NET 3.5,則可以使用LINQ創建一個臨時列表,其中只包含您的值作爲類的屬性。有一個example of this technique on MSDN Forumsvtcoder

List<string> names = new List<string>(new string[] { "John", "Frank", "Bob" }); 

var bindableNames = from name in names 
        select new {Names=name}; 

GridView1.DataSource = bindableNames.ToList(); 

然後「Name」將是DataKeyName和BoundField DataField。

相關問題