Infragistics WebDataGrid get value from a selected row by column name: VB.net to C# conversion

StackOverflow https://stackoverflow.com/questions/13974934

  •  11-12-2021
  •  | 
  •  

質問

I'm in the process of converting a website with codebehind in VB.NET to C#. The only real problem I'm having is getting data from an Infragistics WebDataGrid row by column name in the RowSelectionChanged event.

Example VB.NET code:

If Me.WebDataGrid1.Behaviors.Selection.SelectedRows(0).DataItem("Status").ToString <> "Released" Then
        '"Status" is the column name
End If

I figured changing it to this would pretty much do it, but to no avail.

if (this.WebDataGrid1.Behaviors.Selection.SelectedRows[0].DataItem["Status"].ToString() != "Released") { 
        //do stuff
}

Specifically the error I get is, Cannot apply indexing with [] to an expression of type 'object', which I'm pretty positive is referring to the DataItem["Status"] part.

How do I go about getting the value from the selected row for a column specified by name?

UPDATE: I found a solution, which is in the answers below, but it could probably be done better. I'll gladly accept a different answer if a better one comes along.

役に立ちましたか?

解決 2

All that is missing from your C# line is a cast for this.WebDataGrid1.Behaviors.Selection.SelectedRows[0].DataItem to DataRowView. For example the following would work:

if (((DataRowView)this.WebDataGrid1.Behaviors.Selection.SelectedRows[0].DataItem)["Status"].ToString() != "Released")
{
        //do stuff
}

Note that the following may be easier to read:

DataRowView drv = (DataRowView) this.WebDataGrid1.Behaviors.Selection.SelectedRows[0].DataItem;
if (drv["Status"].ToString() != "Released")
{
    //do stuff
}

I am assuming that the VB code that you are converting from worked because Option Strict wasn't set so the conversion between Object and DataRowView didn't need to be done explicitly.

他のヒント

I found a solution that works here, but it feels rather roundabout.

GridRecord selectedRow = e.CurrentSelectedRows[0];
DataRowView dataItem = (DataRowView)selectedRow.DataItem;
DataRow dataRow = dataItem.Row;
object[] valueArray = dataRow.ItemArray;
int columnIndex = WebDataGrid1.Columns["Status"].Index;
string statusValue = selectedRow.Items[columnIndex].Value.ToString();

if (statusValue != "Released") {
    //do stuff
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top