3
任何人都可以給我一個簡短的片段,給出一個最初綁定到一個簡單的字符串數組,並給定一個GridViewRow行的GridView,將返回綁定到該行的值?綁定到字符串數組的gridview的dataKeyName是什麼?
任何人都可以給我一個簡短的片段,給出一個最初綁定到一個簡單的字符串數組,並給定一個GridViewRow行的GridView,將返回綁定到該行的值?綁定到字符串數組的gridview的dataKeyName是什麼?
您不能,唯一的屬性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 Forums由vtcoder。
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。