Search code examples
c#wpfxamldatatabledatagrid

I have an array of string of mails, i want to make a data grid in WPF that contains 2 columns, mail column and checkbox column


I need to create a datagrid in wpf that contains 2 columns, mail, and checkbox, after that I want the mails to show and a checkbox near them, I need a button that makes the following thing: all the checked checkboxes near the mail presented would get an email (i have that function)

I've tried to make a datatable with 2 columns, bool and string and present the mails there, my problem is that when i check the checkboxes near the mail i want to select, when i press the button and run on the datagrid rows, the boolean is still false instead of true and because of that that wont send the email

<DataGrid HorizontalAlignment="Left" Height="227" Margin="43,146,0,0" 
          VerticalAlignment="Top" Width="448" 
          Grid.ColumnSpan="2" Name="Datagrid1" AutoGenerateColumns="False">
     <DataGrid.Columns>
          <DataGridTextColumn Header="mails" Width="*" IsReadOnly="True" Binding="{Binding Path='Text'}"/>
                <DataGridTemplateColumn Header ="send or not" Width="*">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox Name="CheckboxMail"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>

That's the datagrid.

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Selected", typeof(bool))); //this will show checkboxes
dt.Columns.Add(new DataColumn("Text", typeof(string)));   //this will show text

Datagrid1.DataContext = dt;

foreach (string s in mails)
{
    DataRow r = dt.NewRow();
    r[0] = (bool)false;
    r[1] = s;
    dt.Rows.Add(r);
}

Datagrid1.ItemsSource = dt.DefaultView;

Creation of the data table and the data grid

When I push the button:

foreach(DataRowView r in Datagrid1.ItemsSource)
{
    try
    {
        if(((Boolean)r[0]) == true)
        {
            MailMassage ms = new MailMassage((string)r[1]);
            ms.SendMail();
        }
    }

I expect the program to send an email to every mail in the datagrid that in its row there is a checked checkbox, thanks for the help.


Solution

  • Bind the CheckBox in the CellEditingTemplate to the Selected column:

    <DataGridTemplateColumn Header ="send or not" Width="*">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Selected}" />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
        <DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate>
                <CheckBox Name="CheckboxMail" IsChecked="{Binding Selected}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellEditingTemplate>
    </DataGridTemplateColumn>