在我的 WPF 应用程序中,我正在数据网格中浏览数据库。我的代码的重点是将数据网格中选定的单元格内容存储到一些值列表中以供进一步操作。我的代码适用于 12 岁以下的选定项目,但对于更多项目,它会抛出一个 NullRefferenceException
,表示“
Object reference not set to an instance of an object".
谢谢你的帮助。
代码:
List<string> graphValue = new List<string>(dataGrid1.SelectedItems.Count); //create list
IList someList = new ArrayList(dataGrid1.SelectedItems); //define Ilist
DataGridColumn dataGridCol = dataGrid1.Columns[listBox1.SelectedIndex];
//select column whom i wana collect data
if (dataGrid1.SelectedItems != null) //when selection applied..
{
for (int i = 0; i < dataGrid1.SelectedItems.Count; i++) //go row by row in selected column above
{
try
{
id = ((TextBlock)dataGridCol.GetCellContent(someList[i])).Text.ToString(); //save cell content to string
graphValue.Add(id); //add value to Ilist
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message, "error"); }
}
}
}
最佳答案
这个简单的代码可能对你有帮助首先我们将循环遍历 Data-grid 的每条记录然后通过提供 Row 和 Column as.. 循环选择特定的单元格/列数据
for(int row =0; row < dg_CountInventory.Rows.Count; row ++)
{
TextBlock b = dg_CountInventory.Columns[1].GetCellContent(dg_CountInventory.Items[row ]) as TextBlock;
}
关于c# - 从指定列和行中的数据网格收集数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15259354/