Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 绑定到字符串数组的gridview的dataKeyName是什么?_Asp.net_Gridview - Fatal编程技术网

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

Asp.net 绑定到字符串数组的gridview的dataKeyName是什么?,asp.net,gridview,Asp.net,Gridview,有谁能给我一个简短的代码片段,给定一个最初绑定到简单字符串数组的GridView,以及一个GridViewRow行,它将返回绑定到该行的值 您不能,System.String唯一的属性是长度,DataKeyName需要您绑定到的对象的属性。为了回答第二个问题,下面是一个从GridViewRow获取字符串值的示例 在您的ASPX文件中: <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowD

有谁能给我一个简短的代码片段,给定一个最初绑定到简单字符串数组的GridView,以及一个GridViewRow行,它将返回绑定到该行的值

您不能,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>
唯一合理的解决方法是创建一个具有属性的包装器类。或者,如果您使用的是.NET3.5,则可以使用LINQ创建一个临时列表,其中只包含作为类属性的值。旁边有一条小路

List name=新列表(新字符串[]{“John”、“Frank”、“Bob”});
var bindableNames=来自名称中的名称
选择新的{Names=name};
GridView1.DataSource=bindableNames.ToList();
然后“Name”将是DataKeyName和BoundField数据字段

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;
    }
}
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();