You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GridView中显示字符串数组元素?代码无数据显示问题求助

问题分析与解决方法

你的代码之所以没效果,核心原因是**GridView1.Rows.Count为0**——此时GridView里没有任何数据行,循环条件不成立,代码根本没执行。下面给出两种可行的解决方式:

方式一:手动创建行并添加内容

直接遍历字符串数组,为每个元素创建对应的GridView行和单元格,再添加到GridView中:

string[] r = {"item1","item2", "item3"};

// 清空原有行(可选,根据需求决定)
GridView1.Rows.Clear();

foreach (string item in r)
{
    // 创建数据行
    GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
    // 创建单元格并赋值
    TableCell cell = new TableCell();
    cell.Text = item;
    // 将单元格加入行,行加入GridView
    row.Cells.Add(cell);
    GridView1.Rows.Add(row);
}

方式二:通过数据源绑定(推荐)

GridView的设计初衷是绑定数据源生成行,这种方式更符合ASP.NET的规范,也更易维护:

  1. 在前端页面配置GridView的列(如果不需要自动生成列):
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <!-- 绑定字符串元素本身,DataField用"." -->
        <asp:BoundField DataField="." HeaderText="内容" />
    </Columns>
</asp:GridView>
  1. 后端绑定数据源:
string[] r = {"item1","item2", "item3"};

// 将数组转为可绑定的List
var dataSource = r.ToList();
// 绑定并渲染
GridView1.DataSource = dataSource;
GridView1.DataBind();

内容的提问来源于stack exchange,提问作者user20465780

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:50:33