首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 擴充 GridView 新增 RadioButton 單選欄位

     編輯:ASP.NET 基礎

自訂 DataControlField 元件

繼承 DataControlField 實作 RadioButtonSelectField,支援:

  • RadioButtonGroupName:單選群組名稱,預設取 GridView ClientID。
  • RadioButtonCssClass:自訂樣式類別。
  • DataField:綁定資料欄位作為 value,未指定時用 RowIndex。
  • DataFormatString:格式化顯示值。
  • 自動處理 PostBack 後保持選取狀態。

核心程式碼

[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
public class RadioButtonSelectField : DataControlField
{
    public string RadioButtonGroupName { get; set; }
    public string RadioButtonCssClass { get; set; }
    public string DataField { get; set; }
    public string DataFormatString { get; set; }

    protected override DataControlField CreateField() => this;

    public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
    {
        base.InitializeCell(cell, cellType, rowState, rowIndex);
        if (cellType == DataControlCellType.DataCell)
        {
            var lit = new Literal();
            if (string.IsNullOrEmpty(DataField))
                SetLiteralHtml(lit, rowIndex.ToString());
            else
                lit.DataBinding += Literal_DataBinding;
            cell.Controls.Add(lit);
        }
    }

    void Literal_DataBinding(object sender, EventArgs e)
    {
        var lit = (Literal)sender;
        var cell = lit.Parent as TableCell;
        var container = lit.NamingContainer;
        bool found;
        object dataItem = DataBinder.GetDataItem(container, out found);
        if (!found) return;

        string val = DataField.Contains(".")
            ? DataBinder.Eval(dataItem, DataField, DataFormatString).ToString()
            : DataBinder.GetPropertyValue(dataItem, DataField, DataFormatString).ToString();

        SetLiteralHtml(lit, val);
    }

    void SetLiteralHtml(Literal lit, string dataValue)
    {
        string group = string.IsNullOrEmpty(RadioButtonGroupName)
            ? lit.Parent.Parent.Parent.Parent.ID
            : RadioButtonGroupName;
        string css = string.IsNullOrEmpty(RadioButtonCssClass) ? "" : $"class=\"{RadioButtonCssClass}\"";
        bool selected = false;
        string posted = lit.Page.Request[group];
        if (!string.IsNullOrEmpty(posted) && string.Equals(posted, dataValue, StringComparison.OrdinalIgnoreCase))
            selected = true;

        lit.Text = $"<input type=\"radio\" name=\"{group}\" value=\"{dataValue}\" {css} {(selected ? "checked" : "")} />";
    }
}

使用方式

<cc1:RadioButtonSelectField DataField="UserID" RadioButtonGroupName="grpUser" HeaderText="選取" />

優點

  • 原生 GridView 整合,支援分頁、排序、資料繫結事件。
  • 單選狀態自動還原,無需手動管理 ViewState。
  • 可重複使用於多個專案。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved