简体   繁体   中英

Populating RadiobuttonList dynamically

I have quite a few radiobuttonLists in my ASP.net webform. I am dynamically binding them using the method shown below:

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();
            }
        }

Now, I want to Display only the first Letter of the DataTextField for the RadioButton Item Text.

For example if the Value is Good I just want to Display G. If it Fair I want to display F.

How do I do this in C#

Thanks

You can't do what you want when you do the binding, so you have 2 options:

  1. Modify the data you get from the table, before you do the binding.

  2. After binding, go through each item and modify its Text field.

So, it you want to display "only the first Letter of the DataTextField for the RadioButton Item Text", you can do:

currentRadioButtonList.DataSource = currentDt;
currentRadioButtonList.DataTextField = strTxtField;
currentRadioButtonList.DataValueField = txtValueField;
currentRadioButtonList.DataBind();

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

If I misunderstood you and you want to display the first letter of the Value field, you can replace the last two lines with:

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

You could add a property to the type that is being bound (the one that contains Good, Fair, etc.) and bind to this property. If you will always be using the first letter, you could make it like so (adding in null checks, of course):

    public string MyVar { get; set; }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM