0

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());
moneeb
  • 132
  • 13

2 Answers2

3

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);
moneeb
  • 132
  • 13
0

My guess is that you are trying to access the selected row here is the answer for that https://stackoverflow.com/a/3913791/1449779 also don't forget to bind the text box as DonBoitnott comment

dpineda
  • 2,401
  • 27
  • 25
  • Actually I am trying to access TextBox from Selected Row. And text box is in DataGridTemplateColum – moneeb Oct 10 '18 at 18:27
  • Did you try with TwoWay Binding: – dpineda Oct 10 '18 at 19:22
  • Yes dear I did. but this way I only can get cell value not texbox value..... DataRowView dt = dataGridMain.SelectedItem as DataRowView; String value = dt["Qty"].ToString()); – moneeb Oct 10 '18 at 19:26
  • what about this one https://stackoverflow.com/a/7963771/1449779 but you will have to remove the stacklayout or cast first as stacklyout and get the textbox inside – dpineda Oct 10 '18 at 19:43
  • dpineda: I have followed the method from this link https://stackoverflow.com/a/7963771/1449779 But it gives the error "Object reference not set to an instance of an object." – moneeb Oct 11 '18 at 05:33