简体   繁体   中英

Delete and Edit a datagrid row using checkboxes in WPF C# (Data coming from database)

I am currently new to C#(WPF) and trying to develop a project and stuck on this point. I want to add checkboxes to each row (and a master checkbox in header). The data is coming from my database into datagrid. I want to be able to check a single checkbox at a time and if I click on master checkbox all other checkboxes should get checked as well. I want to be able to perform DELETE, EDIT to a row. DELETE all selected rows too. My Sample code for XMAL is:

 <DataGrid x:Name="dataGrid" CanUserAddRows="False" ColumnWidth="*"  Grid.Row="4" Grid.Column="2" Grid.ColumnSpan="5" Grid.RowSpan="9"></DataGrid>

My Sample code for CS is:

 public void updateDataGrid()
    {
        string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Zeeshan\Documents\zeemobiles.mdf;Integrated Security=True;Connect Timeout=30";

        string query = "Select * from Addphones";

        SqlConnection databaseConnection = new SqlConnection(connectionString);
        SqlCommand commandDatabase = new SqlCommand(query, databaseConnection);
        SqlDataAdapter ad = new SqlDataAdapter(commandDatabase);
        commandDatabase.CommandTimeout = 60;

        // Let's do it !
        try
        {

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

            dataGrid.ItemsSource = dt.DefaultView;

            ad.Update(dt);
        }
        catch (Exception ex)
        {
            // Show any error message.
            MessageBox.Show(ex.Message);
        }
        finally
        {
            databaseConnection.Close();
        }

    }

This is what I have worked out yet from getting help from different webistes.

我在列中添加了复选框,但我不知道如何获取值

Another better approach would be that you get selected Item from DataGridView . And apply operation on that. But for that you would also need to specify the Item Source as well as you will be defining the columns and the data that you'll be binding by using Binding="{Binding id}" in DataGridTextColumn .

For more: https://www.c-sharpcorner.com/UploadFile/009464/how-to-bind-datagrid-in-wpf-using-C-Sharp/

ViewModel

public class ViewModel
{
    public IList<ItemViewModel> DataSource { get; }

    public ICommand EditCommand { get; set; }

    public ICommand DeleteCommand { get; set; }

    private void DeleteCommandExecuteDelegate(object obj)
    {
        foreach (var item in DataSource)
        {
            if (item.IsSelected)
            {
                DataSource.Remove(item);
            }
        }
    }

    private void EditCommandExecuteDelegate(object obj)
    {
        foreach (var item in DataSource)
        {
            if (item.IsSelected)
            {
                item.Property1 = Guid.NewGuid();
            }
        }
    }
}

public class ItemViewModel
{
    public bool IsSelected { get; set; }

    public object Property1 { get; set; }
}

View

<DataGrid x:Name="DataGrid1" ItemsSource="{Binding Path=DataSource}">
    <DataGridTemplateColumn Header="Checked" >
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <CheckBox IsChecked="{binding Path=IsSelected"/>
                </StackPanel>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>    
</DataGrid>

Demo

DataGrid1.DataContext = new ViewModel();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM