将ASP.NET GridView控件绑定到字符串数组 [英] Binding an ASP.NET GridView Control to a string array
问题描述
我正在尝试将一个ASP.NET GridView
控件绑定到一个字符串
数组,我得到以下项目:
I am trying to bind an ASP.NET GridView
control to an string
array and I get the following item:
在所选的
数据源中找不到名称为
'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屋!