1

我的 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# 中执行此操作

谢谢

4

2 回答 2

3

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

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

  2. 绑定后,遍历每个项目并修改其文本字段。

因此,如果您想显示“仅显示 RadioButton 项目文本的 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);
于 2010-10-12T18:14:19.580 回答
0

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

    public string MyVar { get; set; }

    public string MyVarFirstChar
    {
        get { return MyVar.Substring(0, 2); }
    }
于 2010-10-12T18:26:01.330 回答