简体   繁体   中英

How to get checked row values in WPF Gridview

I have created gridview in WPF with two columns. One for DataGridTextColumn and another one is DataGridCheckBoxColumn.

<DataGrid AutoGenerateColumns="False" Name="dataGrid1">

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

Now, I want to get the checked items text value,

var SelectedList = new List<checkedBoxIte>();
            StringBuilder aa = new StringBuilder();
            for (int i = 0; i < dataGrid1.Items.Count; i++)
            {
                var item = dataGrid1.Items[i];
                var mycheckbox = dataGrid1.Columns[1].GetCellContent(item) as CheckBox;
                var myTextBox = dataGrid1.Columns[0].GetCellContent(item) as TextBox;
                if ((bool)mycheckbox.IsChecked)
                {
                    SelectedList.Add(item[i]);
                    //aa.Append(myTextBox.Text);
                }
            }

How, can i do this.

You should not be using a TextBox , you should use a TextBlock instead, because that's what your DataGridView actually contains in WPF .

So change your code like this:

var SelectedList = new List<checkedBoxIte>();
StringBuilder aa = new StringBuilder();
for (int i = 0; i < dataGrid1.Items.Count; i++)
{
    var item = dataGrid1.Items[i];
    var mycheckbox = dataGrid1.Columns[1].GetCellContent(item) as CheckBox;
    var myTextBlock = dataGrid1.Columns[0].GetCellContent(item) as TextBlock;
    if ((bool)mycheckbox.IsChecked)
    {
        SelectedList.Add(item[i]);
        aa.Append(myTextBlock.Text);
    }
}

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