【问题标题】:Populating RadiobuttonList dynamically动态填充 RadiobuttonList
【发布时间】:2010-10-13 03:32:38
【问题描述】:

我的 ASP.net 网络表单中有很多单选按钮列表。我使用如下所示的方法动态绑定它们:

public static void PopulateRadioButtonList(DataTable currentDt, RadioButtonList currentRadioButtonList, string strTxtField, string txtValueField,
            string txtDisplay)
        {
            currentRadioButtonList.Items.Clear();
            ListItem item = new ListItem();
            currentRadioButtonList.Items.Add(item);
            if (currentDt.Rows.Count > 0)
            {
                currentRadioButtonList.DataSource = currentDt;
                currentRadioButtonList.DataTextField = strTxtField;
                currentRadioButtonList.DataValueField = txtValueField;
                currentRadioButtonList.DataBind();
            }
            else
            {
                currentRadioButtonList.Items.Clear();
            }
        }

现在,我只想显示 RadioButton 项文本的 DataTextField 的第一个字母。

例如,如果值很好,我只想显示 G。如果它公平,我想显示 F。

如何在 C# 中做到这一点

谢谢

【问题讨论】:

    标签: c# radiobuttonlist


    【解决方案1】:

    绑定时不能做你想做的事,所以你有2个选择:

    1. 在绑定之前修改从表中获取的数据。

    2. 绑定后,遍历每一项,修改其Text字段。

    所以,如果你想显示“单选按钮项目文本的 DataTextField 的第一个字母”,你可以这样做:

    currentRadioButtonList.DataSource = currentDt;
    currentRadioButtonList.DataTextField = strTxtField;
    currentRadioButtonList.DataValueField = txtValueField;
    currentRadioButtonList.DataBind();
    
    foreach (ListItem item in currentRadioButtonList.Items) 
        item.Text = item.Text.Substring(0, 1);
    

    如果我误解了你,你想显示 Value 字段的第一个字母,你可以将最后两行替换为:

    foreach (ListItem item in currentRadioButtonList.Items) 
        item.Text = item.Value.Substring(0, 1);
    

    【讨论】:

    • Dan 抱歉,strTxtField 的值为“VAL_ID”不起作用,这就是为什么它为所有值显示 V。其中 VAL_ID 是数据库表字段,而不是实际值。
    • @acadia - 我不太明白你在说什么。使用您的原始代码(因此没有我的 foreach),您将获得 RadioButtonList 中所有值的“VAL_ID”?
    【解决方案2】:

    您可以将属性添加到正在绑定的类型(包含 Good、Fair 等的类型)并绑定到该属性。如果你总是使用第一个字母,你可以这样(当然,添加空检查):

        public string MyVar { get; set; }
    
        public string MyVarFirstChar
        {
            get { return MyVar.Substring(0, 2); }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多