Click here to Skip to main content
15,851,387 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

i have a datagrid with a columns name, age and gender. if i double click on a row , that rows details should populate in corresponding textboxes provided. if the gender is male, male radiobutton should select otherwise famale radio button should select. In the database i saved true for male and false for female. how can i do it using databinding.Everything works but the gender radiobutton is not populating. Please help me...

My xaml code

XML
<Window x:Class="WPFTestProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:converter="clr-namespace:WPFTestProject.Converter"
        Title="MainWindow" Height="484" Width="1116" WindowState="Maximized" Initialized="Window_Initialized">
    <Window.Resources>
        <converter:StringToBooleanConverter x:Key="StringToBool"></converter:StringToBooleanConverter>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="584*" />
            <ColumnDefinition Width="510*" />
        </Grid.ColumnDefinitions>
        <Grid Height="421" Margin="12,12,0,0" Name="grid1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="558">
            <Grid.RowDefinitions>
                <RowDefinition Height="50*" />
                <RowDefinition Height="42*" />
                <RowDefinition Height="44*" />
                <RowDefinition Height="43*" />
                <RowDefinition Height="46*" />
                <RowDefinition Height="45*" />
                <RowDefinition Height="45*" />
                <RowDefinition Height="44*" />
                <RowDefinition Height="62*" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="194*" />
                <ColumnDefinition Width="364*" />
            </Grid.ColumnDefinitions>
            <Label Content="Name:" Height="28" HorizontalAlignment="Left" Margin="0,22,0,0" Name="label1" VerticalAlignment="Top" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="0,27,0,0" Name="NameTextBox" VerticalAlignment="Top" Width="211" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" Grid.Column="1" />
            <Label Content="Father's Name:" Height="28" HorizontalAlignment="Left" Margin="0,14,0,0" Name="label2" VerticalAlignment="Top" Grid.Row="1" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="0,14,0,0" Name="FatherNameTextBox" VerticalAlignment="Top" Width="211" Text="{Binding FatherName, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" Grid.Column="1" Grid.Row="1" />
            <Label Content="DOB:" Height="28" HorizontalAlignment="Left" Margin="0,16,0,0" Name="label3" VerticalAlignment="Top" Grid.Row="2" />
            <DatePicker Height="25" HorizontalAlignment="Left" Margin="0,19,0,0" Name="DOBDatePicker" VerticalAlignment="Top" Width="211" Text="{Binding DOB, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" Grid.Column="1" Grid.Row="2" />
            <Label Content="Gender:" Height="28" HorizontalAlignment="Left" Margin="0,15,0,0" Name="label4" VerticalAlignment="Top" Grid.Row="3" />
            <RadioButton Content="Male" Height="16" Margin="1,27,0,0" Name="MaleRadioButton" VerticalAlignment="Top" IsChecked="{Binding Gender, Mode=TwoWay,UpdateSourceTrigger=LostFocus, Converter={StaticResource StringToBool}, ConverterParameter=Male}" Grid.Column="1" HorizontalAlignment="Left" Width="42" Grid.Row="3" />
            <RadioButton Content="Female" Height="16" HorizontalAlignment="Left" Margin="56,27,0,0" Name="FemaleRadioButton" VerticalAlignment="Top" IsChecked="{Binding Gender, Mode=TwoWay,UpdateSourceTrigger=LostFocus, Converter={StaticResource StringToBool}, ConverterParameter=Female}" Grid.Column="1" Grid.Row="3" />
            <Label Content="State:" Height="28" HorizontalAlignment="Left" Margin="0,18,0,0" Name="label6" VerticalAlignment="Top" Grid.Row="4" />
            <ComboBox Height="23" HorizontalAlignment="Right" Margin="0,23,153,0" Name="StateComboBox" VerticalAlignment="Top" Width="211" Text="{Binding State, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" Grid.Column="1" Grid.Row="4" />
            <Label Content="District:" Height="28" HorizontalAlignment="Left" Margin="1,17,0,0" Name="label5" VerticalAlignment="Top" Grid.Row="5" />
            <ComboBox Height="23" HorizontalAlignment="Right" Margin="0,22,153,0" Name="DistrictComboBox" VerticalAlignment="Top" Width="211" Text="{Binding District, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" Grid.Column="1" Grid.Row="5" />
            <Button Content="Save" Height="23" HorizontalAlignment="Left" Margin="1,22,0,0" Name="SaveButton" VerticalAlignment="Top" Width="75" Click="SaveButton_Click" Grid.Column="1" Grid.Row="6" />
            <Button Content="Delete" Height="23" HorizontalAlignment="Left" Margin="84,22,0,0" Name="DeleteButton" VerticalAlignment="Top" Width="75" Grid.Column="1" Grid.Row="6" Click="DeleteButton_Click" />
            <Button Content="Refresh" Height="23" HorizontalAlignment="Left" Margin="165,22,0,0" Name="RefreshButton" VerticalAlignment="Top" Width="75" Grid.Column="1" Grid.Row="6" Click="RefreshButton_Click" />
        </Grid>
        <DataGrid AutoGenerateColumns="False" Grid.Column="1" Height="200" HorizontalAlignment="Left" Margin="0,12,0,0" Name="PersonDatagrid" VerticalAlignment="Top" Width="498" MouseDoubleClick="PersonDatagrid_MouseDoubleClick">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Width="100" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Father's name" Width="100" Binding="{Binding FatherName}" />
                <DataGridTextColumn Header="DOB" Width="70" Binding="{Binding DOB, StringFormat=dd/MM/yyyy}" />
                <DataGridTextColumn Header="Gender" Width="50" Binding="{Binding Gender, Converter={StaticResource StringToBool}}" />
                <DataGridTextColumn Header="State" Width="80" Binding="{Binding State}" />
                <DataGridTextColumn Header="District" Width="98" Binding="{Binding District}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>


My converter class

C#
class StringToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((bool)value == false)
            {
                return "Female";
            }
            else
            {
                return "Male";
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (parameter.ToString() == "Male")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }


Row double click event
C#
private void PersonDatagrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.DataContext = PersonDatagrid.SelectedItem as PersonBO;
        }
Posted
Updated 21-Aug-12 21:03pm
v4
Comments
jay_1493 28-Jan-17 0:27am    
please sher above code in xaml.cs file ....

Hi Kunjammu,
You can find the solution here...

XAML Page :

XML
<window x:class="SampleWPFApp.GridWindow" xmlns:x="#unknown">
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Converters="clr-namespace:SampleWPFApp"
        Title="GridWindow" Height="300" Width="300">
    <window.resources>       
        <converters:enumbooleanconverter x:key="EnumGender" xmlns:converters="#unknown" />
    </window.resources>
    <grid>
        <grid.rowdefinitions>
            <rowdefinition height="100" />
            <rowdefinition height="*" />
        </grid.rowdefinitions>
        <grid datacontext="{Binding ElementName=PersonDatagrid,Path=SelectedItem}">
            <grid.rowdefinitions>
                <rowdefinition height="50"></rowdefinition>
                <rowdefinition height="50"></rowdefinition>
                <rowdefinition height="*"></rowdefinition>
            </grid.rowdefinitions>

            <grid.columndefinitions>
                <columndefinition width="100" />
                <columndefinition width="120" />
                <columndefinition width="*" />
            </grid.columndefinitions>
            
            <textblock name="Name" grid.row="0" grid.column="0" text="Name" />
            <textbox name="txtName" grid.row="0" grid.column="1" height="30" margin="10" text="{Binding Name}" />
            
            <textblock name="txtgender" grid.row="1" grid.column="0" text="Gender" />
            <radiobutton groupname="male" content="Male" height="16" margin="1,27,0,0" name="MaleRadioButton" verticalalignment="Top" grid.column="1" horizontalalignment="Left" width="42" grid.row="1">
                         IsChecked="{Binding Converter={StaticResource EnumGender},Path=Gender,Mode=TwoWay,ConverterParameter=Male}"/>
            <radiobutton groupname="female" content="Female" height="16" horizontalalignment="Left" margin="56,27,0,0" name="FemaleRadioButton" verticalalignment="Top" grid.column="1" grid.row="1">
                         IsChecked="{Binding Converter={StaticResource EnumGender},Path=Gender,Mode=TwoWay,ConverterParameter=Female}"/>


        </radiobutton></radiobutton></grid>

        <datagrid autogeneratecolumns="False" height="200" horizontalalignment="Left" grid.row="1" margin="0,12,0,0" name="PersonDatagrid" verticalalignment="Top" width="498">
            <datagrid.columns>
                <datagridtextcolumn header="Name" width="100" binding="{Binding Name}" />
                <datagridtextcolumn header="Gender" width="150" binding="{Binding Gender}" />
               
            </datagrid.columns>
        </datagrid>
    </grid>
</window>


Code Behind Page :

C#
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SampleWPFApp
{
    /// <summary>
    /// Interaction logic for GridWindow.xaml
    /// </summary>
    public partial class GridWindow : Window
    {
        public GridWindow()
        {
            InitializeComponent();
            PersonDatagrid.ItemsSource = new List<personalinfo> { new   PersonalInfo { Gender =  Genders.Female , Name = "Mariya"},
                                                                    new PersonalInfo { Gender = Genders.Male , Name = "Martin"}};
        }       
    }

    public class PersonalInfo
    {
        public string Name { get; set; }
        public  Genders Gender { get; set; }
    }

    public enum Genders
    {
        Male = 1,
        Female
    }
}</personalinfo>



Converter class:

C#
public class EnumBooleanConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var ParameterString = parameter as string;
            if (ParameterString == null)
                return DependencyProperty.UnsetValue;

            if (Enum.IsDefined(value.GetType(), value) == false)
                return DependencyProperty.UnsetValue;

            object paramvalue = Enum.Parse(value.GetType(), ParameterString);
            return paramvalue.Equals(value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var ParameterString = parameter as string;
            if (ParameterString == null)
                return DependencyProperty.UnsetValue;

            return Enum.Parse(targetType, ParameterString);
        }

        #endregion
    }



If you find this as useful ...rate it and dont forget to mark as output
 
Share this answer
 
Comments
Kunjammu 22-Aug-12 5:23am    
The above code is great and i created like that and i got the result. But i am populating my datagrid using the following code

_dbHandler.AddParameter("@PersonID", PersonID);
DataSet ds = _dbHandler.GetData("dbo.PersonRetrieve");
var result = from column in ds.Tables[0].AsEnumerable()
select new PersonBO
{
PersonID = Convert.ToInt32(column["PersonID"]),
Name = column["Name"].ToString(),
FatherName = column["FatherName"].ToString(),
State = column["State"].ToString(),
District = column["District"].ToString(),
DOB = Convert.ToDateTime(column["DOB"]),
Gender = Convert.ToBoolean(column["Gender"])
};
PersonDatagrid.ItemsSource=result.

but after doing like you said , a compilation error shows at Gender(cannot implicitely convert the type Genders to boolean.

How can i convert column["Gender"] to the type Genders
Prabhakaran Soundarapandian 22-Aug-12 5:32am    
Gender = Convert.ToBoolean(column["Gender"]) ? Genders.Male :Genders.Female

If you find this as useful ...rate it and dont forget to mark as output
Kunjammu 22-Aug-12 5:37am    
Thank you so much.....its working fine...:D:D:D
Prabhakaran Soundarapandian 22-Aug-12 5:50am    
Welcome...
See my answer over this post..i think your problem is same..
RadioButton Binding in WPF[^]
 
Share this answer
 
Comments
Kunjammu 22-Aug-12 0:48am    
no.i have a datagrid with a column GENDER. when double click on datagrid rows, if the gender is Male , then MaleRadioButton should select
i used IValueConverter like below
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value == false)
{
return "Female";
}
else
{
return "Male";
}
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter.ToString() == "Male")
{
return true;
}
else
{
return false;
}
}

but not working...
ridoy 22-Aug-12 1:39am    
then you need to use..
if (parameter.ToString() == "Male")
{
MaleRadioButton.isChecked=true;
}
Kunjammu 22-Aug-12 2:05am    
this is a seperate class.Radiobutton is not available here
You can use IValueConverter interface to achieve your requirement.
Have a look on this link.
 
Share this answer
 
Comments
Kunjammu 22-Aug-12 0:49am    
i used IValueConverter like below
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value == false)
{
return "Female";
}
else
{
return "Male";
}
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter.ToString() == "Male")
{
return true;
}
else
{
return false;
}
}

but not working...
Prabhakaran Soundarapandian 22-Aug-12 0:53am    
Are you able to debug your code? and your break-point is hitting or not ?..show your XAML code...
Kunjammu 22-Aug-12 1:00am    
yes. i am able to debug. when double click on row breakpoint in Convert hits

<Label Content="Name:" Height="28" HorizontalAlignment="Left" Margin="0,22,0,0" Name="label1" VerticalAlignment="Top" />
<textbox height="23" horizontalalignment="Left" margin="0,27,0,0" name="NameTextBox" verticalalignment="Top" width="211" text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" grid.column="1">
<Label Content="Father's Name:" Height="28" HorizontalAlignment="Left" Margin="0,14,0,0" Name="label2" VerticalAlignment="Top" Grid.Row="1" />
<textbox height="23" horizontalalignment="Left" margin="0,14,0,0" name="FatherNameTextBox" verticalalignment="Top" width="211" text="{Binding FatherName, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" grid.column="1" grid.row="1">
<Label Content="DOB:" Height="28" HorizontalAlignment="Left" Margin="0,16,0,0" Name="label3" VerticalAlignment="Top" Grid.Row="2" />
<datepicker height="25" horizontalalignment="Left" margin="0,19,0,0" name="DOBDatePicker" verticalalignment="Top" width="211" text="{Binding DOB, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" grid.column="1" grid.row="2">
<Label Content="Gender:" Height="28" HorizontalAlignment="Left" Margin="0,15,0,0" Name="label4" VerticalAlignment="Top" Grid.Row="3" />
<radiobutton content="Male" height="16" margin="1,27,0,0" name="MaleRadioButton" verticalalignment="Top" ischecked="{Binding Gender, Mode=TwoWay,UpdateSourceTrigger=LostFocus, Converter={StaticResource StringToBool}, ConverterParameter=Male}" grid.column="1" horizontalalignment="Left" width="42" grid.row="3">
<radiobutton content="Female" height="16" horizontalalignment="Left" margin="56,27,0,0" name="FemaleRadioButton" verticalalignment="Top" ischecked="{Binding Gender, Mode=TwoWay,UpdateSourceTrigger=LostFocus, Converter={StaticResource StringToBool}, ConverterParameter=Female}" grid.column="1" grid.row="3">
<Label Content="State:" Height="28" HorizontalAlignment="Left" Margin="0,18,0,0" Name="label6" VerticalAlignment="Top" Grid.Row="4" />
<combobox height="23" horizontalalignment="Right" margin="0,23,153,0" name="StateComboBox" verticalalignment="Top" width="211" text="{Binding State, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" grid.column="1" grid.row="4">
<Label Content="District:" Height="28" HorizontalAlignment="Left" Margin="1,17,0,0" Name="label5" VerticalAlignment="Top" Grid.Row="5" />
<combobox height="23" horizontalalignment="Right" margin="0,22,153,0" name="DistrictComboBox" verticalalignment="Top" width="211" text="{Binding District, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" grid.column="1" grid.row="5">
<Button Content="Save" Height="23" HorizontalAlignment="Left" Margin="1,22,0,0" Name="SaveButton" VerticalAlignment="Top" Width="75" Click="SaveButton_Click" Grid.Column="1" Grid.Row="6" />
<Button Content="Delete" Height="23" HorizontalAlignment="Left" Margin="84,22,0,0" Name="DeleteButton" VerticalAlignment="Top" Width="75" Grid.Column="1" Grid.Row="6" Click="DeleteButton_Click" />
<Button Content="Refresh" Height="23" HorizontalAlignment="Left" Margin="165,22,0,0" Name="RefreshButton" VerticalAlignment="Top" Width="75" Grid.Column="1" Grid.Row="6" Click="RefreshButton_Click" />

<datagrid autogeneratecolumns="False" grid.column="1" height="200" horizontalalignment="Left" margin="0,12,0,0" name="PersonDatagrid" verticalalignment="Top" width="498" mousedoubleclick="PersonDatagrid_MouseDoubleClick">
<datagrid.columns>
<datagridtextcolumn header="Name" width="100" binding="{Binding Name}">
<datagridtextcolumn header="Father's name" width="100" binding="{Binding FatherName}">
Kunjammu 22-Aug-12 1:01am    
can you able to see my xaml code??
Prabhakaran Soundarapandian 22-Aug-12 1:06am    
Here i cant find your call for Ivalueconverter keyname..

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