如何获取datagridview中的所有行?
Posted
技术标签:
【中文标题】如何获取datagridview中的所有行?【英文标题】:How to get all rows in datagridview? 【发布时间】:2019-10-25 06:10:30 【问题描述】:我有 datagridview 与名为 DGItem 的类绑定,我通过 linq 查询获取 datagrid 的值我想获取所有这些值
试图从 DGItem 中获取它,但只有我得到的最后一个值
CollegeContext cd = new CollegeContext();
Teacher teaherCB = _TeachersComboBox.SelectedItem as Teacher;
var query = (from sc in cd.SubjectTeachers
join s in cd.Subjects on sc.IdSubject equals s.Id
join t in cd.Teachers on sc.IdTeacher equals t.Id
join wh in cd.WorkHours on t.IdWorkHours equals wh.Id
join b in cd.Branches on sc.IdBranch equals b.Id
where sc.IdTeacher== teaherCB.Id
select new DGItem
Name = t.Name,
Rank = wh.Rank,
HoursOfquerm = wh.HoursOfQuorum,
Namesub = s.Name,
Academic = s.Academic,
Virtual = s.Virtual,
Exprement = s.Exprement,
TotalHour = s.TotalHours
).ToList();
IstmaraB.ItemsSource = query;
public class DGItem
public String Name get; set;
public String Rank get; set;
public int? HoursOfquerm get; set;
public String Namesub get; set;
public int? Academic get; set;
public int? Virtual get; set;
public int? Exprement get; set;
public int? TotalHour get; set;
我的 wpf 是:
<Button Content="select all" HorizontalAlignment="Left" Margin="11,382,0,0" VerticalAlignment="Top" Width="94" Click="Button_Click"/>
<DataGrid x:Name="IstmaraB" HorizontalAlignment="Left" AutoGenerateColumns="False" IsReadOnly="True" Height="327" EnableRowVirtualization="True" ItemsSource="Binding " FlowDirection="RightToLeft" Margin="110,147,0,0" VerticalAlignment="Top" Width="652" RowDetailsVisibilityMode="VisibleWhenSelected">
<DataGrid.Columns>
<DataGridTextColumn Binding="Binding Name" Header="الاسم" Width="auto"/>
<DataGridTextColumn Binding="Binding Rank" Header="الدرجة" Width="auto"/>
<DataGridTextColumn Binding="Binding HoursOfquerm" Header="النصب القانوني" Width="auto"/>
<DataGridTextColumn Binding="Binding Namesub" Header="المواد التي يقوم بتدريسها" Width="auto"/>
<DataGridTextColumn Binding="Binding Academic" Header="نظري" Width="auto"/>
<DataGridTextColumn Binding="Binding Virtual" Header="عملي" Width="auto"/>
<DataGridTextColumn Binding="Binding Exprement" Header="تمارين" Width="auto"/>
<DataGridTextColumn Binding="Binding TotalHour" Header="مجموع" Width="auto"/>
</DataGrid.Columns>
</DataGrid>
我试图这样做:
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
IstmaraB.SelectAll();
if (IstmaraB.SelectedItems.Count > 0)
for (int i = 0; i < IstmaraB.SelectedItems.Count; i++)
System.Data.DataRowView selectedFile = (System.Data.DataRowView)IstmaraB.SelectedItems[i];
【问题讨论】:
你试过像foreach(DGItem item in IstmaraB.ItemsSource)
这样的事情吗?
认为这可能对您有所帮助***.com/a/15686971/1966993
【参考方案1】:
我很确定你的错误在于这一行
System.Data.DataRowView selectedFile = (System.Data.DataRowView)IstmaraB.SelectedItems[i];
当我阅读它时,它只会返回最后发生的任何事情。我也不确定您所说的“获取”是什么意思。您的意思是放入数组或列表中吗?如果这就是你想要的,你可以简单地使用上面的行在数据网格中填充一个包含值的数组,就像这样,
MyArray[i] = IstmaraB.SelectedItems[i];
如果这不是你的,你可能需要澄清。
【讨论】:
以上是关于如何获取datagridview中的所有行?的主要内容,如果未能解决你的问题,请参考以下文章