【问题标题】:gridview data binding itemptemplate fieldgridview 数据绑定 itemptemplate 字段
【发布时间】:2016-01-09 00:17:01
【问题描述】:

我有一个从数据库收集数据的数据网格视图。网格有 4 列。其中一列是城市名称。在sql代码中,我选择的是城市代码而不是城市名称。

我已将此列转换为模板字段。在编辑模式下,我能够放置下拉列表并提供数据绑定,以便用户能够选择城市。

但是在 itemtemplate 模式下我有标签字段。我如何提供可以从数据库中获取数据的数据绑定?

【问题讨论】:

    标签: asp.net gridview data-binding


    【解决方案1】:

    您可以通过以下方式实现它

    第一种方法
    使用子查询或连接声明您的数据源,例如 SQL 数据源/对象数据源,包括所需的值字段,并在分配其他值时将其分配给标签。

    第二种方法
    将 ItemTemplate 声明为

    <ItemTemplate>
        <asp:Label ID="lblCity" runat="server" Text='<%# LookupCity(DataBinder.Eval(Container.DataItem, "CityCode")) %>'></asp:Label> 
    </ItemTemplate>
    

    在代码隐藏中将 LookupCity 函数声明为

    protected string LookupCity(object idObj)
    {
        string CityCode = idObj.ToString();
        if (string.IsNullOrEmpty(CityCode))
            // return if CityCode is not valid value
            return null;
        // find the corresponding name from SQL Data Source named SQLDS_City
        IEnumerator CityEnum = SQLDS_City.Select(new DataSourceSelectArguments()).GetEnumerator();
        // loop through enum until required value is not found
        while (CityEnum.MoveNext())
        {
            DataRowView row = CityEnum.Current as DataRowView;
            if ((string)row["CityCode"].ToString() == CityCode)
                return string.Concat(row["CityName"].ToString());
        }
        // return code if it is not found in the enum
        return CityCode;
    }
    

    第三种方法
    您也可以对 ItemTemplate 使用 DropDownList 控件。一个例子可以在这里找到Bind-DropDownList-in-ItemTemplate-of-TemplateField-in-ASPNet-GridView。要限制用户更改 ItemTemplate 中的值,您可以将其禁用仅用于显示目的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-17
      相关资源
      最近更新 更多