iterating through rows of a datagrid

纵饮孤独 提交于 2019-12-10 10:39:28

问题


I am trying to extract values from a datagrid, by iterating through all the rows of the datagrid

    foreach (DataRow drv in PGIPortfolio.Items)
    {
    // DataRow row = drv.Row;

    string acname = drv["Portfolio"].ToString();
string paramt = drv["Par Amount"].ToString();
MessageBox.Show(acname);

}

But it is giving me an InvalidCastException at DataRow drv. Could someone tell me what changes I should make so it works? The datagrid has a binding, and it is being populated by a stored procedure from ms sql 2008 database


回答1:


Use a DataGridRow not a DataRow they are a different objects

foreach (DataGridRow drv in PGIPortfolio.Items)

However it is not clear what Items is in this context. Assuming that PGIPortfolio is the DataGridView then your loop should be written as

foreach (DataGridRow drv in PGIPortfolio.Rows)

EDIT I assumed that you was using the DataGridView control in WinForms, not the WPF DataGrid In this case then the correct approach is to use the ItemsSource property.
Please try this code....

    var itemsSource = PGIPortfolio.ItemsSource as IEnumerable;
    if (itemsSource != null)
    {
        foreach (var item in itemsSource)
        {
            var row = PGIPortfolio.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
            if (row != null) 
            {
               .....
            }

        }
    }



回答2:


foreach(DataGridViewRow r in dataGridView1.Rows)



来源:https://stackoverflow.com/questions/16863531/iterating-through-rows-of-a-datagrid

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