将 ASP.NET GridView 控件绑定到字符串数组 [英] Binding an ASP.NET GridView Control to a string array
问题描述
我正在尝试将一个 ASP.NET GridView
控件绑定到一个 string
数组,我得到以下项目:
I am trying to bind an ASP.NET GridView
control to an string
array and I get the following item:
具有名称的字段或属性在所选项目上找不到项目"数据来源.
A field or property with the name 'Item' was not found on the selected data source.
我应该为 GridView 控件中 asp:BoundField 列的 DataField 属性使用什么正确值.这是我的源代码:
What is correct value I should use for DataField property of the asp:BoundField column in my GridView control. Here is my source code:
ASPX 页面
<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Item" />
<asp:CommandField ButtonType="Link" ShowSelectButton="true" SelectText="Click Me!" />
</Columns>
</asp:GridView>
背后的代码:
string[] MyArray = new string[1];
MyArray[0] = "My Value";
MyGridView.DataSource = MyArray;
MyGridView.DataBind();
更新
我需要将 AutoGenerateColumns
属性设置为 false
,因为我需要生成额外的 asp:CommandField
列.我已经更新了我的代码示例以反映这种情况
I need to have the AutoGenerateColumns
attribute set to false
because I need to generate additional asp:CommandField
columns. I have updated my code sample to reflect this scenario
推荐答案
一种方法是将一个具有单个命名字段的类传递给它.这样,您就可以为其命名.
One method is to pass it a class with a single, named field. That way, you can give it a name.
public class GridRecord
{
public string MyValue { get; set; }
}
然后将您的字符串数组转换为类的列表
Then convert your string array to a list of the class
string[] MyArray = new string[1];
MyArray[0] = "My Value";
List<GridRecord> MyList = (
from ar in myArray
select new GridRecord
{
MyValue = ar
}).ToList();
MyGridView.DataSource = MyList;
MyGridView.DataBind();
现在您可以命名您的 DataField 属性
Now you can name your DataField property
<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="MyValue" />
</Columns>
</asp:GridView>
这篇关于将 ASP.NET GridView 控件绑定到字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!