views:

73

answers:

1

I have a Silverlight DataGrid control inside which I have a textbox and a button control.

It is as under

<dg:DataGrid x:Name="myGrid" AutoGenerateColumns="False">
  <dg:DataGrid.Columns>

 <dg:DataGridTemplateColumn Header="Name" Width="100">
    <dg:DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
        <TextBox Text="{Binding Name}" x:name="txtName"/>
      </DataTemplate>
    </dg:DataGridTemplateColumn.CellTemplate>
  </dg:DataGridTemplateColumn>

  <dg:DataGridTemplateColumn Header="Age" Width="100">
    <dg:DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
        <TextBox Text="{Binding Age}" x:name="txtAge"/>
      </DataTemplate>
    </dg:DataGridTemplateColumn.CellTemplate>
  </dg:DataGridTemplateColumn>

      <dg:DataGridTemplateColumn Header="Action" Width="100">
    <dg:DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
        <Button x:Name="btnCilck" Content="Click" Click="btnClick_Click />
      </DataTemplate>
    </dg:DataGridTemplateColumn.CellTemplate>
 </dg:DataGridTemplateColumn>

  </dg:DataGrid.Columns>
</dg:DataGrid>

What I want to do is that at runtime I want to fetch the textbox value (txtName) for the row selected.

I mean, say the grid has 10 rows(i.e. 10 textbox's in that particular column; say Column Name) and 10 Buttons in say Action column(let's name it like that).

Now when I click on the 5th rows Click button, I want to get the value from the textbox present in that row.

Thanks in advance.

+6  A: 

In the click event handler you can examine the sender's (Button's) DataContext, which will be the item represented by that row and will have the properties Name, Age etc.; you can get the property which is bound to the textbox.

A better design, assuming you designed your app with MVVM, is to have an ICommand in the ViewModel and bind the Button's Command property to that ICommand. In that case you can bind something to the CommandParameter of the button and receive it in the ICommand handler - either the DataContext itself with {Binding} or the actual property you're interested in.

Edit: sorry about going on with the Command bindings, they're not readily available in SL3; there are ways around it though, google it if you're interested. The commanding pattern will much better encapsulate the actions across your application.

There are actually ways to get to the actual contents of the grid cells, but I wouldn't recommend it, as it will come with a lot of overhead and will be fragile in case any of the templates change; it's much better to work with the actual data and leave the controls to do their jobs through bindings.

Alex Paven
+1 For the first paragraph, simple, straighforward and pragmatic.
AnthonyWJones