Mark
Mark

Reputation: 209

How to check if checkbox is selected on datagrid on button click

This is the Xaml Code for a datagrid and checkbox item being added to the first row of the datagrid. I need a way of identifying the selected row of the datagrid when the checkbox is checked.

XAML

<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" AutoGenerateColumns="True" Name="MedicationDatagrid" Width="{Binding GroupBox}" Background="White" Height="200" >
    <DataGrid.Columns>
        <DataGridTemplateColumn >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox Name="chkCheckinMedication"  />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

C#

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        checkinCheckBox();

    }

    private void checkinCheckBox()
    {

        // find datarow and store data into database            
    }

Upvotes: 2

Views: 1553

Answers (2)

Hutjepower
Hutjepower

Reputation: 1261

A dirty way to fix this, is by using a hidden field around the checkbox, in which you can place an id of your selection... In your codebehind you can than see the value of that row...

Upvotes: 1

Nirmal
Nirmal

Reputation: 934

protected void Button_Click(object sender, EventArgs e)
{
 foreach (GridViewRow itemrow in GridView1.Rows)
 {
   CheckBox cbview = (CheckBox)(itemrow.Cells[0].FindControl("viewdata"));
   if (cbview.Checked)
   {

      string value = GetObjectType(itemrow.Cells[2].Controls[1]);
      Response.Write(value);
   }
 }

private String GetObjectType(Control ctrl)
    {
        switch (ctrl.GetType().Name)
        {
            case "Label":
                return ((Label)ctrl).Text;
            case "TextBox":
                return ((TextBox)ctrl).Text;
        }
        return "";
    }

Upvotes: 0

Related Questions