WPF get TextBox Value from datagridtemplatecolumn

有些话、适合烂在心里 提交于 2020-04-18 05:01:06

问题


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());

回答1:


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);



回答2:


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



来源:https://stackoverflow.com/questions/52745984/wpf-get-textbox-value-from-datagridtemplatecolumn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!