Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add Check Box in Datagrid WPF c#

Hi i want to add check box in datagrid view.i have writen test code but fails. What i am trying to do is Add a CheckBox in datagrid with the items i add into it with select all and select none option.

I donot know how to do it so i need some help.I am confused with a thing that if we add then dynamically how would we track which checkbox was checked or un checked.

I have current code

    public partial class MainWindow : Window
    {
        List<checkedBoxIte> item = new List<checkedBoxIte>();
        public MainWindow()
        {
            InitializeComponent();
            for (int i = 0; i < 5; i++)
            {
                checkedBoxIte ite = new checkedBoxIte();
                ite.sr = i.ToString();
                ite.ch = new CheckBox();
                item.Add(ite);
            }
            dataGrid1.ItemsSource = item
        }
    }
    public class checkedBoxIte
    {
       public string sr {get;set;}
       public CheckBox ch { get; set; }
    }

but i know it is stupidest thing to add checkbox like this but it was just a try Above class contains two attributes later on it would have more but all will be strings

like image 862
Afnan Bashir Avatar asked Mar 07 '11 19:03

Afnan Bashir


1 Answers

WPF doesn't know how to deal with your checkedBoxIte items. I suggest you to change your class as follows:

public class checkedBoxIte
{
   public string MyString {get;set;}
   public bool MyBool { get; set; }
}

And then to set the columns of your DataGrid in this way:

<DataGrid AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="MyString" Binding="{Binding MyString}" />
        <DataGridCheckBoxColumn Header="MyBool" Binding="{Binding MyBool}" />
    </DataGrid.Columns>
</DataGrid>

Now you can set the ItemsSource:

for (int i = 0; i < 5; i++)
{
    checkedBoxIte ite = new checkedBoxIte();
    ite.MyString = i.ToString();
    item.Add(ite);
}
dataGrid1.ItemsSource = item;
like image 189
as-cii Avatar answered Nov 01 '22 00:11

as-cii