绑定到字符串数组的gridview的dataKeyName是什么?

时间:2009-02-02 03:23:37

标签: asp.net gridview

任何人都可以给我一个简短的片段,给定一个最初绑定到一个简单字符串数组的GridView,并给定一个GridViewRow行,它将返回绑定到该行的值吗?

1 个答案:

答案 0 :(得分:4)

你不能,System.String唯一的属性是Length,而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。