Click here to Skip to main content
16,016,562 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here i am binding a value to the datagrid as show given below

XML
<DataGrid Grid.Row="1" Name="dgDept" IsReadOnly="True" AutoGenerateColumns="False" BorderBrush="Black" BorderThickness="1 1 1 1" Margin="10,15,10,0" MouseDoubleClick="OndgDeptMouseDoubleClick" IsEnabled="True"  PreviewKeyDown="dgDept_KeyDown" >
<DataGrid.Columns>
<DataGridTextColumn Header="Status" Width="*" Binding="{Binding Status}"/>
</DataGrid.Columns>
</DataGrid>


C#
var data=dbobj.GetDataFromDB("Select Status from tblDept");
dgDept.ItemsSource=data;


Status has 0,1,2,3 values.Now my problem is how can i bind text as one,two three,four to datagrid instead of 0,1,2,3

Any idea to achieve this?
Posted
Updated 25-Nov-13 15:51pm
v2

1 solution

Hi,

you can use IValueConverter as below. I have pasted here a example have a look.

IValueConverter convertor Reference in XAML

XML
xmlns:convertor="clr-namespace:ApplicationShell"


Add Window Resource

XML
<Window.Resources>
    <convertor:InttoString x:Key="inttoString"/>
</Window.Resources>


My XAML

XML
<datagrid x:name="studentDG" height="150" autogeneratecolumns="False" xmlns:x="#unknown">
                    <datagrid.columns>
                        <datagridtextcolumn binding="{Binding IDs, Converter={StaticResource inttoString}}" header="ID" />
                    </datagrid.columns>
                </datagrid>


My Code behind

C#
List<teststu> IDs = new List<teststu>();
           IDs.Add(new TestStu { IDs = 1 });
           IDs.Add(new TestStu { IDs = 2 });
           IDs.Add(new TestStu { IDs = 3 });
           IDs.Add(new TestStu { IDs = 4 });
           studentDG.ItemsSource = IDs;


and my IValueConverter

C#
public class InttoString : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            switch (value + "")
            {
                case "1":
                    return "One";
                case "2":
                    return "Two";
                case "3":
                    return "Three";
                case "4":
                    return "Four";
                default:
                    return "Zero";
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }


let me know if you can't understand.
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900