views:

30

answers:

2

Hello, 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

+1  A: 

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);
Dan Dumitru
Dan Sorry, it is not working the strTxtField Value is "VAL_ID" thats why it is showing V for all the values. Where as VAL_ID is the database table field but not the actual value.
acadia
@acadia - I don't quite understand what you're saying. With your original code (so without my foreach) you get "VAL_ID" for all the values in the RadioButtonList?
Dan Dumitru
@acadia - Also, see my edit.
Dan Dumitru
A: 

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); }
    }
Mark Avenius