9

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

1 Answer 1

23

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;
Sign up to request clarification or add additional context in comments.

4 Comments

Its working perfectly ok but i have some issues like that first of all there are 4 colums appearing mean repeats2.How can we fire event or check which checkbox is this?
Well, I don't think that is normal that there are four columns. Are you sure you have set AutoGenerateColumns to False?
it was true.Working now.and what can i do for the second part detect checked row
Attach an handler to DataGridCellEditEnding and then extract the row from Row property of the EventArgs. Alternatively you could implement INotifyPropertyChanged on your class and then see when a CheckBox is checked directly from there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.