我希望在文本框中选择数据网格。
我试过这段代码
private void datagrid1_SelectionChange(object Sender, RoutedEventArg e)
{
var selectedrow = datagrid1.selectedItem as datarowview;
var id = selectedrow["Tagid"]; // Here I get error that object reference is not set is an instance of an object
string s = conver.tostring(id);
txttextbox1.text= s;
}
工作正常。
但是当我刷新(或重新加载)datagrid1
时,selectionChange会抛出错误:
对象引用不是对象的实例
答案 0 :(得分:0)
在你的XAML中
<DataGrid Name="MyGrid" AutoGenerateColumns="False" SelectionChanged="DataGrid_Details_SelectionChanged">
并在.cs
文件中添加
private void DataGrid_Details_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
var row_list = GetDataGridRows(MyGrid);
foreach (DataGridRow single_row in row_list)
{
if (single_row.IsSelected == true)
{
//Get your value over here
}
}
}
catch { }
}
public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row) yield return row;
}
}