locked
bindingsource syntax problem RRS feed

  • Question

  • I am trying to find the correct systax for retrieving a value from a column in a bindingsource list.

    int x = (int)(bindingsource[itemindex]).row["colname"];

    Or

    DataRowView x = (DataRowView)(bindingsource[itemindex]).row["colname"];

    Does not work?

    Thanks.

    p

     


    Paul
    Sunday, February 5, 2012 7:44 AM

Answers

  • Hi Paul,

    In your second example you are casting to the wrong type.
    Let's see a small example:

    DataTable table = new DataTable();
    table.Columns.Add("LastName");
    table.Rows.Add(new object[] { "B.B. King" });
    BindingSource bs = new BindingSource { DataSource = table };
    DataRowView rowView =(DataRowView)bs[0];
    DataRow row = rowView.Row;
    var value = (string) row["LastName"];
    
    

    As you can see, row["LastName"] returns an object of a given column type.
    Casting the object to a DataRowView is simply wrong. You should cast to the correct type, or use DataRowView as in the code snippet above.

    Marcel

    • Marked as answer by PAUL stanley Sunday, February 5, 2012 12:44 PM
    Sunday, February 5, 2012 11:50 AM

All replies

  • Hi Paul,

    In your second example you are casting to the wrong type.
    Let's see a small example:

    DataTable table = new DataTable();
    table.Columns.Add("LastName");
    table.Rows.Add(new object[] { "B.B. King" });
    BindingSource bs = new BindingSource { DataSource = table };
    DataRowView rowView =(DataRowView)bs[0];
    DataRow row = rowView.Row;
    var value = (string) row["LastName"];
    
    

    As you can see, row["LastName"] returns an object of a given column type.
    Casting the object to a DataRowView is simply wrong. You should cast to the correct type, or use DataRowView as in the code snippet above.

    Marcel

    • Marked as answer by PAUL stanley Sunday, February 5, 2012 12:44 PM
    Sunday, February 5, 2012 11:50 AM
  • ok Thanks!
    Paul
    Sunday, February 5, 2012 12:44 PM