Search code examples
c#wpfwpfdatagrid

WPF get TextBox Value from datagridtemplatecolumn


Hello guys I am trying to get TextBox Named "txtQty" value from DataGridTemplateColum

Here is the code, Hope someone Helps me....

.XML

     <DataGrid x:Name="dataGridMain">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Id" Binding="{Binding Id}" IsReadOnly="True" Visibility="Hidden"/>
            <DataGridTextColumn Header="Name" Binding="{Binding PName}" IsReadOnly="True"/>
            <DataGridTemplateColumn Header="Qty" >
                 <DataGridTemplateColumn.CellTemplate >
                       <DataTemplate >
                             <StackPanel Orientation="Horizontal">
                                  <TextBox x:Name="txtQty"/>                                                                       
                              </StackPanel>
                       </DataTemplate>
                 </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

I tried using this code

       DataRowView dt = dataGridMain.SelectedItem as DataRowView;

       String value = dt["Qty"].ToString());

Solution

  • After some struggle I found this solution helpful.....

           int i=5; //Set this equal to desired column index.... 
              ContentPresenter myCp = dataGridMain.Columns[i].GetCellContent(dataGridMain.SelectedItem) as ContentPresenter;
            var myTemplate = myCp.ContentTemplate;
            TextBox mytxtbox = myTemplate.FindName("txtQty", myCp) as TextBox;
            MessageBox.Show(mytxtbox.Text);